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/137/0xa5f27C702C80d71585C26C0d1de9a0fdAAAD2404/sources/contracts/LootBox.sol | * @dev Alternate way to add token ids to a class Note: resets the full list for the class instead of adding each token id/ | function setTokenIdsForClass(
Class _class,
uint256[] memory _tokenIds
) public onlyOperator {
uint256 classId = uint256(_class);
classIsPreminted[classId] = true;
classToTokenIds[classId] = _tokenIds;
}
| 3,748,736 | [
1,
25265,
4031,
358,
527,
1147,
3258,
358,
279,
667,
3609,
30,
20063,
326,
1983,
666,
364,
326,
667,
3560,
434,
6534,
1517,
1147,
612,
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
] | [
1,
1,
1,
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
] | [
1,
225,
445,
22629,
2673,
22581,
12,
203,
565,
1659,
389,
1106,
16,
203,
565,
2254,
5034,
8526,
3778,
389,
2316,
2673,
203,
225,
262,
1071,
1338,
5592,
288,
203,
565,
2254,
5034,
31181,
273,
2254,
5034,
24899,
1106,
1769,
203,
565,
667,
2520,
23890,
474,
329,
63,
1106,
548,
65,
273,
638,
31,
203,
565,
667,
774,
1345,
2673,
63,
1106,
548,
65,
273,
389,
2316,
2673,
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
] |
./full_match/5/0x54FFCE9bE0C17840103e5b28408932A2C6cC7ED4/sources/contracts/BaseRenewalController.sol | Calculate the amount to be given to the owner of the contract. We don't need a balance for the owner of the contract because the owner can withdraw any funds in the contract minus total balances. | uint256 ownerAmount = price * ownerCut / 10000;
| 7,064,053 | [
1,
8695,
326,
3844,
358,
506,
864,
358,
326,
3410,
434,
326,
6835,
18,
1660,
2727,
1404,
1608,
279,
11013,
364,
326,
3410,
434,
326,
6835,
2724,
326,
3410,
848,
598,
9446,
1281,
284,
19156,
316,
326,
6835,
12647,
2078,
324,
26488,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3639,
2254,
5034,
3410,
6275,
273,
6205,
380,
3410,
15812,
342,
12619,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/**
* @title Token contract for Legends of Venari Alpha Passes
* @dev This contract allows the distribution of
* Legends of Venari Passes in the form of a presale and main sale.
*
* Users can mint from Talaw, Vestal, or Azule in either sales.
*
*
* Smart contract work done by lenopix.eth
*/
contract LegendsOfVenariAlphaPass is
ERC721Enumerable,
Ownable,
ReentrancyGuard
{
using ECDSA for bytes32;
using Address for address;
event Mint(
address indexed to,
uint256 indexed tokenId,
uint256 indexed factionId
);
// Faction Ids
uint256 public constant TALAW_ID = 0;
uint256 public constant VESTAL_ID = 1;
uint256 public constant AZULE_ID = 2;
// Minting constants
uint256 public maxMintPerTransaction;
uint256 public MINT_SUPPLY_PER_FACTION;
uint256 public TEAM_SUPPLY_PER_FACTION;
// Current price: 0.0011
uint256 public constant MINT_PRICE = 110000000000000000;
// Keep track of supply
uint256 public talawMintCount = 0;
uint256 public vestalMintCount = 0;
uint256 public azuleMintCount = 0;
// Sale toggles
bool private _isPresaleActive = false;
bool private _isSaleActive = false;
// Tracks the faction for a token
mapping(uint256 => uint256) factionForToken;
// Presale
mapping(address => bool) private presaleClaimed; // Everyone who got in on the presale can only claim once.
address private signVerifier = 0xf79e8a0d24cF91EE36c8a7e7dB8Aa95fbF7d6a8f;
// Base URI
string private _uri;
// Merkle Root
bytes32 immutable public root;
// Last Token ID starts from the end of Gilded Pass ID
uint256 lastTokenId = 600;
constructor(
uint256 mintSupply,
uint256 teamSupply,
uint256 maxMint,
bytes32 merkleroot
) ERC721("Legends of Venari Alpha Pass", "LVP") {
MINT_SUPPLY_PER_FACTION = mintSupply;
TEAM_SUPPLY_PER_FACTION = teamSupply;
maxMintPerTransaction = maxMint;
root = merkleroot;
}
// @dev Returns the faction of the token id
function getFaction(uint256 tokenId) external view returns (uint256) {
require(_exists(tokenId), "Query for nonexistent token id");
return factionForToken[tokenId];
}
// @dev Returns whether a user has claimed from presale
function getPresaleClaimed(address user) external view returns (bool) {
return presaleClaimed[user];
}
// @dev Returns the enabled/disabled status for presale
function getPreSaleState() external view returns (bool) {
return _isPresaleActive;
}
// @dev Returns the enabled/disabled status for minting
function getSaleState() external view returns (bool) {
return _isSaleActive;
}
// @dev Returns the mint count of a specific faction
function getMintCount(uint256 factionId) external view returns (uint256) {
require(_isValidFactionId(factionId), "Faction is not valid");
if (factionId == TALAW_ID) {
return talawMintCount;
} else if (factionId == VESTAL_ID) {
return vestalMintCount;
} else if (factionId == AZULE_ID) {
return azuleMintCount;
}
return 0;
}
// @dev Allows to set the baseURI dynamically
// @param uri The base uri for the metadata store
function setBaseURI(string memory uri) external onlyOwner {
_uri = uri;
}
// @dev Sets a new signature verifier
function setSignVerifier(address verifier) external onlyOwner {
signVerifier = verifier;
}
// @dev Dynamically set the max mints a user can do in the main sale
function setMaxMintPerTransaction(uint256 maxMint) external onlyOwner {
maxMintPerTransaction = maxMint;
}
// Presale
function presaleMint(
uint256 tokenId,
bytes32[] calldata proof,
uint256 factionId
) external payable {
require(_verify(_leaf(msg.sender, tokenId), proof), "Invalid merkle proof");
require(!presaleClaimed[msg.sender], "Already claimed with this address");
require(_isPresaleActive, "Presale not active");
require(!_isSaleActive, "Cannot mint while main sale is active");
require(_isValidFactionId(factionId), "Faction is not valid");
require(MINT_PRICE == msg.value, "ETH sent does not match required payment");
presaleClaimed[msg.sender] = true;
_handleFactionMint(1, factionId, msg.sender, MINT_SUPPLY_PER_FACTION);
}
function _leaf(address account, uint256 tokenId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(tokenId, account));
}
function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) {
return MerkleProof.verify(proof, root, leaf);
}
mapping(uint256 => bool) partnerNonceUsed;
mapping(address => uint256) basePassNonce;
// @dev Partner Mint - For partners who we allow to batch mint
// @param factionIds The factions associated with the tokens
// @param addresses The addresses that the tokens will be distributed to
// @param sig Server side signature authorizing user to use the presale
function partnerMint(
uint256[] memory factionIds,
uint256 nonce,
bytes memory sig
) external payable nonReentrant {
require(_isPresaleActive, "Presale not active");
require(
(MINT_PRICE * factionIds.length) == msg.value,
"ETH sent does not match required payment"
);
require(!partnerNonceUsed[nonce], "Nonce already used.");
// Verify signature
bytes32 message = getPartnerSigningHash(
msg.sender,
factionIds,
nonce
).toEthSignedMessageHash();
require(
ECDSA.recover(message, sig) == signVerifier,
"Permission to call this function failed"
);
partnerNonceUsed[nonce] = true;
// Mint
for (uint256 i = 0; i < factionIds.length; i++) {
uint256 factionId = factionIds[i];
require(_isValidFactionId(factionId), "Faction is not valid");
_handleFactionMint(1, factionId, msg.sender, MINT_SUPPLY_PER_FACTION);
}
}
// @dev Main sale mint
// @param tokensCount The tokens a user wants to purchase
// @param factionId Talaw: 0, Vestal: 1, Azule: 2
function mint(uint256 tokenCount, uint256 factionId)
external
payable
nonReentrant
{
require(_isValidFactionId(factionId), "Faction is not valid");
require(_isSaleActive, "Sale not active");
require(tokenCount > 0, "Must mint at least 1 token");
require(tokenCount <= maxMintPerTransaction, "Token count exceeds limit");
require(
(MINT_PRICE * tokenCount) == msg.value,
"ETH sent does not match required payment"
);
_handleFactionMint(tokenCount, factionId, msg.sender, MINT_SUPPLY_PER_FACTION);
}
// @dev Private mint function reserved for company.
// THIS SHOULD ONLY BE DONE AFTER THE MAIN SALE HAS FINISHED
// 50 of each faction is reserved.
// @param recipient The user receiving the tokens
// @param tokenCount The number of tokens to distribute
// @param factionId Talaw: 0, Vestal: 1, Azule: 2
function mintToAddress(
address[] memory addresses,
uint256[] memory factionIds
) external onlyOwner {
require(factionIds.length == addresses.length, "Faction ids much have the same length as addresses");
// Mint
for (uint256 i = 0; i < factionIds.length; i++) {
uint256 factionId = factionIds[i];
require(_isValidFactionId(factionId), "Faction is not valid");
_handleFactionMint(1, factionId, addresses[i], MINT_SUPPLY_PER_FACTION + TEAM_SUPPLY_PER_FACTION);
}
}
function redeemBasePass(
uint256 factionId,
bytes memory sig
) external {
require(_isValidFactionId(factionId), "Faction does not exist");
// Verify signature
bytes32 message = getBasePassSigningHash(
msg.sender,
factionId
).toEthSignedMessageHash();
require(
ECDSA.recover(message, sig) == signVerifier,
"Permission to call this function failed"
);
basePassNonce[msg.sender]++;
if (factionId == TALAW_ID) {
talawMintCount++;
} else if (factionId == VESTAL_ID) {
vestalMintCount++;
} else if (factionId == AZULE_ID) {
azuleMintCount++;
}
_mint(msg.sender, 1, factionId);
}
// @dev Allows to enable/disable minting of presale
function flipPresaleState() external onlyOwner {
_isPresaleActive = !_isPresaleActive;
}
// @dev Allows to enable/disable minting of main sale
function flipSaleState() external onlyOwner {
_isSaleActive = !_isSaleActive;
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function getPartnerSigningHash(
address sender,
uint256[] memory factionIds,
uint256 nonce
) public pure returns (bytes32) {
return
keccak256(
abi.encodePacked(sender, factionIds, nonce)
);
}
function getBasePassSigningHash(
address sender,
uint256 factionId
) public view returns (bytes32) {
return
keccak256(
abi.encodePacked(sender, factionId, basePassNonce[sender])
);
}
function _baseURI() internal view override returns (string memory) {
return _uri;
}
function _handleFactionMint(
uint256 tokenCount,
uint256 factionId,
address recipient,
uint256 totalSupply
) private {
if (factionId == TALAW_ID) {
require(talawMintCount < totalSupply, "This faction has been fully minted");
require((talawMintCount + tokenCount) <= totalSupply, "Cannot purchase more than the available supply");
talawMintCount += tokenCount;
} else if (factionId == VESTAL_ID) {
require(vestalMintCount < totalSupply, "This faction has been fully minted");
require((vestalMintCount + tokenCount) <= totalSupply, "Cannot purchase more than the available supply");
vestalMintCount += tokenCount;
} else if (factionId == AZULE_ID) {
require(azuleMintCount < totalSupply, "This faction has been fully minted");
require((azuleMintCount + tokenCount) <= totalSupply, "Cannot purchase more than the available supply");
azuleMintCount += tokenCount;
}
_mint(recipient, tokenCount, factionId);
}
function _mint(
address recipient,
uint256 tokenCount,
uint256 factionId
) private {
for (uint256 i = 0; i < tokenCount; i++) {
uint256 tokenId = lastTokenId + i;
_mintWithTokenId(recipient, tokenId, factionId);
}
lastTokenId += tokenCount;
}
function _mintWithTokenId(
address recipient,
uint256 tokenId,
uint256 factionId
) private {
factionForToken[tokenId] = factionId;
emit Mint(recipient, tokenId, factionId);
_safeMint(recipient, tokenId);
}
function _isValidFactionId(uint256 factionId) private pure returns (bool) {
return factionId == TALAW_ID || factionId == AZULE_ID || factionId == VESTAL_ID;
}
}
| @dev Returns the mint count of a specific faction | function getMintCount(uint256 factionId) external view returns (uint256) {
require(_isValidFactionId(factionId), "Faction is not valid");
if (factionId == TALAW_ID) {
return talawMintCount;
return vestalMintCount;
return azuleMintCount;
}
return 0;
}
| 15,826,203 | [
1,
1356,
326,
312,
474,
1056,
434,
279,
2923,
284,
1128,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
2108,
474,
1380,
12,
11890,
5034,
284,
1128,
548,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2583,
24899,
26810,
42,
1128,
548,
12,
507,
349,
548,
3631,
315,
42,
1128,
353,
486,
923,
8863,
203,
203,
565,
309,
261,
507,
349,
548,
422,
399,
1013,
12999,
67,
734,
13,
288,
203,
1377,
327,
268,
287,
2219,
49,
474,
1380,
31,
203,
1377,
327,
331,
395,
287,
49,
474,
1380,
31,
203,
1377,
327,
10562,
725,
49,
474,
1380,
31,
203,
565,
289,
203,
565,
327,
374,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @dev {ERC20} token, including:
*
* - standard ERC20 contract interactions and functions
* - an issuer role that allows for token minting via signed claim tickets,
* which are issued by authorised addresses having the ISSUER_ROLE role.
* - nonce tracking for each address to prevent ticket claim replay
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles.
*
* The account that deploys the contract will be granted the ISSUER_ROLE
* role, as well as the default admin role, which will let it grant
* and revoke ISSUER_ROLE roles to other accounts.
*/
contract XFUND is Context, AccessControl, ERC20 {
bytes32 public constant ISSUER_ROLE = keccak256("ISSUER_ROLE");
mapping(address => mapping(uint256 => bool)) _usedNonces;
mapping(address => uint256) _lastNonce;
bytes32 private _sigSalt;
/**
* @dev Log the claim
*
* claimant - wallet address of msg.sender. Indexed
* valHash - sha256 hash of the validator's self-delegate address. Indexed
* issuer - wallet address of the ticket issuer. Indexed
* validator - string value of the validator's self-delegate address.
* nonce - nonce used for this claim
* amount - amount of claim
*/
event TicketClaimed(
address indexed claimant,
bytes32 indexed valHash,
address indexed issuer,
string validator,
uint256 nonce,
uint256 amount
);
event SigSalt(bytes32 salt);
/**
* @dev Grants `DEFAULT_ADMIN_ROLE` and `ISSUER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol, bytes32 sigSalt) public ERC20(name, symbol) {
require(sigSalt[0] != 0 && sigSalt != 0x0, "xFUND: must include sig salt");
_setupDecimals(9);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
emit SigSalt(sigSalt);
_sigSalt = sigSalt;
}
/**
* @dev Creates `amount` new tokens for `_msgSender()`, after validating
* via recovery of data held in `ticket`. The `amount`, `nonce` and
* `_msgSender()` values are used to recreate the message hash used to sign
* the `ticket`. If recovery succeeds, the `amount` is minted for
* `_msgSender()`.
*
* Also see {ERC20-_mint}.
*
* Requirements:
*
* - the `ticket` must have been issued by the `ISSUER_ROLE`.
* - the `nonce` must not have been used and must be incremented by 1.
* - the ticket must include the sig salt defined in the contract
* - the ticket must include the contract's address
* - the ticket must include the sha256 hash of the validator's
* self-delegate address
*/
function claim(uint256 amount, uint256 nonce, string memory validator, bytes memory ticket) external {
require(nonce > 0, "xFUND: nonce must be greater than zero");
require(amount > 0, "xFUND: amount must be greater than zero");
require(ticket.length > 0, "xFUND: must include claim ticket");
require(bytes(validator).length > 0, "xFUND: must include validator");
require(!_usedNonces[_msgSender()][nonce], "xFUND: nonce already used/ticket claimed");
_usedNonces[_msgSender()][nonce] = true;
require(nonce == (_lastNonce[_msgSender()] + 1), "xFUND: expected nonce mismatch");
_lastNonce[_msgSender()] = nonce;
bytes32 valHash = keccak256(abi.encodePacked(validator));
bytes32 message = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(_msgSender(), valHash, amount, nonce, _sigSalt, address(this))));
address issuer = ECDSA.recover(message, ticket);
require(hasRole(ISSUER_ROLE, issuer), "xFUND: ticket invalid or issuer does not have issuer role");
emit TicketClaimed(_msgSender(), valHash, issuer, validator, nonce, amount);
_mint(_msgSender(), amount);
}
/**
* @dev Returns the last nonce value used by a claimant.
*/
function lastNonce(address account) external view returns (uint256) {
return _lastNonce[account];
}
/**
* @dev Returns the current signature salt.
*/
function sigSalt() external view returns (bytes32) {
return _sigSalt;
}
}
| * @dev {ERC20} token, including: - standard ERC20 contract interactions and functions - an issuer role that allows for token minting via signed claim tickets, which are issued by authorised addresses having the ISSUER_ROLE role. - nonce tracking for each address to prevent ticket claim replay This contract uses {AccessControl} to lock permissioned functions using the different roles. The account that deploys the contract will be granted the ISSUER_ROLE role, as well as the default admin role, which will let it grant and revoke ISSUER_ROLE roles to other accounts./ | contract XFUND is Context, AccessControl, ERC20 {
bytes32 public constant ISSUER_ROLE = keccak256("ISSUER_ROLE");
mapping(address => mapping(uint256 => bool)) _usedNonces;
mapping(address => uint256) _lastNonce;
bytes32 private _sigSalt;
event TicketClaimed(
address indexed claimant,
bytes32 indexed valHash,
address indexed issuer,
string validator,
uint256 nonce,
uint256 amount
);
event SigSalt(bytes32 salt);
constructor(string memory name, string memory symbol, bytes32 sigSalt) public ERC20(name, symbol) {
require(sigSalt[0] != 0 && sigSalt != 0x0, "xFUND: must include sig salt");
_setupDecimals(9);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
emit SigSalt(sigSalt);
_sigSalt = sigSalt;
}
function claim(uint256 amount, uint256 nonce, string memory validator, bytes memory ticket) external {
require(nonce > 0, "xFUND: nonce must be greater than zero");
require(amount > 0, "xFUND: amount must be greater than zero");
require(ticket.length > 0, "xFUND: must include claim ticket");
require(bytes(validator).length > 0, "xFUND: must include validator");
require(!_usedNonces[_msgSender()][nonce], "xFUND: nonce already used/ticket claimed");
_usedNonces[_msgSender()][nonce] = true;
require(nonce == (_lastNonce[_msgSender()] + 1), "xFUND: expected nonce mismatch");
_lastNonce[_msgSender()] = nonce;
bytes32 valHash = keccak256(abi.encodePacked(validator));
bytes32 message = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(_msgSender(), valHash, amount, nonce, _sigSalt, address(this))));
address issuer = ECDSA.recover(message, ticket);
require(hasRole(ISSUER_ROLE, issuer), "xFUND: ticket invalid or issuer does not have issuer role");
emit TicketClaimed(_msgSender(), valHash, issuer, validator, nonce, amount);
_mint(_msgSender(), amount);
}
function lastNonce(address account) external view returns (uint256) {
return _lastNonce[account];
}
function sigSalt() external view returns (bytes32) {
return _sigSalt;
}
}
| 1,831,206 | [
1,
95,
654,
39,
3462,
97,
1147,
16,
6508,
30,
225,
300,
4529,
4232,
39,
3462,
6835,
23877,
471,
4186,
225,
300,
392,
9715,
2478,
716,
5360,
364,
1147,
312,
474,
310,
3970,
6726,
7516,
24475,
16,
565,
1492,
854,
16865,
635,
2869,
5918,
6138,
7999,
326,
467,
1260,
57,
654,
67,
16256,
2478,
18,
225,
300,
7448,
11093,
364,
1517,
1758,
358,
5309,
9322,
7516,
16033,
1220,
6835,
4692,
288,
16541,
97,
358,
2176,
4132,
329,
4186,
1450,
326,
3775,
4900,
18,
1021,
2236,
716,
5993,
383,
1900,
326,
6835,
903,
506,
17578,
326,
467,
1260,
57,
654,
67,
16256,
2478,
16,
487,
5492,
487,
326,
805,
3981,
2478,
16,
1492,
903,
2231,
518,
7936,
471,
18007,
467,
1260,
57,
654,
67,
16256,
4900,
358,
1308,
9484,
18,
19,
2,
0,
0,
0,
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,
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
] | [
1,
16351,
1139,
42,
5240,
353,
1772,
16,
24349,
16,
4232,
39,
3462,
288,
203,
565,
1731,
1578,
1071,
5381,
467,
1260,
57,
654,
67,
16256,
273,
417,
24410,
581,
5034,
2932,
25689,
57,
654,
67,
16256,
8863,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
1426,
3719,
389,
3668,
3989,
764,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
389,
2722,
13611,
31,
203,
203,
565,
1731,
1578,
3238,
389,
7340,
19290,
31,
203,
203,
565,
871,
22023,
9762,
329,
12,
203,
3639,
1758,
8808,
7516,
970,
16,
203,
3639,
1731,
1578,
8808,
1244,
2310,
16,
203,
3639,
1758,
8808,
9715,
16,
203,
3639,
533,
4213,
16,
203,
3639,
2254,
5034,
7448,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
11272,
203,
565,
871,
21911,
19290,
12,
3890,
1578,
4286,
1769,
203,
203,
203,
565,
3885,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
1731,
1578,
3553,
19290,
13,
1071,
4232,
39,
3462,
12,
529,
16,
3273,
13,
288,
203,
3639,
2583,
12,
7340,
19290,
63,
20,
65,
480,
374,
597,
3553,
19290,
480,
374,
92,
20,
16,
315,
16275,
5240,
30,
1297,
2341,
3553,
4286,
8863,
203,
3639,
389,
8401,
31809,
12,
29,
1769,
203,
3639,
389,
8401,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
389,
3576,
12021,
10663,
203,
203,
3639,
3626,
21911,
19290,
12,
7340,
19290,
1769,
203,
3639,
389,
7340,
19290,
273,
3553,
19290,
31,
203,
565,
289,
203,
203,
565,
445,
7516,
12,
11890,
5034,
3844,
16,
2254,
5034,
7448,
16,
2
] |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'ADE' 'AdeCoin' token contract
//
// Symbol : ADE
// Name : AdeCoin
// Total supply: Generated from contributions
// Decimals : 8
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event TransferSell(address indexed from, uint tokens, uint eth);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals
// Receives ETH and generates tokens
// ----------------------------------------------------------------------------
contract ADEToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public totalSupply;
uint public sellRate;
uint public buyRate;
uint private lockRate = 30 days;
struct lockPosition{
uint time;
uint count;
uint releaseRate;
}
mapping(address => lockPosition) private lposition;
// locked account dictionary that maps addresses to boolean
mapping (address => bool) private lockedAccounts;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
modifier is_not_locked(address _address) {
if (lockedAccounts[_address] == true) revert();
_;
}
modifier validate_address(address _address) {
if (_address == address(0)) revert();
_;
}
modifier is_locked(address _address) {
if (lockedAccounts[_address] != true) revert();
_;
}
modifier validate_position(address _address,uint count) {
if(balances[_address] < count * 10**uint(decimals)) revert();
if(lposition[_address].count > 0 && (balances[_address] - (count * 10**uint(decimals))) < lposition[_address].count && now < lposition[_address].time) revert();
checkPosition(_address,count);
_;
}
function checkPosition(address _address,uint count) private view {
if(lposition[_address].releaseRate < 100 && lposition[_address].count > 0){
uint _rate = safeDiv(100,lposition[_address].releaseRate);
uint _time = lposition[_address].time;
uint _tmpRate = lposition[_address].releaseRate;
uint _tmpRateAll = 0;
uint _count = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_count = _a;
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
if(_count < _rate && lposition[_address].count > 0 && (balances[_address] - count * 10**uint(decimals)) < (lposition[_address].count - safeDiv(lposition[_address].count*_tmpRateAll,100)) && now >= lposition[_address].time) revert();
}
}
event _lockAccount(address _add);
event _unlockAccount(address _add);
function () public payable{
require(owner != msg.sender);
require(buyRate > 0);
require(msg.value >= 0.1 ether && msg.value <= 1000 ether);
uint tokens;
tokens = msg.value / (1 ether * 1 wei / buyRate);
require(balances[owner] >= tokens * 10**uint(decimals));
balances[msg.sender] = safeAdd(balances[msg.sender], tokens * 10**uint(decimals));
balances[owner] = safeSub(balances[owner], tokens * 10**uint(decimals));
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function ADEToken(uint _sellRate,uint _buyRate) public payable {
symbol = "ADE";
name = "AdeCoin";
decimals = 8;
totalSupply = 2000000000 * 10**uint(decimals);
balances[owner] = totalSupply;
Transfer(address(0), owner, totalSupply);
sellRate = _sellRate;
buyRate = _buyRate;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public is_not_locked(msg.sender) is_not_locked(to) validate_position(msg.sender,tokens / (10**uint(decimals))) returns (bool success) {
require(to != msg.sender);
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public is_not_locked(msg.sender) is_not_locked(spender) validate_position(msg.sender,tokens / (10**uint(decimals))) returns (bool success) {
require(spender != msg.sender);
require(tokens > 0);
require(balances[msg.sender] >= tokens);
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public is_not_locked(msg.sender) is_not_locked(from) is_not_locked(to) validate_position(from,tokens / (10**uint(decimals))) returns (bool success) {
require(transferFromCheck(from,to,tokens));
return true;
}
function transferFromCheck(address from,address to,uint tokens) private returns (bool success) {
require(tokens > 0);
require(from != msg.sender && msg.sender != to && from != to);
require(balances[from] >= tokens && allowed[from][msg.sender] >= tokens);
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Sall a token from a contract
// ------------------------------------------------------------------------
function sellCoin(address seller, uint amount) public onlyOwner is_not_locked(seller) validate_position(seller,amount){
require(balances[seller] >= amount * 10**uint(decimals));
require(sellRate > 0);
require(seller != msg.sender);
uint tmpAmount = amount * (1 ether * 1 wei / sellRate);
balances[owner] += amount * 10**uint(decimals);
balances[seller] -= amount * 10**uint(decimals);
seller.transfer(tmpAmount);
TransferSell(seller, amount * 10**uint(decimals), tmpAmount);
}
// set rate
function setRate(uint _buyRate,uint _sellRate) public onlyOwner {
require(_buyRate > 0);
require(_sellRate > 0);
require(_buyRate < _sellRate);
buyRate = _buyRate;
sellRate = _sellRate;
}
//set lock position
function setLockPostion(address _add,uint _count,uint _time,uint _releaseRate) public is_not_locked(_add) onlyOwner {
require(_time > now);
require(_count > 0);
require(_releaseRate > 0 && _releaseRate <= 100);
require(_releaseRate == 2 || _releaseRate == 4 || _releaseRate == 5 || _releaseRate == 10 || _releaseRate == 20 || _releaseRate == 25 || _releaseRate == 50);
require(balances[_add] >= _count * 10**uint(decimals));
lposition[_add].time = _time;
lposition[_add].count = _count * 10**uint(decimals);
lposition[_add].releaseRate = _releaseRate;
}
// lockAccount
function lockStatus(address _owner) public is_not_locked(_owner) validate_address(_owner) onlyOwner {
lockedAccounts[_owner] = true;
_lockAccount(_owner);
}
/// @notice only the admin is allowed to unlock accounts.
/// @param _owner the address of the account to be unlocked
function unlockStatus(address _owner) public is_locked(_owner) validate_address(_owner) onlyOwner {
lockedAccounts[_owner] = false;
_unlockAccount(_owner);
}
//get lockedaccount
function getLockStatus(address _owner) public view returns (bool _lockStatus) {
return lockedAccounts[_owner];
}
//get lockPosition info
function getLockPosition(address _add) public view returns(uint time,uint count,uint rate,uint scount) {
return (lposition[_add].time,lposition[_add].count,lposition[_add].releaseRate,positionScount(_add));
}
function positionScount(address _add) private view returns (uint count){
uint _rate = safeDiv(100,lposition[_add].releaseRate);
uint _time = lposition[_add].time;
uint _tmpRate = lposition[_add].releaseRate;
uint _tmpRateAll = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
return (lposition[_add].count - safeDiv(lposition[_add].count*_tmpRateAll,100));
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals Receives ETH and generates tokens ---------------------------------------------------------------------------- | contract ADEToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public totalSupply;
uint public sellRate;
uint public buyRate;
uint private lockRate = 30 days;
struct lockPosition{
uint time;
uint count;
uint releaseRate;
}
mapping(address => lockPosition) private lposition;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping (address => bool) private lockedAccounts;
modifier is_not_locked(address _address) {
if (lockedAccounts[_address] == true) revert();
_;
}
modifier validate_address(address _address) {
if (_address == address(0)) revert();
_;
}
modifier is_locked(address _address) {
if (lockedAccounts[_address] != true) revert();
_;
}
modifier validate_position(address _address,uint count) {
if(balances[_address] < count * 10**uint(decimals)) revert();
if(lposition[_address].count > 0 && (balances[_address] - (count * 10**uint(decimals))) < lposition[_address].count && now < lposition[_address].time) revert();
checkPosition(_address,count);
_;
}
function checkPosition(address _address,uint count) private view {
if(lposition[_address].releaseRate < 100 && lposition[_address].count > 0){
uint _rate = safeDiv(100,lposition[_address].releaseRate);
uint _time = lposition[_address].time;
uint _tmpRate = lposition[_address].releaseRate;
uint _tmpRateAll = 0;
uint _count = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_count = _a;
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
if(_count < _rate && lposition[_address].count > 0 && (balances[_address] - count * 10**uint(decimals)) < (lposition[_address].count - safeDiv(lposition[_address].count*_tmpRateAll,100)) && now >= lposition[_address].time) revert();
}
}
event _lockAccount(address _add);
event _unlockAccount(address _add);
function checkPosition(address _address,uint count) private view {
if(lposition[_address].releaseRate < 100 && lposition[_address].count > 0){
uint _rate = safeDiv(100,lposition[_address].releaseRate);
uint _time = lposition[_address].time;
uint _tmpRate = lposition[_address].releaseRate;
uint _tmpRateAll = 0;
uint _count = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_count = _a;
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
if(_count < _rate && lposition[_address].count > 0 && (balances[_address] - count * 10**uint(decimals)) < (lposition[_address].count - safeDiv(lposition[_address].count*_tmpRateAll,100)) && now >= lposition[_address].time) revert();
}
}
event _lockAccount(address _add);
event _unlockAccount(address _add);
function checkPosition(address _address,uint count) private view {
if(lposition[_address].releaseRate < 100 && lposition[_address].count > 0){
uint _rate = safeDiv(100,lposition[_address].releaseRate);
uint _time = lposition[_address].time;
uint _tmpRate = lposition[_address].releaseRate;
uint _tmpRateAll = 0;
uint _count = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_count = _a;
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
if(_count < _rate && lposition[_address].count > 0 && (balances[_address] - count * 10**uint(decimals)) < (lposition[_address].count - safeDiv(lposition[_address].count*_tmpRateAll,100)) && now >= lposition[_address].time) revert();
}
}
event _lockAccount(address _add);
event _unlockAccount(address _add);
function checkPosition(address _address,uint count) private view {
if(lposition[_address].releaseRate < 100 && lposition[_address].count > 0){
uint _rate = safeDiv(100,lposition[_address].releaseRate);
uint _time = lposition[_address].time;
uint _tmpRate = lposition[_address].releaseRate;
uint _tmpRateAll = 0;
uint _count = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_count = _a;
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
if(_count < _rate && lposition[_address].count > 0 && (balances[_address] - count * 10**uint(decimals)) < (lposition[_address].count - safeDiv(lposition[_address].count*_tmpRateAll,100)) && now >= lposition[_address].time) revert();
}
}
event _lockAccount(address _add);
event _unlockAccount(address _add);
function () public payable{
require(owner != msg.sender);
require(buyRate > 0);
require(msg.value >= 0.1 ether && msg.value <= 1000 ether);
uint tokens;
tokens = msg.value / (1 ether * 1 wei / buyRate);
require(balances[owner] >= tokens * 10**uint(decimals));
balances[msg.sender] = safeAdd(balances[msg.sender], tokens * 10**uint(decimals));
balances[owner] = safeSub(balances[owner], tokens * 10**uint(decimals));
}
function ADEToken(uint _sellRate,uint _buyRate) public payable {
symbol = "ADE";
name = "AdeCoin";
decimals = 8;
totalSupply = 2000000000 * 10**uint(decimals);
balances[owner] = totalSupply;
Transfer(address(0), owner, totalSupply);
sellRate = _sellRate;
buyRate = _buyRate;
}
function totalSupply() public constant returns (uint) {
return totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public is_not_locked(msg.sender) is_not_locked(to) validate_position(msg.sender,tokens / (10**uint(decimals))) returns (bool success) {
require(to != msg.sender);
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public is_not_locked(msg.sender) is_not_locked(spender) validate_position(msg.sender,tokens / (10**uint(decimals))) returns (bool success) {
require(spender != msg.sender);
require(tokens > 0);
require(balances[msg.sender] >= tokens);
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public is_not_locked(msg.sender) is_not_locked(from) is_not_locked(to) validate_position(from,tokens / (10**uint(decimals))) returns (bool success) {
require(transferFromCheck(from,to,tokens));
return true;
}
function transferFromCheck(address from,address to,uint tokens) private returns (bool success) {
require(tokens > 0);
require(from != msg.sender && msg.sender != to && from != to);
require(balances[from] >= tokens && allowed[from][msg.sender] >= tokens);
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function sellCoin(address seller, uint amount) public onlyOwner is_not_locked(seller) validate_position(seller,amount){
require(balances[seller] >= amount * 10**uint(decimals));
require(sellRate > 0);
require(seller != msg.sender);
uint tmpAmount = amount * (1 ether * 1 wei / sellRate);
balances[owner] += amount * 10**uint(decimals);
balances[seller] -= amount * 10**uint(decimals);
seller.transfer(tmpAmount);
TransferSell(seller, amount * 10**uint(decimals), tmpAmount);
}
function setRate(uint _buyRate,uint _sellRate) public onlyOwner {
require(_buyRate > 0);
require(_sellRate > 0);
require(_buyRate < _sellRate);
buyRate = _buyRate;
sellRate = _sellRate;
}
function setLockPostion(address _add,uint _count,uint _time,uint _releaseRate) public is_not_locked(_add) onlyOwner {
require(_time > now);
require(_count > 0);
require(_releaseRate > 0 && _releaseRate <= 100);
require(_releaseRate == 2 || _releaseRate == 4 || _releaseRate == 5 || _releaseRate == 10 || _releaseRate == 20 || _releaseRate == 25 || _releaseRate == 50);
require(balances[_add] >= _count * 10**uint(decimals));
lposition[_add].time = _time;
lposition[_add].count = _count * 10**uint(decimals);
lposition[_add].releaseRate = _releaseRate;
}
function lockStatus(address _owner) public is_not_locked(_owner) validate_address(_owner) onlyOwner {
lockedAccounts[_owner] = true;
_lockAccount(_owner);
}
function unlockStatus(address _owner) public is_locked(_owner) validate_address(_owner) onlyOwner {
lockedAccounts[_owner] = false;
_unlockAccount(_owner);
}
function getLockStatus(address _owner) public view returns (bool _lockStatus) {
return lockedAccounts[_owner];
}
function getLockPosition(address _add) public view returns(uint time,uint count,uint rate,uint scount) {
return (lposition[_add].time,lposition[_add].count,lposition[_add].releaseRate,positionScount(_add));
}
function positionScount(address _add) private view returns (uint count){
uint _rate = safeDiv(100,lposition[_add].releaseRate);
uint _time = lposition[_add].time;
uint _tmpRate = lposition[_add].releaseRate;
uint _tmpRateAll = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
return (lposition[_add].count - safeDiv(lposition[_add].count*_tmpRateAll,100));
}
function positionScount(address _add) private view returns (uint count){
uint _rate = safeDiv(100,lposition[_add].releaseRate);
uint _time = lposition[_add].time;
uint _tmpRate = lposition[_add].releaseRate;
uint _tmpRateAll = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
return (lposition[_add].count - safeDiv(lposition[_add].count*_tmpRateAll,100));
}
function positionScount(address _add) private view returns (uint count){
uint _rate = safeDiv(100,lposition[_add].releaseRate);
uint _time = lposition[_add].time;
uint _tmpRate = lposition[_add].releaseRate;
uint _tmpRateAll = 0;
for(uint _a=1;_a<=_rate;_a++){
if(now >= _time){
_tmpRateAll = safeAdd(_tmpRateAll,_tmpRate);
_time = safeAdd(_time,lockRate);
}
}
return (lposition[_add].count - safeDiv(lposition[_add].count*_tmpRateAll,100));
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1,561,405 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
9797,
3606,
512,
2455,
471,
6026,
2430,
8879,
13849,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
432,
1639,
1345,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
2078,
3088,
1283,
31,
203,
565,
2254,
1071,
357,
80,
4727,
31,
203,
565,
2254,
1071,
30143,
4727,
31,
203,
377,
203,
565,
2254,
3238,
2176,
4727,
273,
5196,
4681,
31,
203,
377,
203,
565,
1958,
2176,
2555,
95,
203,
3639,
2254,
813,
31,
203,
3639,
2254,
1056,
31,
203,
3639,
2254,
3992,
4727,
31,
203,
565,
289,
203,
377,
203,
565,
2874,
12,
2867,
516,
2176,
2555,
13,
3238,
328,
3276,
31,
203,
377,
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,
377,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
8586,
13971,
31,
203,
565,
9606,
353,
67,
902,
67,
15091,
12,
2867,
389,
2867,
13,
288,
203,
3639,
309,
261,
15091,
13971,
63,
67,
2867,
65,
422,
638,
13,
15226,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
565,
9606,
1954,
67,
2867,
12,
2867,
389,
2867,
13,
288,
203,
3639,
309,
261,
67,
2867,
422,
1758,
12,
20,
3719,
15226,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
565,
9606,
353,
67,
15091,
12,
2867,
389,
2867,
13,
288,
203,
3639,
309,
261,
15091,
13971,
63,
67,
2867,
65,
480,
638,
13,
15226,
5621,
203,
2
] |
./partial_match/4/0x38076be7DF04a09aeE3181eD15454961FBc2331a/sources/WrappedTalleoToken.sol | TODO: figure out exactly how much is needed
| uint8[] memory digits = new uint8[](97); | 8,525,314 | [
1,
6241,
30,
7837,
596,
8950,
3661,
9816,
353,
3577,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
28,
8526,
3778,
6815,
273,
394,
2254,
28,
8526,
12,
10580,
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
] |
./full_match/43114/0x78eD6e74806f60c0E3139c6fe7485a24c11120d2/sources/MasterChef.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/ 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. | abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
pragma solidity 0.6.12;
constructor() internal {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
| 4,586,386 | [
1,
8924,
1605,
716,
21814,
5309,
283,
8230,
970,
4097,
358,
279,
445,
18,
25953,
310,
628,
1375,
426,
8230,
12514,
16709,
68,
903,
1221,
326,
288,
5836,
426,
8230,
970,
97,
9606,
2319,
16,
1492,
848,
506,
6754,
358,
4186,
358,
1221,
3071,
1915,
854,
1158,
4764,
261,
2842,
313,
970,
13,
4097,
358,
2182,
18,
3609,
716,
2724,
1915,
353,
279,
2202,
1375,
5836,
426,
8230,
970,
68,
11026,
16,
4186,
9350,
487,
1375,
5836,
426,
8230,
970,
68,
2026,
486,
745,
1245,
4042,
18,
1220,
848,
506,
28613,
6740,
635,
10480,
5348,
4186,
1375,
1152,
9191,
471,
1508,
6534,
1375,
9375,
68,
1375,
5836,
426,
8230,
970,
68,
1241,
3143,
358,
2182,
18,
399,
2579,
30,
971,
1846,
4102,
3007,
358,
16094,
1898,
2973,
283,
8230,
12514,
471,
10355,
16226,
358,
17151,
5314,
518,
16,
866,
596,
3134,
10700,
1603,
19,
605,
11887,
634,
854,
1898,
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,
17801,
6835,
868,
8230,
12514,
16709,
288,
203,
203,
565,
2254,
5034,
3238,
5381,
389,
4400,
67,
12278,
2056,
273,
404,
31,
203,
565,
2254,
5034,
3238,
5381,
389,
12278,
2056,
273,
576,
31,
203,
203,
565,
2254,
5034,
3238,
389,
2327,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
565,
3885,
1435,
2713,
288,
203,
3639,
389,
2327,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
289,
203,
203,
565,
9606,
1661,
426,
8230,
970,
1435,
288,
203,
3639,
2583,
24899,
2327,
480,
389,
12278,
2056,
16,
315,
426,
8230,
12514,
16709,
30,
283,
8230,
970,
745,
8863,
203,
203,
3639,
389,
2327,
273,
389,
12278,
2056,
31,
203,
203,
3639,
389,
31,
203,
203,
3639,
389,
2327,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
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.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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 <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);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function parseAssetsForAction(
address _vaultProxy,
bytes4 _selector,
bytes calldata _encodedCallArgs
)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/CurvePriceFeed.sol";
import "../../../../infrastructure/staking-wrappers/convex-curve-lp/ConvexCurveLpStakingWrapperFactory.sol";
import "../utils/actions/StakingWrapperActionsMixin.sol";
import "../utils/bases/CurveLiquidityAdapterBase.sol";
/// @title ConvexCurveLpStakingAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for staking Curve LP tokens via Convex,
/// with optional combined end-to-end liquidity provision via Curve
/// @dev Rewards tokens are not included as incoming assets for claimRewards()
/// Rationale:
/// - rewards tokens can be claimed to the vault outside of the IntegrationManager, so no need
/// to enforce policy management or emit an event
/// - rewards tokens can be outside of the asset universe, in which case they cannot be tracked
contract ConvexCurveLpStakingAdapter is CurveLiquidityAdapterBase, StakingWrapperActionsMixin {
ConvexCurveLpStakingWrapperFactory private immutable STAKING_WRAPPER_FACTORY_CONTRACT;
CurvePriceFeed private immutable CURVE_PRICE_FEED_CONTRACT;
constructor(
address _integrationManager,
address _curvePriceFeed,
address _wrappedNativeAsset,
address _stakingWrapperFactory,
address _nativeAssetAddress
)
public
CurveLiquidityAdapterBase(_integrationManager, _wrappedNativeAsset, _nativeAssetAddress)
{
CURVE_PRICE_FEED_CONTRACT = CurvePriceFeed(_curvePriceFeed);
STAKING_WRAPPER_FACTORY_CONTRACT = ConvexCurveLpStakingWrapperFactory(
_stakingWrapperFactory
);
}
// EXTERNAL FUNCTIONS
/// @notice Claims all rewards for a given staking token
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
function claimRewards(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata
) external onlyIntegrationManager {
__stakingWrapperClaimRewardsFor(__decodeClaimRewardsCallArgs(_actionData), _vaultProxy);
}
/// @notice Lends assets for LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function lendAndStake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
) external onlyIntegrationManager {
(
address pool,
uint256[] memory orderedOutgoingAssetAmounts,
address incomingStakingToken,
uint256 minIncomingStakingTokenAmount,
bool useUnderlyings
) = __decodeLendAndStakeCallArgs(_actionData);
(address[] memory spendAssets, , ) = __decodeAssetData(_assetData);
address lpToken = CURVE_PRICE_FEED_CONTRACT.getLpTokenForPool(pool);
__curveAddLiquidity(
pool,
spendAssets,
orderedOutgoingAssetAmounts,
minIncomingStakingTokenAmount,
useUnderlyings
);
__stakingWrapperStake(
incomingStakingToken,
_vaultProxy,
ERC20(lpToken).balanceOf(address(this)),
lpToken
);
}
/// @notice Stakes LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function stake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
) external onlyIntegrationManager {
(, address incomingStakingToken, uint256 amount) = __decodeStakeCallArgs(_actionData);
(address[] memory spendAssets, , ) = __decodeAssetData(_assetData);
__stakingWrapperStake(incomingStakingToken, _vaultProxy, amount, spendAssets[0]);
}
/// @notice Unstakes LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
function unstake(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata
) external onlyIntegrationManager {
(, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs(_actionData);
__stakingWrapperUnstake(outgoingStakingToken, _vaultProxy, _vaultProxy, amount, false);
}
/// @notice Unstakes LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _actionData Data specific to this action
/// @param _assetData Parsed spend assets and incoming assets data for this action
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _actionData,
bytes calldata _assetData
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData)
{
(
address pool,
address outgoingStakingToken,
uint256 outgoingStakingTokenAmount,
bool useUnderlyings,
RedeemType redeemType,
bytes memory incomingAssetsData
) = __decodeUnstakeAndRedeemCallArgs(_actionData);
__stakingWrapperUnstake(
outgoingStakingToken,
_vaultProxy,
address(this),
outgoingStakingTokenAmount,
false
);
__curveRedeem(
pool,
outgoingStakingTokenAmount,
useUnderlyings,
redeemType,
incomingAssetsData
);
}
/////////////////////////////
// PARSE ASSETS FOR METHOD //
/////////////////////////////
/// @notice Parses the expected assets in a particular action
/// @param _selector The function selector for the callOnIntegration
/// @param _actionData Data specific to this action
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForAction(
address,
bytes4 _selector,
bytes calldata _actionData
)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == CLAIM_REWARDS_SELECTOR) {
return __parseAssetsForClaimRewards();
} else if (_selector == LEND_AND_STAKE_SELECTOR) {
return __parseAssetsForLendAndStake(_actionData);
} else if (_selector == STAKE_SELECTOR) {
return __parseAssetsForStake(_actionData);
} else if (_selector == UNSTAKE_SELECTOR) {
return __parseAssetsForUnstake(_actionData);
} else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) {
return __parseAssetsForUnstakeAndRedeem(_actionData);
}
revert("parseAssetsForAction: _selector invalid");
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during claimRewards() calls.
/// No action required, all values empty.
function __parseAssetsForClaimRewards()
private
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
return (
IIntegrationManager.SpendAssetsHandleType.None,
new address[](0),
new uint256[](0),
new address[](0),
new uint256[](0)
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during lendAndStake() calls
function __parseAssetsForLendAndStake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address pool,
uint256[] memory orderedOutgoingAssetAmounts,
address incomingStakingToken,
uint256 minIncomingStakingTokenAmount,
bool useUnderlyings
) = __decodeLendAndStakeCallArgs(_actionData);
__validatePoolForWrapper(pool, incomingStakingToken);
(spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls(
pool,
orderedOutgoingAssetAmounts,
useUnderlyings
);
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingStakingToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingStakingTokenAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during stake() calls
function __parseAssetsForStake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(, address incomingStakingToken, uint256 amount) = __decodeStakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(
incomingStakingToken
);
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingStakingToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstake() calls
function __parseAssetsForUnstake(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs(_actionData);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingStakingToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(
outgoingStakingToken
);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
// SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf
return (
IIntegrationManager.SpendAssetsHandleType.Approve,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper function to parse spend and incoming assets from encoded call args
/// during unstakeAndRedeem() calls
function __parseAssetsForUnstakeAndRedeem(bytes calldata _actionData)
private
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
address pool,
address outgoingStakingToken,
uint256 outgoingStakingTokenAmount,
bool useUnderlyings,
RedeemType redeemType,
bytes memory incomingAssetsData
) = __decodeUnstakeAndRedeemCallArgs(_actionData);
__validatePoolForWrapper(pool, outgoingStakingToken);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingStakingToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingStakingTokenAmount;
(incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls(
pool,
useUnderlyings,
redeemType,
incomingAssetsData
);
// SpendAssetsHandleType is `Approve`, since staking wrapper allows unstaking on behalf
return (
IIntegrationManager.SpendAssetsHandleType.Approve,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Helper to validate a given Curve `pool` for a given convex staking wrapper
function __validatePoolForWrapper(address _pool, address _wrapper) private view {
address lpToken = STAKING_WRAPPER_FACTORY_CONTRACT.getCurveLpTokenForWrapper(_wrapper);
require(
lpToken == CURVE_PRICE_FEED_CONTRACT.getLpTokenForPool(_pool),
"__validatePoolForWrapper: Invalid"
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../utils/AssetHelpers.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _assetData
) {
_;
(, , address[] memory incomingAssets) = __decodeAssetData(_assetData);
__pushFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) {
_;
(address[] memory spendAssets, , ) = __decodeAssetData(_assetData);
__pushFullAssetBalances(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper to decode the _assetData param passed to adapter call
function __decodeAssetData(bytes memory _assetData)
internal
pure
returns (
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return abi.decode(_assetData, (address[], uint256[], address[]));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Rewards
bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4(
keccak256("claimRewards(address,bytes,bytes)")
);
// Combined
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/Strings.sol";
import "../../../../../interfaces/IWETH.sol";
import "../../../../../utils/AssetHelpers.sol";
/// @title CurveLiquidityActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with the Curve pool liquidity functions
/// @dev Inheriting contract must have a receive() function if lending or redeeming for the native asset
abstract contract CurveLiquidityActionsMixin is AssetHelpers {
using Strings for uint256;
uint256 private constant ASSET_APPROVAL_TOP_UP_THRESHOLD = 1e76; // Arbitrary, slightly less than 1/11 of max uint256
bytes4 private constant CURVE_REMOVE_LIQUIDITY_ONE_COIN_SELECTOR = 0x1a4d01d2;
bytes4 private constant CURVE_REMOVE_LIQUIDITY_ONE_COIN_USE_UNDERLYINGS_SELECTOR = 0x517a55a3;
address private immutable CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET;
constructor(address _wrappedNativeAsset) public {
CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET = _wrappedNativeAsset;
}
/// @dev Helper to add liquidity to the pool.
/// _squashedOutgoingAssets are only those pool assets that are actually used to add liquidity,
/// which can be verbose and ordered, but it is more gas-efficient to only include non-0 amounts.
function __curveAddLiquidity(
address _pool,
address[] memory _squashedOutgoingAssets,
uint256[] memory _orderedOutgoingAssetAmounts,
uint256 _minIncomingLpTokenAmount,
bool _useUnderlyings
) internal {
// Approve and/or unwrap native asset as necessary.
// Rather than using exact amounts for approvals,
// this tops up to max approval if 1/2 max is reached.
uint256 outgoingNativeAssetAmount;
for (uint256 i; i < _squashedOutgoingAssets.length; i++) {
if (_squashedOutgoingAssets[i] == getCurveLiquidityWrappedNativeAsset()) {
// It is never the case that a pool has multiple slots for the same native asset,
// so this is not additive
outgoingNativeAssetAmount = ERC20(getCurveLiquidityWrappedNativeAsset()).balanceOf(
address(this)
);
IWETH(getCurveLiquidityWrappedNativeAsset()).withdraw(outgoingNativeAssetAmount);
} else {
// Once an asset it approved for a given pool, it will almost definitely
// never need approval again, but it is topped up to max once an arbitrary
// threshold is reached
__approveAssetMaxAsNeeded(
_squashedOutgoingAssets[i],
_pool,
ASSET_APPROVAL_TOP_UP_THRESHOLD
);
}
}
// Dynamically call the appropriate selector
(bool success, bytes memory returnData) = _pool.call{value: outgoingNativeAssetAmount}(
__curveAddLiquidityEncodeCalldata(
_orderedOutgoingAssetAmounts,
_minIncomingLpTokenAmount,
_useUnderlyings
)
);
require(success, string(returnData));
}
/// @dev Helper to remove liquidity from the pool.
/// if using _redeemSingleAsset, must pre-validate that one - and only one - asset
/// has a non-zero _orderedMinIncomingAssetAmounts value.
function __curveRemoveLiquidity(
address _pool,
uint256 _outgoingLpTokenAmount,
uint256[] memory _orderedMinIncomingAssetAmounts,
bool _useUnderlyings
) internal {
// Dynamically call the appropriate selector
(bool success, bytes memory returnData) = _pool.call(
__curveRemoveLiquidityEncodeCalldata(
_outgoingLpTokenAmount,
_orderedMinIncomingAssetAmounts,
_useUnderlyings
)
);
require(success, string(returnData));
// Wrap native asset
__curveLiquidityWrapNativeAssetBalance();
}
/// @dev Helper to remove liquidity from the pool and receive all value owed in one specified token
function __curveRemoveLiquidityOneCoin(
address _pool,
uint256 _outgoingLpTokenAmount,
int128 _incomingAssetPoolIndex,
uint256 _minIncomingAssetAmount,
bool _useUnderlyings
) internal {
bytes memory callData;
if (_useUnderlyings) {
callData = abi.encodeWithSelector(
CURVE_REMOVE_LIQUIDITY_ONE_COIN_USE_UNDERLYINGS_SELECTOR,
_outgoingLpTokenAmount,
_incomingAssetPoolIndex,
_minIncomingAssetAmount,
true
);
} else {
callData = abi.encodeWithSelector(
CURVE_REMOVE_LIQUIDITY_ONE_COIN_SELECTOR,
_outgoingLpTokenAmount,
_incomingAssetPoolIndex,
_minIncomingAssetAmount
);
}
// Dynamically call the appropriate selector
(bool success, bytes memory returnData) = _pool.call(callData);
require(success, string(returnData));
// Wrap native asset
__curveLiquidityWrapNativeAssetBalance();
}
// PRIVATE FUNCTIONS
/// @dev Helper to encode calldata for a call to add liquidity on Curve
function __curveAddLiquidityEncodeCalldata(
uint256[] memory _orderedOutgoingAssetAmounts,
uint256 _minIncomingLpTokenAmount,
bool _useUnderlyings
) private pure returns (bytes memory callData_) {
bytes memory finalEncodedArgOrEmpty;
if (_useUnderlyings) {
finalEncodedArgOrEmpty = abi.encode(true);
}
return
abi.encodePacked(
__curveAddLiquidityEncodeSelector(
_orderedOutgoingAssetAmounts.length,
_useUnderlyings
),
abi.encodePacked(_orderedOutgoingAssetAmounts),
_minIncomingLpTokenAmount,
finalEncodedArgOrEmpty
);
}
/// @dev Helper to encode selector for a call to add liquidity on Curve
function __curveAddLiquidityEncodeSelector(uint256 _numberOfCoins, bool _useUnderlyings)
private
pure
returns (bytes4 selector_)
{
string memory finalArgOrEmpty;
if (_useUnderlyings) {
finalArgOrEmpty = ",bool";
}
return
bytes4(
keccak256(
abi.encodePacked(
"add_liquidity(uint256[",
_numberOfCoins.toString(),
"],",
"uint256",
finalArgOrEmpty,
")"
)
)
);
}
/// @dev Helper to wrap the full native asset balance of the current contract
function __curveLiquidityWrapNativeAssetBalance() private {
uint256 nativeAssetBalance = payable(address(this)).balance;
if (nativeAssetBalance > 0) {
IWETH(payable(getCurveLiquidityWrappedNativeAsset())).deposit{
value: nativeAssetBalance
}();
}
}
/// @dev Helper to encode calldata for a call to remove liquidity from Curve
function __curveRemoveLiquidityEncodeCalldata(
uint256 _outgoingLpTokenAmount,
uint256[] memory _orderedMinIncomingAssetAmounts,
bool _useUnderlyings
) private pure returns (bytes memory callData_) {
bytes memory finalEncodedArgOrEmpty;
if (_useUnderlyings) {
finalEncodedArgOrEmpty = abi.encode(true);
}
return
abi.encodePacked(
__curveRemoveLiquidityEncodeSelector(
_orderedMinIncomingAssetAmounts.length,
_useUnderlyings
),
_outgoingLpTokenAmount,
abi.encodePacked(_orderedMinIncomingAssetAmounts),
finalEncodedArgOrEmpty
);
}
/// @dev Helper to encode selector for a call to remove liquidity on Curve
function __curveRemoveLiquidityEncodeSelector(uint256 _numberOfCoins, bool _useUnderlyings)
private
pure
returns (bytes4 selector_)
{
string memory finalArgOrEmpty;
if (_useUnderlyings) {
finalArgOrEmpty = ",bool";
}
return
bytes4(
keccak256(
abi.encodePacked(
"remove_liquidity(uint256,",
"uint256[",
_numberOfCoins.toString(),
"]",
finalArgOrEmpty,
")"
)
)
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET` variable
/// @return addressProvider_ The `CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET` variable value
function getCurveLiquidityWrappedNativeAsset() public view returns (address addressProvider_) {
return CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../../infrastructure/staking-wrappers/IStakingWrapper.sol";
import "../../../../../utils/AssetHelpers.sol";
/// @title StakingWrapperActionsMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin contract for interacting with IStakingWrapper implementations
abstract contract StakingWrapperActionsMixin is AssetHelpers {
/// @dev Helper to claim rewards via a IStakingWrapper implementation
function __stakingWrapperClaimRewardsFor(address _wrapper, address _for) internal {
IStakingWrapper(_wrapper).claimRewardsFor(_for);
}
/// @dev Helper to stake via a IStakingWrapper implementation
function __stakingWrapperStake(
address _wrapper,
address _to,
uint256 _amount,
address _outgoingAsset
) internal {
__approveAssetMaxAsNeeded(_outgoingAsset, _wrapper, _amount);
IStakingWrapper(_wrapper).depositTo(_to, _amount);
}
/// @dev Helper to unstake via a IStakingWrapper implementation
function __stakingWrapperUnstake(
address _wrapper,
address _from,
address _to,
uint256 _amount,
bool _claimRewards
) internal {
IStakingWrapper(_wrapper).withdrawToOnBehalf(_from, _to, _amount, _claimRewards);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "../../../../../interfaces/ICurveLiquidityPool.sol";
import "../actions/CurveLiquidityActionsMixin.sol";
import "../AdapterBase.sol";
/// @title CurveLiquidityAdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base adapter for liquidity provision in Curve pools that adhere to pool templates,
/// as well as some old pools that have almost the same required interface (e.g., 3pool).
/// Implementing contracts can allow staking via Curve gauges, Convex, etc.
abstract contract CurveLiquidityAdapterBase is AdapterBase, CurveLiquidityActionsMixin {
enum RedeemType {Standard, OneCoin}
address private immutable CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS;
constructor(
address _integrationManager,
address _wrappedNativeAsset,
address _nativeAssetAddress
) public AdapterBase(_integrationManager) CurveLiquidityActionsMixin(_wrappedNativeAsset) {
CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS = _nativeAssetAddress;
}
/// @dev Needed to unwrap and receive the native asset
receive() external payable {}
// INTERNAL FUNCTIONS
/// @dev Helper to return the wrappedNativeAsset if the input is the native asset
function __castWrappedIfNativeAsset(address _tokenOrNativeAsset)
internal
view
returns (address token_)
{
if (_tokenOrNativeAsset == CURVE_LIQUIDITY_NATIVE_ASSET_ADDRESS) {
return getCurveLiquidityWrappedNativeAsset();
}
return _tokenOrNativeAsset;
}
/// @dev Helper to correctly call the relevant redeem function based on RedeemType
function __curveRedeem(
address _pool,
uint256 _outgoingLpTokenAmount,
bool _useUnderlyings,
RedeemType _redeemType,
bytes memory _incomingAssetsData
) internal {
if (_redeemType == RedeemType.OneCoin) {
(
uint256 incomingAssetPoolIndex,
uint256 minIncomingAssetAmount
) = __decodeIncomingAssetsDataRedeemOneCoin(_incomingAssetsData);
__curveRemoveLiquidityOneCoin(
_pool,
_outgoingLpTokenAmount,
int128(incomingAssetPoolIndex),
minIncomingAssetAmount,
_useUnderlyings
);
} else {
__curveRemoveLiquidity(
_pool,
_outgoingLpTokenAmount,
__decodeIncomingAssetsDataRedeemStandard(_incomingAssetsData),
_useUnderlyings
);
}
}
/// @dev Helper function to parse spend assets for redeem() and unstakeAndRedeem() calls
function __parseIncomingAssetsForRedemptionCalls(
address _pool,
bool _useUnderlyings,
RedeemType _redeemType,
bytes memory _incomingAssetsData
)
internal
view
returns (address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_)
{
if (_redeemType == RedeemType.OneCoin) {
(
uint256 incomingAssetPoolIndex,
uint256 minIncomingAssetAmount
) = __decodeIncomingAssetsDataRedeemOneCoin(_incomingAssetsData);
// No need to validate incomingAssetPoolIndex,
// as an out-of-bounds index will fail in the call to Curve
incomingAssets_ = new address[](1);
incomingAssets_[0] = __getPoolAsset(_pool, incomingAssetPoolIndex, _useUnderlyings);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else {
minIncomingAssetAmounts_ = __decodeIncomingAssetsDataRedeemStandard(
_incomingAssetsData
);
// No need to validate minIncomingAssetAmounts_.length,
// as an incorrect length will fail with the wrong n_tokens in the call to Curve
incomingAssets_ = new address[](minIncomingAssetAmounts_.length);
for (uint256 i; i < incomingAssets_.length; i++) {
incomingAssets_[i] = __getPoolAsset(_pool, i, _useUnderlyings);
}
}
return (incomingAssets_, minIncomingAssetAmounts_);
}
/// @dev Helper function to parse spend assets for lend() and lendAndStake() calls
function __parseSpendAssetsForLendingCalls(
address _pool,
uint256[] memory _orderedOutgoingAssetAmounts,
bool _useUnderlyings
) internal view returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_) {
uint256 spendAssetsCount;
for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) {
if (_orderedOutgoingAssetAmounts[i] > 0) {
spendAssetsCount++;
}
}
spendAssets_ = new address[](spendAssetsCount);
spendAssetAmounts_ = new uint256[](spendAssetsCount);
uint256 spendAssetsIndex;
for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) {
if (_orderedOutgoingAssetAmounts[i] > 0) {
spendAssets_[spendAssetsIndex] = __getPoolAsset(_pool, i, _useUnderlyings);
spendAssetAmounts_[spendAssetsIndex] = _orderedOutgoingAssetAmounts[i];
spendAssetsIndex++;
if (spendAssetsIndex == spendAssetsCount) {
break;
}
}
}
return (spendAssets_, spendAssetAmounts_);
}
/// @dev Helper to get a pool asset at a given index
function __getPoolAsset(
address _pool,
uint256 _index,
bool _useUnderlying
) internal view returns (address asset_) {
if (_useUnderlying) {
try ICurveLiquidityPool(_pool).underlying_coins(_index) returns (
address underlyingCoin
) {
asset_ = underlyingCoin;
} catch {
asset_ = ICurveLiquidityPool(_pool).underlying_coins(int128(_index));
}
} else {
try ICurveLiquidityPool(_pool).coins(_index) returns (address coin) {
asset_ = coin;
} catch {
asset_ = ICurveLiquidityPool(_pool).coins(int128(_index));
}
}
return __castWrappedIfNativeAsset(asset_);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
// Some of these decodings are not relevant to inheriting contracts,
// and some parameters will be ignored, but this keeps the payloads
// consistent for all inheriting adapters.
/// @dev Helper to decode the encoded call arguments for claiming rewards
function __decodeClaimRewardsCallArgs(bytes memory _actionData)
internal
pure
returns (address stakingToken_)
{
return abi.decode(_actionData, (address));
}
/// @dev Helper to decode the encoded call arguments for lending and then staking
function __decodeLendAndStakeCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
uint256[] memory orderedOutgoingAssetAmounts_,
address incomingStakingToken_,
uint256 minIncomingStakingTokenAmount_,
bool useUnderlyings_
)
{
return abi.decode(_actionData, (address, uint256[], address, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
uint256[] memory orderedOutgoingAssetAmounts_,
uint256 minIncomingLpTokenAmount_,
bool useUnderlyings_
)
{
return abi.decode(_actionData, (address, uint256[], uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for redeeming
function __decodeRedeemCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
uint256 outgoingLpTokenAmount_,
bool useUnderlyings_,
RedeemType redeemType_,
bytes memory incomingAssetsData_
)
{
return abi.decode(_actionData, (address, uint256, bool, RedeemType, bytes));
}
/// @dev Helper to decode the encoded incoming assets arguments for RedeemType.OneCoin
function __decodeIncomingAssetsDataRedeemOneCoin(bytes memory _incomingAssetsData)
internal
pure
returns (uint256 incomingAssetPoolIndex_, uint256 minIncomingAssetAmount_)
{
return abi.decode(_incomingAssetsData, (uint256, uint256));
}
/// @dev Helper to decode the encoded incoming assets arguments for RedeemType.Standard
function __decodeIncomingAssetsDataRedeemStandard(bytes memory _incomingAssetsData)
internal
pure
returns (uint256[] memory orderedMinIncomingAssetAmounts_)
{
return abi.decode(_incomingAssetsData, (uint256[]));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
address incomingStakingToken_,
uint256 amount_
)
{
return abi.decode(_actionData, (address, address, uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking and then redeeming
function __decodeUnstakeAndRedeemCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
address outgoingStakingToken_,
uint256 outgoingStakingTokenAmount_,
bool useUnderlyings_,
RedeemType redeemType_,
bytes memory incomingAssetsData_
)
{
return abi.decode(_actionData, (address, address, uint256, bool, RedeemType, bytes));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _actionData)
internal
pure
returns (
address pool_,
address outgoingStakingToken_,
uint256 amount_
)
{
return abi.decode(_actionData, (address, address, uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurvePoolOwner.sol";
import "../../../../interfaces/ICurveRegistryMain.sol";
import "../../../../interfaces/ICurveRegistryMetapoolFactory.sol";
import "../../../../utils/FundDeployerOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CurvePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Curve pool tokens
contract CurvePriceFeed is IDerivativePriceFeed, FundDeployerOwnerMixin {
using SafeMath for uint256;
event CurvePoolOwnerSet(address poolOwner);
event DerivativeAdded(address indexed derivative, address indexed pool);
event DerivativeRemoved(address indexed derivative);
event InvariantProxyAssetForPoolSet(address indexed pool, address indexed invariantProxyAsset);
event PoolRemoved(address indexed pool);
event ValidatedVirtualPriceForPoolUpdated(address indexed pool, uint256 virtualPrice);
uint256 private constant ADDRESS_PROVIDER_METAPOOL_FACTORY_ID = 3;
uint256 private constant VIRTUAL_PRICE_DEVIATION_DIVISOR = 10000;
uint256 private constant VIRTUAL_PRICE_UNIT = 10**18;
ICurveAddressProvider private immutable ADDRESS_PROVIDER_CONTRACT;
uint256 private immutable VIRTUAL_PRICE_DEVIATION_THRESHOLD;
// We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools.
// Caching invariantProxyAssetDecimals in a packed storage slot
// removes an additional external call and cold SLOAD operation during value lookups.
struct PoolInfo {
address invariantProxyAsset; // 20 bytes
uint8 invariantProxyAssetDecimals; // 1 byte
uint88 lastValidatedVirtualPrice; // 11 bytes (could safely be 8-10 bytes)
}
address private curvePoolOwner;
// Pool tokens and liquidity gauge tokens are treated the same for pricing purposes
mapping(address => address) private derivativeToPool;
mapping(address => PoolInfo) private poolToPoolInfo;
// Not necessary for this contract, but used by Curve liquidity adapters
mapping(address => address) private poolToLpToken;
constructor(
address _fundDeployer,
address _addressProvider,
address _poolOwner,
uint256 _virtualPriceDeviationThreshold
) public FundDeployerOwnerMixin(_fundDeployer) {
ADDRESS_PROVIDER_CONTRACT = ICurveAddressProvider(_addressProvider);
VIRTUAL_PRICE_DEVIATION_THRESHOLD = _virtualPriceDeviationThreshold;
__setCurvePoolOwner(_poolOwner);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address pool = getPoolForDerivative(_derivative);
require(pool != address(0), "calcUnderlyingValues: _derivative is not supported");
PoolInfo memory poolInfo = getPoolInfo(pool);
uint256 virtualPrice = ICurveLiquidityPool(pool).get_virtual_price();
// Validate and update the cached lastValidatedVirtualPrice if:
/// 1. a pool requires virtual price validation, and
/// 2. the unvalidated `virtualPrice` deviates from the PoolInfo.lastValidatedVirtualPrice value
/// by more than the tolerated "deviation threshold" (e.g., 1%).
/// This is an optimization to save gas on validating non-reentrancy during the virtual price query,
/// since the virtual price increases relatively slowly as the pool accrues fees over time.
if (
poolInfo.lastValidatedVirtualPrice > 0 &&
__virtualPriceDiffExceedsThreshold(
virtualPrice,
uint256(poolInfo.lastValidatedVirtualPrice)
)
) {
__updateValidatedVirtualPrice(pool, virtualPrice);
}
underlyings_ = new address[](1);
underlyings_[0] = poolInfo.invariantProxyAsset;
underlyingAmounts_ = new uint256[](1);
if (poolInfo.invariantProxyAssetDecimals == 18) {
underlyingAmounts_[0] = _derivativeAmount.mul(virtualPrice).div(VIRTUAL_PRICE_UNIT);
} else {
underlyingAmounts_[0] = _derivativeAmount
.mul(virtualPrice)
.mul(10**uint256(poolInfo.invariantProxyAssetDecimals))
.div(VIRTUAL_PRICE_UNIT)
.div(VIRTUAL_PRICE_UNIT);
}
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return getPoolForDerivative(_asset) != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
// addPools() is the primary action to add validated lpTokens and gaugeTokens as derivatives.
// addGaugeTokens() can be used to add validated gauge tokens for an already-registered pool.
// addPoolsWithoutValidation() and addGaugeTokensWithoutValidation() can be used as overrides.
// It is possible to remove all pool data and derivatives (separately).
// It is possible to update the invariant proxy asset for any pool.
// It is possible to update whether the pool's virtual price is reenterable.
/// @notice Adds validated gaugeTokens to the price feed
/// @param _gaugeTokens The ordered gauge tokens
/// @param _pools The ordered pools corresponding to _gaugeTokens
/// @dev All params are corresponding, equal length arrays.
/// _pools must already have been added via an addPools~() function
function addGaugeTokens(address[] calldata _gaugeTokens, address[] calldata _pools)
external
onlyFundDeployerOwner
{
ICurveRegistryMain registryContract = __getRegistryMainContract();
ICurveRegistryMetapoolFactory factoryContract = __getRegistryMetapoolFactoryContract();
for (uint256 i; i < _gaugeTokens.length; i++) {
if (factoryContract.get_gauge(_pools[i]) != _gaugeTokens[i]) {
__validateGaugeMainRegistry(_gaugeTokens[i], _pools[i], registryContract);
}
}
__addGaugeTokens(_gaugeTokens, _pools);
}
/// @notice Adds unvalidated gaugeTokens to the price feed
/// @param _gaugeTokens The ordered gauge tokens
/// @param _pools The ordered pools corresponding to _gaugeTokens
/// @dev Should only be used if something is incorrectly failing in the registry validation,
/// or if gauge tokens exist outside of the registries supported by this price feed,
/// e.g., a wrapper for non-tokenized gauges.
/// All params are corresponding, equal length arrays.
/// _pools must already have been added via an addPools~() function.
function addGaugeTokensWithoutValidation(
address[] calldata _gaugeTokens,
address[] calldata _pools
) external onlyFundDeployerOwner {
__addGaugeTokens(_gaugeTokens, _pools);
}
/// @notice Adds validated Curve pool info, lpTokens, and gaugeTokens to the price feed
/// @param _pools The ordered Curve pools
/// @param _invariantProxyAssets The ordered invariant proxy assets corresponding to _pools,
/// e.g., WETH for ETH-based pools
/// @param _reentrantVirtualPrices The ordered flags corresponding to _pools,
/// true if the get_virtual_price() function is potentially reenterable
/// @param _lpTokens The ordered lpToken corresponding to _pools
/// @param _gaugeTokens The ordered gauge token corresponding to _pools
/// @dev All params are corresponding, equal length arrays.
/// address(0) can be used for any _gaugeTokens index to omit the gauge (e.g., no gauge token exists).
/// _lpTokens is not technically necessary since it is knowable from a Curve registry,
/// but it's better to use Curve's upgradable contracts as an input validation rather than fully-trusted.
function addPools(
address[] calldata _pools,
address[] calldata _invariantProxyAssets,
bool[] calldata _reentrantVirtualPrices,
address[] calldata _lpTokens,
address[] calldata _gaugeTokens
) external onlyFundDeployerOwner {
ICurveRegistryMain registryContract = __getRegistryMainContract();
ICurveRegistryMetapoolFactory factoryContract = __getRegistryMetapoolFactoryContract();
for (uint256 i; i < _pools.length; i++) {
// Validate the lpToken and gauge token based on registry
if (_lpTokens[i] == registryContract.get_lp_token(_pools[i])) {
// Main registry
if (_gaugeTokens[i] != address(0)) {
__validateGaugeMainRegistry(_gaugeTokens[i], _pools[i], registryContract);
}
} else if (_lpTokens[i] == _pools[i] && factoryContract.get_n_coins(_pools[i]) > 0) {
// Metapool factory registry
// lpToken and pool are the same address
// get_n_coins() is arbitrarily used to validate the pool is on this registry
if (_gaugeTokens[i] != address(0)) {
__validateGaugeMetapoolFactoryRegistry(
_gaugeTokens[i],
_pools[i],
factoryContract
);
}
} else {
revert("addPools: Invalid inputs");
}
}
__addPools(
_pools,
_invariantProxyAssets,
_reentrantVirtualPrices,
_lpTokens,
_gaugeTokens
);
}
/// @notice Adds unvalidated Curve pool info, lpTokens, and gaugeTokens to the price feed
/// @param _pools The ordered Curve pools
/// @param _invariantProxyAssets The ordered invariant proxy assets corresponding to _pools,
/// e.g., WETH for ETH-based pools
/// @param _reentrantVirtualPrices The ordered flags corresponding to _pools,
/// true if the get_virtual_price() function is potentially reenterable
/// @param _lpTokens The ordered lpToken corresponding to _pools
/// @param _gaugeTokens The ordered gauge token corresponding to _pools
/// @dev Should only be used if something is incorrectly failing in the registry validation,
/// or if pools exist outside of the registries supported by this price feed.
/// All params are corresponding, equal length arrays.
/// address(0) can be used for any _gaugeTokens index to omit the gauge (e.g., no gauge token exists).
function addPoolsWithoutValidation(
address[] calldata _pools,
address[] calldata _invariantProxyAssets,
bool[] calldata _reentrantVirtualPrices,
address[] calldata _lpTokens,
address[] calldata _gaugeTokens
) external onlyFundDeployerOwner {
__addPools(
_pools,
_invariantProxyAssets,
_reentrantVirtualPrices,
_lpTokens,
_gaugeTokens
);
}
/// @notice Removes derivatives from the price feed
/// @param _derivatives The derivatives to remove
/// @dev Unlikely to be needed, just in case of bad storage entry.
/// Can remove both lpToken and gaugeToken from derivatives list,
/// but does not remove lpToken from pool info cache.
function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner {
for (uint256 i; i < _derivatives.length; i++) {
delete derivativeToPool[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @notice Removes pools from the price feed
/// @param _pools The pools to remove
/// @dev Unlikely to be needed, just in case of bad storage entry.
/// Does not remove lpToken nor gauge tokens from derivatives list.
function removePools(address[] calldata _pools) external onlyFundDeployerOwner {
for (uint256 i; i < _pools.length; i++) {
delete poolToPoolInfo[_pools[i]];
delete poolToLpToken[_pools[i]];
emit PoolRemoved(_pools[i]);
}
}
/// @notice Sets the Curve pool owner
/// @param _nextPoolOwner The next pool owner value
function setCurvePoolOwner(address _nextPoolOwner) external onlyFundDeployerOwner {
__setCurvePoolOwner(_nextPoolOwner);
}
/// @notice Updates the PoolInfo for the given pools
/// @param _pools The ordered pools
/// @param _invariantProxyAssets The ordered invariant asset proxy assets
/// @param _reentrantVirtualPrices The ordered flags corresponding to _pools,
/// true if the get_virtual_price() function is potentially reenterable
function updatePoolInfo(
address[] calldata _pools,
address[] calldata _invariantProxyAssets,
bool[] calldata _reentrantVirtualPrices
) external onlyFundDeployerOwner {
require(
_pools.length == _invariantProxyAssets.length &&
_pools.length == _reentrantVirtualPrices.length,
"updatePoolInfo: Unequal arrays"
);
for (uint256 i; i < _pools.length; i++) {
__setPoolInfo(_pools[i], _invariantProxyAssets[i], _reentrantVirtualPrices[i]);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to add a derivative to the price feed
function __addDerivative(address _derivative, address _pool) private {
require(
getPoolForDerivative(_derivative) == address(0),
"__addDerivative: Already exists"
);
// Assert that the assumption that all Curve pool tokens are 18 decimals
require(ERC20(_derivative).decimals() == 18, "__addDerivative: Not 18-decimal");
derivativeToPool[_derivative] = _pool;
emit DerivativeAdded(_derivative, _pool);
}
/// @dev Helper for common logic in addGauges~() functions
function __addGaugeTokens(address[] calldata _gaugeTokens, address[] calldata _pools) private {
require(_gaugeTokens.length == _pools.length, "__addGaugeTokens: Unequal arrays");
for (uint256 i; i < _gaugeTokens.length; i++) {
require(
getLpTokenForPool(_pools[i]) != address(0),
"__addGaugeTokens: Pool not registered"
);
// Not-yet-registered _gaugeTokens[i] tested in __addDerivative()
__addDerivative(_gaugeTokens[i], _pools[i]);
}
}
/// @dev Helper for common logic in addPools~() functions
function __addPools(
address[] calldata _pools,
address[] calldata _invariantProxyAssets,
bool[] calldata _reentrantVirtualPrices,
address[] calldata _lpTokens,
address[] calldata _gaugeTokens
) private {
require(
_pools.length == _invariantProxyAssets.length &&
_pools.length == _reentrantVirtualPrices.length &&
_pools.length == _lpTokens.length &&
_pools.length == _gaugeTokens.length,
"__addPools: Unequal arrays"
);
for (uint256 i; i < _pools.length; i++) {
// Redundant for validated addPools()
require(_lpTokens[i] != address(0), "__addPools: Empty lpToken");
// Empty _pools[i] reverts during __validatePoolCompatibility
// Empty _invariantProxyAssets[i] reverts during __setPoolInfo
// Validate new pool's compatibility with price feed
require(getLpTokenForPool(_pools[i]) == address(0), "__addPools: Already registered");
__validatePoolCompatibility(_pools[i]);
// Register pool info
__setPoolInfo(_pools[i], _invariantProxyAssets[i], _reentrantVirtualPrices[i]);
poolToLpToken[_pools[i]] = _lpTokens[i];
// Add lpToken and gauge token as derivatives
__addDerivative(_lpTokens[i], _pools[i]);
if (_gaugeTokens[i] != address(0)) {
__addDerivative(_gaugeTokens[i], _pools[i]);
}
}
}
/// @dev Helper to get the main Curve registry contract
function __getRegistryMainContract() private view returns (ICurveRegistryMain contract_) {
return ICurveRegistryMain(ADDRESS_PROVIDER_CONTRACT.get_registry());
}
/// @dev Helper to get the Curve metapool factory registry contract
function __getRegistryMetapoolFactoryContract()
private
view
returns (ICurveRegistryMetapoolFactory contract_)
{
return
ICurveRegistryMetapoolFactory(
ADDRESS_PROVIDER_CONTRACT.get_address(ADDRESS_PROVIDER_METAPOOL_FACTORY_ID)
);
}
/// @dev Helper to call a known non-reenterable pool function
function __makeNonReentrantPoolCall(address _pool) private {
ICurvePoolOwner(getCurvePoolOwner()).withdraw_admin_fees(_pool);
}
/// @dev Helper to set the Curve pool owner
function __setCurvePoolOwner(address _nextPoolOwner) private {
curvePoolOwner = _nextPoolOwner;
emit CurvePoolOwnerSet(_nextPoolOwner);
}
/// @dev Helper to set the PoolInfo for a given pool
function __setPoolInfo(
address _pool,
address _invariantProxyAsset,
bool _reentrantVirtualPrice
) private {
uint256 lastValidatedVirtualPrice;
if (_reentrantVirtualPrice) {
// Validate the virtual price by calling a non-reentrant pool function
__makeNonReentrantPoolCall(_pool);
lastValidatedVirtualPrice = ICurveLiquidityPool(_pool).get_virtual_price();
emit ValidatedVirtualPriceForPoolUpdated(_pool, lastValidatedVirtualPrice);
}
poolToPoolInfo[_pool] = PoolInfo({
invariantProxyAsset: _invariantProxyAsset,
invariantProxyAssetDecimals: ERC20(_invariantProxyAsset).decimals(),
lastValidatedVirtualPrice: uint88(lastValidatedVirtualPrice)
});
emit InvariantProxyAssetForPoolSet(_pool, _invariantProxyAsset);
}
/// @dev Helper to update the last validated virtual price for a given pool
function __updateValidatedVirtualPrice(address _pool, uint256 _virtualPrice) private {
// Validate the virtual price by calling a non-reentrant pool function
__makeNonReentrantPoolCall(_pool);
// _virtualPrice is now considered valid
poolToPoolInfo[_pool].lastValidatedVirtualPrice = uint88(_virtualPrice);
emit ValidatedVirtualPriceForPoolUpdated(_pool, _virtualPrice);
}
/// @dev Helper to validate a gauge on the main Curve registry
function __validateGaugeMainRegistry(
address _gauge,
address _pool,
ICurveRegistryMain _mainRegistryContract
) private view {
(address[10] memory gauges, ) = _mainRegistryContract.get_gauges(_pool);
for (uint256 i; i < gauges.length; i++) {
if (_gauge == gauges[i]) {
return;
}
}
revert("__validateGaugeMainRegistry: Invalid gauge");
}
/// @dev Helper to validate a gauge on the Curve metapool factory registry
function __validateGaugeMetapoolFactoryRegistry(
address _gauge,
address _pool,
ICurveRegistryMetapoolFactory _metapoolFactoryRegistryContract
) private view {
require(
_gauge == _metapoolFactoryRegistryContract.get_gauge(_pool),
"__validateGaugeMetapoolFactoryRegistry: Invalid gauge"
);
}
/// @dev Helper to validate a pool's compatibility with the price feed.
/// Pool must implement expected get_virtual_price() function.
function __validatePoolCompatibility(address _pool) private view {
require(
ICurveLiquidityPool(_pool).get_virtual_price() > 0,
"__validatePoolCompatibility: Incompatible"
);
}
/// @dev Helper to check if the difference between lastValidatedVirtualPrice and the current virtual price
/// exceeds the allowed threshold before the current virtual price must be validated and stored
function __virtualPriceDiffExceedsThreshold(
uint256 _currentVirtualPrice,
uint256 _lastValidatedVirtualPrice
) private view returns (bool exceedsThreshold_) {
// Uses the absolute delta between current and last validated virtual prices for the rare
// case where a virtual price might have decreased (e.g., rounding, slashing, yet unknown
// manipulation vector, etc)
uint256 absDiff;
if (_currentVirtualPrice > _lastValidatedVirtualPrice) {
absDiff = _currentVirtualPrice.sub(_lastValidatedVirtualPrice);
} else {
absDiff = _lastValidatedVirtualPrice.sub(_currentVirtualPrice);
}
return
absDiff >
_lastValidatedVirtualPrice.mul(VIRTUAL_PRICE_DEVIATION_THRESHOLD).div(
VIRTUAL_PRICE_DEVIATION_DIVISOR
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the Curve pool owner
/// @return poolOwner_ The Curve pool owner
function getCurvePoolOwner() public view returns (address poolOwner_) {
return curvePoolOwner;
}
/// @notice Gets the lpToken for a given pool
/// @param _pool The pool
/// @return lpToken_ The lpToken
function getLpTokenForPool(address _pool) public view returns (address lpToken_) {
return poolToLpToken[_pool];
}
/// @notice Gets the stored PoolInfo for a given pool
/// @param _pool The pool
/// @return poolInfo_ The PoolInfo
function getPoolInfo(address _pool) public view returns (PoolInfo memory poolInfo_) {
return poolToPoolInfo[_pool];
}
/// @notice Gets the pool for a given derivative
/// @param _derivative The derivative
/// @return pool_ The pool
function getPoolForDerivative(address _derivative) public view returns (address pool_) {
return derivativeToPool[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title IStakingWrapper interface
/// @author Enzyme Council <[email protected]>
interface IStakingWrapper {
struct TotalHarvestData {
uint128 integral;
uint128 lastCheckpointBalance;
}
struct UserHarvestData {
uint128 integral;
uint128 claimableReward;
}
function claimRewardsFor(address _for)
external
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_);
function deposit(uint256 _amount) external;
function depositTo(address _to, uint256 _amount) external;
function withdraw(uint256 _amount, bool _claimRewards)
external
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_);
function withdrawTo(
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external;
function withdrawToOnBehalf(
address _onBehalf,
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external;
// STATE GETTERS
function getRewardTokenAtIndex(uint256 _index) external view returns (address rewardToken_);
function getRewardTokenCount() external view returns (uint256 count_);
function getRewardTokens() external view returns (address[] memory rewardTokens_);
function getTotalHarvestDataForRewardToken(address _rewardToken)
external
view
returns (TotalHarvestData memory totalHarvestData_);
function getUserHarvestDataForRewardToken(address _user, address _rewardToken)
external
view
returns (UserHarvestData memory userHarvestData_);
function isPaused() external view returns (bool isPaused_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../utils/AddressArrayLib.sol";
import "./IStakingWrapper.sol";
/// @title StakingWrapperBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for staking wrappers
/// @dev Can be used as a base for both standard deployments and proxy targets.
/// Draws on Convex's ConvexStakingWrapper implementation (https://github.com/convex-eth/platform/blob/main/contracts/contracts/wrappers/ConvexStakingWrapper.sol),
/// which is based on Curve.fi gauge wrappers (https://github.com/curvefi/curve-dao-contracts/tree/master/contracts/gauges/wrappers)
abstract contract StakingWrapperBase is IStakingWrapper, ERC20, ReentrancyGuard {
using AddressArrayLib for address[];
using SafeERC20 for ERC20;
using SafeMath for uint256;
event Deposited(address indexed from, address indexed to, uint256 amount);
event PauseToggled(bool isPaused);
event RewardsClaimed(
address caller,
address indexed user,
address[] rewardTokens,
uint256[] claimedAmounts
);
event RewardTokenAdded(address token);
event TotalHarvestIntegralUpdated(address indexed rewardToken, uint256 integral);
event TotalHarvestLastCheckpointBalanceUpdated(
address indexed rewardToken,
uint256 lastCheckpointBalance
);
event UserHarvestUpdated(
address indexed user,
address indexed rewardToken,
uint256 integral,
uint256 claimableReward
);
event Withdrawn(
address indexed caller,
address indexed from,
address indexed to,
uint256 amount
);
uint8 private constant DEFAULT_DECIMALS = 18;
uint256 private constant INTEGRAL_PRECISION = 1e18;
address internal immutable OWNER;
// Paused stops new deposits and checkpoints
bool private paused;
address[] private rewardTokens;
mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData;
mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData;
modifier onlyOwner() {
require(msg.sender == OWNER, "Only owner callable");
_;
}
constructor(
address _owner,
string memory _tokenName,
string memory _tokenSymbol
) public ERC20(_tokenName, _tokenSymbol) {
OWNER = _owner;
}
/// @notice Toggles pause for deposit and harvesting new rewards
/// @param _isPaused True if next state is paused, false if unpaused
function togglePause(bool _isPaused) external onlyOwner {
paused = _isPaused;
emit PauseToggled(_isPaused);
}
////////////////////////////
// DEPOSITOR INTERACTIONS //
////////////////////////////
// CLAIM REWARDS
/// @notice Claims all rewards for a given account
/// @param _for The account for which to claim rewards
/// @return rewardTokens_ The reward tokens
/// @return claimedAmounts_ The reward token amounts claimed
/// @dev Can be called off-chain to simulate the total harvestable rewards for a particular user
function claimRewardsFor(address _for)
external
override
nonReentrant
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
return __checkpointAndClaim(_for);
}
// DEPOSIT
/// @notice Deposits tokens to be staked, minting staking token to sender
/// @param _amount The amount of tokens to deposit
function deposit(uint256 _amount) external override {
__deposit(msg.sender, msg.sender, _amount);
}
/// @notice Deposits tokens to be staked, minting staking token to a specified account
/// @param _to The account to receive staking tokens
/// @param _amount The amount of tokens to deposit
function depositTo(address _to, uint256 _amount) external override {
__deposit(msg.sender, _to, _amount);
}
/// @dev Helper to deposit tokens to be staked
function __deposit(
address _from,
address _to,
uint256 _amount
) private nonReentrant {
require(!isPaused(), "__deposit: Paused");
// Checkpoint before minting
__checkpoint([_to, address(0)]);
_mint(_to, _amount);
__depositLogic(_from, _amount);
emit Deposited(_from, _to, _amount);
}
// WITHDRAWAL
/// @notice Withdraws staked tokens, returning tokens to the sender, and optionally claiming rewards
/// @param _amount The amount of tokens to withdraw
/// @param _claimRewards True if accrued rewards should be claimed
/// @return rewardTokens_ The reward tokens
/// @return claimedAmounts_ The reward token amounts claimed
/// @dev Setting `_claimRewards` to true will save gas over separate calls to withdraw + claim
function withdraw(uint256 _amount, bool _claimRewards)
external
override
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
return __withdraw(msg.sender, msg.sender, _amount, _claimRewards);
}
/// @notice Withdraws staked tokens, returning tokens to a specified account,
/// and optionally claims rewards to the staked token holder
/// @param _to The account to receive tokens
/// @param _amount The amount of tokens to withdraw
function withdrawTo(
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external override {
__withdraw(msg.sender, _to, _amount, _claimRewardsToHolder);
}
/// @notice Withdraws staked tokens on behalf of AccountA, returning tokens to a specified AccountB,
/// and optionally claims rewards to the staked token holder
/// @param _onBehalf The account on behalf to withdraw
/// @param _to The account to receive tokens
/// @param _amount The amount of tokens to withdraw
/// @dev The caller must have an adequate ERC20.allowance() for _onBehalf
function withdrawToOnBehalf(
address _onBehalf,
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external override {
// Validate and reduce sender approval
_approve(_onBehalf, msg.sender, allowance(_onBehalf, msg.sender).sub(_amount));
__withdraw(_onBehalf, _to, _amount, _claimRewardsToHolder);
}
/// @dev Helper to withdraw staked tokens
function __withdraw(
address _from,
address _to,
uint256 _amount,
bool _claimRewards
)
private
nonReentrant
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
// Checkpoint before burning
if (_claimRewards) {
(rewardTokens_, claimedAmounts_) = __checkpointAndClaim(_from);
} else {
__checkpoint([_from, address(0)]);
}
_burn(_from, _amount);
__withdrawLogic(_to, _amount);
emit Withdrawn(msg.sender, _from, _to, _amount);
return (rewardTokens_, claimedAmounts_);
}
/////////////
// REWARDS //
/////////////
// Rewards tokens are added by the inheriting contract. Rewards tokens should be added, but not removed.
// If new rewards tokens need to be added over time, that logic must be handled by the inheriting contract,
// and can make use of __harvestRewardsLogic() if necessary
// INTERNAL FUNCTIONS
/// @dev Helper to add new reward tokens. Silently ignores duplicates.
function __addRewardToken(address _rewardToken) internal {
if (!rewardTokens.contains(_rewardToken)) {
rewardTokens.push(_rewardToken);
emit RewardTokenAdded(_rewardToken);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to calculate an unaccounted for reward amount due to a user based on integral values
function __calcClaimableRewardForIntegralDiff(
address _account,
uint256 _totalHarvestIntegral,
uint256 _userHarvestIntegral
) private view returns (uint256 claimableReward_) {
return
balanceOf(_account).mul(_totalHarvestIntegral.sub(_userHarvestIntegral)).div(
INTEGRAL_PRECISION
);
}
/// @dev Helper to calculate an unaccounted for integral amount based on checkpoint balance diff
function __calcIntegralForBalDiff(
uint256 _supply,
uint256 _currentBalance,
uint256 _lastCheckpointBalance
) private pure returns (uint256 integral_) {
if (_supply > 0) {
uint256 balDiff = _currentBalance.sub(_lastCheckpointBalance);
if (balDiff > 0) {
return balDiff.mul(INTEGRAL_PRECISION).div(_supply);
}
}
return 0;
}
/// @dev Helper to checkpoint harvest data for specified accounts.
/// Harvests all rewards prior to checkpoint.
function __checkpoint(address[2] memory _accounts) private {
// If paused, continue to checkpoint, but don't attempt to get new rewards
if (!isPaused()) {
__harvestRewardsLogic();
}
uint256 supply = totalSupply();
uint256 rewardTokensLength = rewardTokens.length;
for (uint256 i; i < rewardTokensLength; i++) {
__updateHarvest(rewardTokens[i], _accounts, supply);
}
}
/// @dev Helper to checkpoint harvest data for specified accounts.
/// Harvests all rewards prior to checkpoint.
function __checkpointAndClaim(address _account)
private
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
// If paused, continue to checkpoint, but don't attempt to get new rewards
if (!isPaused()) {
__harvestRewardsLogic();
}
uint256 supply = totalSupply();
rewardTokens_ = rewardTokens;
claimedAmounts_ = new uint256[](rewardTokens_.length);
for (uint256 i; i < rewardTokens_.length; i++) {
claimedAmounts_[i] = __updateHarvestAndClaim(rewardTokens_[i], _account, supply);
}
emit RewardsClaimed(msg.sender, _account, rewardTokens_, claimedAmounts_);
return (rewardTokens_, claimedAmounts_);
}
/// @dev Helper to update harvest data
function __updateHarvest(
address _rewardToken,
address[2] memory _accounts,
uint256 _supply
) private {
TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken];
uint256 totalIntegral = totalHarvestData.integral;
uint256 bal = ERC20(_rewardToken).balanceOf(address(this));
uint256 integralToAdd = __calcIntegralForBalDiff(
_supply,
bal,
totalHarvestData.lastCheckpointBalance
);
if (integralToAdd > 0) {
totalIntegral = totalIntegral.add(integralToAdd);
totalHarvestData.integral = uint128(totalIntegral);
emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral);
totalHarvestData.lastCheckpointBalance = uint128(bal);
emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, bal);
}
for (uint256 i; i < _accounts.length; i++) {
// skip address(0), passed in upon mint and burn
if (_accounts[i] == address(0)) continue;
UserHarvestData storage userHarvestData
= rewardTokenToUserToHarvestData[_rewardToken][_accounts[i]];
uint256 userIntegral = userHarvestData.integral;
if (userIntegral < totalIntegral) {
uint256 claimableReward = uint256(userHarvestData.claimableReward).add(
__calcClaimableRewardForIntegralDiff(_accounts[i], totalIntegral, userIntegral)
);
userHarvestData.claimableReward = uint128(claimableReward);
userHarvestData.integral = uint128(totalIntegral);
emit UserHarvestUpdated(
_accounts[i],
_rewardToken,
totalIntegral,
claimableReward
);
}
}
}
/// @dev Helper to update harvest data and claim all rewards to holder
function __updateHarvestAndClaim(
address _rewardToken,
address _account,
uint256 _supply
) private returns (uint256 claimedAmount_) {
TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken];
uint256 totalIntegral = totalHarvestData.integral;
uint256 integralToAdd = __calcIntegralForBalDiff(
_supply,
ERC20(_rewardToken).balanceOf(address(this)),
totalHarvestData.lastCheckpointBalance
);
if (integralToAdd > 0) {
totalIntegral = totalIntegral.add(integralToAdd);
totalHarvestData.integral = uint128(totalIntegral);
emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral);
}
UserHarvestData storage userHarvestData
= rewardTokenToUserToHarvestData[_rewardToken][_account];
uint256 userIntegral = userHarvestData.integral;
claimedAmount_ = userHarvestData.claimableReward;
if (userIntegral < totalIntegral) {
userHarvestData.integral = uint128(totalIntegral);
claimedAmount_ = claimedAmount_.add(
__calcClaimableRewardForIntegralDiff(_account, totalIntegral, userIntegral)
);
emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, claimedAmount_);
}
if (claimedAmount_ > 0) {
userHarvestData.claimableReward = 0;
ERC20(_rewardToken).safeTransfer(_account, claimedAmount_);
emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, 0);
}
// Repeat balance lookup since the reward token could have irregular transfer behavior
uint256 finalBal = ERC20(_rewardToken).balanceOf(address(this));
if (finalBal < totalHarvestData.lastCheckpointBalance) {
totalHarvestData.lastCheckpointBalance = uint128(finalBal);
emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, finalBal);
}
return claimedAmount_;
}
////////////////////////////////
// REQUIRED VIRTUAL FUNCTIONS //
////////////////////////////////
/// @dev Logic to be run during a deposit, specific to the integrated protocol.
/// Do not mint staking tokens, which already happens during __deposit().
function __depositLogic(address _onBehalf, uint256 _amount) internal virtual;
/// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol.
/// Can also be used to add new rewards tokens dynamically.
/// Do not checkpoint, only harvest the rewards.
function __harvestRewardsLogic() internal virtual;
/// @dev Logic to be run during a withdrawal, specific to the integrated protocol.
/// Do not burn staking tokens, which already happens during __withdraw().
function __withdrawLogic(address _to, uint256 _amount) internal virtual;
/////////////////////
// ERC20 OVERRIDES //
/////////////////////
/// @notice Gets the token decimals
/// @return decimals_ The token decimals
/// @dev Implementing contracts should override to set different decimals
function decimals() public view virtual override returns (uint8 decimals_) {
return DEFAULT_DECIMALS;
}
/// @dev Overrides ERC20._transfer() in order to checkpoint sender and recipient pre-transfer rewards
function _transfer(
address _from,
address _to,
uint256 _amount
) internal override nonReentrant {
__checkpoint([_from, _to]);
super._transfer(_from, _to, _amount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the reward token at a particular index
/// @return rewardToken_ The reward token address
function getRewardTokenAtIndex(uint256 _index)
public
view
override
returns (address rewardToken_)
{
return rewardTokens[_index];
}
/// @notice Gets the count of reward tokens being harvested
/// @return count_ The count
function getRewardTokenCount() public view override returns (uint256 count_) {
return rewardTokens.length;
}
/// @notice Gets all reward tokens being harvested
/// @return rewardTokens_ The reward tokens
function getRewardTokens() public view override returns (address[] memory rewardTokens_) {
return rewardTokens;
}
/// @notice Gets the TotalHarvestData for a specified reward token
/// @param _rewardToken The reward token
/// @return totalHarvestData_ The TotalHarvestData
function getTotalHarvestDataForRewardToken(address _rewardToken)
public
view
override
returns (TotalHarvestData memory totalHarvestData_)
{
return rewardTokenToTotalHarvestData[_rewardToken];
}
/// @notice Gets the UserHarvestData for a specified account and reward token
/// @param _user The account
/// @param _rewardToken The reward token
/// @return userHarvestData_ The UserHarvestData
function getUserHarvestDataForRewardToken(address _user, address _rewardToken)
public
view
override
returns (UserHarvestData memory userHarvestData_)
{
return rewardTokenToUserToHarvestData[_rewardToken][_user];
}
/// @notice Checks if deposits and new reward harvesting are paused
/// @return isPaused_ True if paused
function isPaused() public view override returns (bool isPaused_) {
return paused;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./StakingWrapperBase.sol";
/// @title StakingWrapperLibBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A staking wrapper base for proxy targets, extending StakingWrapperBase
abstract contract StakingWrapperLibBase is StakingWrapperBase {
event TokenNameSet(string name);
event TokenSymbolSet(string symbol);
string private tokenName;
string private tokenSymbol;
/// @dev Helper function to set token name
function __setTokenName(string memory _name) internal {
tokenName = _name;
emit TokenNameSet(_name);
}
/// @dev Helper function to set token symbol
function __setTokenSymbol(string memory _symbol) internal {
tokenSymbol = _symbol;
emit TokenSymbolSet(_symbol);
}
/////////////////////
// ERC20 OVERRIDES //
/////////////////////
/// @notice Gets the token name
/// @return name_ The token name
/// @dev Overrides the constructor-set storage for use in proxies
function name() public view override returns (string memory name_) {
return tokenName;
}
/// @notice Gets the token symbol
/// @return symbol_ The token symbol
/// @dev Overrides the constructor-set storage for use in proxies
function symbol() public view override returns (string memory symbol_) {
return tokenSymbol;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../utils/beacon-proxy/BeaconProxyFactory.sol";
import "./ConvexCurveLpStakingWrapperLib.sol";
/// @title ConvexCurveLpStakingWrapperFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract factory for ConvexCurveLpStakingWrapper instances
contract ConvexCurveLpStakingWrapperFactory is BeaconProxyFactory {
event WrapperDeployed(uint256 indexed pid, address wrapperProxy, address curveLpToken);
IDispatcher private immutable DISPATCHER_CONTRACT;
mapping(uint256 => address) private pidToWrapper;
// Handy cache for interacting contracts
mapping(address => address) private wrapperToCurveLpToken;
modifier onlyOwner {
require(msg.sender == getOwner(), "Only the owner can call this function");
_;
}
constructor(
address _dispatcher,
address _convexBooster,
address _crvToken,
address _cvxToken
) public BeaconProxyFactory(address(0)) {
DISPATCHER_CONTRACT = IDispatcher(_dispatcher);
__setCanonicalLib(
address(
new ConvexCurveLpStakingWrapperLib(
address(this),
_convexBooster,
_crvToken,
_cvxToken
)
)
);
}
/// @notice Deploys a staking wrapper for a given Convex pool
/// @param _pid The Convex Curve pool id
/// @return wrapperProxy_ The staking wrapper proxy contract address
function deploy(uint256 _pid) external returns (address wrapperProxy_) {
require(getWrapperForConvexPool(_pid) == address(0), "deploy: Wrapper already exists");
bytes memory constructData = abi.encodeWithSelector(
ConvexCurveLpStakingWrapperLib.init.selector,
_pid
);
wrapperProxy_ = deployProxy(constructData);
pidToWrapper[_pid] = wrapperProxy_;
address lpToken = ConvexCurveLpStakingWrapperLib(wrapperProxy_).getCurveLpToken();
wrapperToCurveLpToken[wrapperProxy_] = lpToken;
emit WrapperDeployed(_pid, wrapperProxy_, lpToken);
return wrapperProxy_;
}
/// @notice Pause deposits and harvesting new rewards for the given wrappers
/// @param _wrappers The wrappers to pause
function pauseWrappers(address[] calldata _wrappers) external onlyOwner {
for (uint256 i; i < _wrappers.length; i++) {
ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(true);
}
}
/// @notice Unpauses deposits and harvesting new rewards for the given wrappers
/// @param _wrappers The wrappers to unpause
function unpauseWrappers(address[] calldata _wrappers) external onlyOwner {
for (uint256 i; i < _wrappers.length; i++) {
ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(false);
}
}
////////////////////////////////////
// BEACON PROXY FACTORY OVERRIDES //
////////////////////////////////////
/// @notice Gets the contract owner
/// @return owner_ The contract owner
function getOwner() public view override returns (address owner_) {
return DISPATCHER_CONTRACT.getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
// EXTERNAL FUNCTIONS
/// @notice Gets the Curve LP token address for a given wrapper
/// @param _wrapper The wrapper proxy address
/// @return lpToken_ The Curve LP token address
function getCurveLpTokenForWrapper(address _wrapper) external view returns (address lpToken_) {
return wrapperToCurveLpToken[_wrapper];
}
// PUBLIC FUNCTIONS
/// @notice Gets the wrapper address for a given Convex pool
/// @param _pid The Convex pool id
/// @return wrapper_ The wrapper proxy address
function getWrapperForConvexPool(uint256 _pid) public view returns (address wrapper_) {
return pidToWrapper[_pid];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../interfaces/IConvexBaseRewardPool.sol";
import "../../../interfaces/IConvexBooster.sol";
import "../../../interfaces/IConvexVirtualBalanceRewardPool.sol";
import "../StakingWrapperLibBase.sol";
/// @title ConvexCurveLpStakingWrapperLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A library contract for ConvexCurveLpStakingWrapper instances
contract ConvexCurveLpStakingWrapperLib is StakingWrapperLibBase {
IConvexBooster private immutable CONVEX_BOOSTER_CONTRACT;
address private immutable CRV_TOKEN;
address private immutable CVX_TOKEN;
address private convexPool;
uint256 private convexPoolId;
address private curveLPToken;
constructor(
address _owner,
address _convexBooster,
address _crvToken,
address _cvxToken
) public StakingWrapperBase(_owner, "", "") {
CONVEX_BOOSTER_CONTRACT = IConvexBooster(_convexBooster);
CRV_TOKEN = _crvToken;
CVX_TOKEN = _cvxToken;
}
/// @notice Initializes the proxy
/// @param _pid The Convex pool id for which to use the proxy
function init(uint256 _pid) external {
// Can validate with any variable set here
require(getCurveLpToken() == address(0), "init: Initialized");
IConvexBooster.PoolInfo memory poolInfo = CONVEX_BOOSTER_CONTRACT.poolInfo(_pid);
// Set ERC20 info on proxy
__setTokenName(string(abi.encodePacked("Enzyme Staked: ", ERC20(poolInfo.token).name())));
__setTokenSymbol(string(abi.encodePacked("stk", ERC20(poolInfo.token).symbol())));
curveLPToken = poolInfo.lptoken;
convexPool = poolInfo.crvRewards;
convexPoolId = _pid;
__addRewardToken(CRV_TOKEN);
__addRewardToken(CVX_TOKEN);
addExtraRewards();
setApprovals();
}
/// @notice Adds rewards tokens that have not yet been added to the wrapper
/// @dev Anybody can call, in case more pool tokens are added.
/// Is called prior to every new harvest.
function addExtraRewards() public {
IConvexBaseRewardPool convexPoolContract = IConvexBaseRewardPool(getConvexPool());
// Could probably exit early after validating that extraRewardsCount + 2 <= rewardsTokens.length,
// but this protects against a reward token being removed that still needs to be paid out
uint256 extraRewardsCount = convexPoolContract.extraRewardsLength();
for (uint256 i; i < extraRewardsCount; i++) {
// __addRewardToken silently ignores duplicates
__addRewardToken(
IConvexVirtualBalanceRewardPool(convexPoolContract.extraRewards(i)).rewardToken()
);
}
}
/// @notice Sets necessary ERC20 approvals, as-needed
function setApprovals() public {
ERC20(getCurveLpToken()).safeApprove(address(CONVEX_BOOSTER_CONTRACT), type(uint256).max);
}
////////////////////////////////
// STAKING WRAPPER BASE LOGIC //
////////////////////////////////
/// @dev Logic to be run during a deposit, specific to the integrated protocol.
/// Do not mint staking tokens, which already happens during __deposit().
function __depositLogic(address _from, uint256 _amount) internal override {
ERC20(getCurveLpToken()).safeTransferFrom(_from, address(this), _amount);
CONVEX_BOOSTER_CONTRACT.deposit(convexPoolId, _amount, true);
}
/// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol.
/// Can also be used to add new rewards tokens dynamically.
/// Do not checkpoint, only harvest the rewards.
function __harvestRewardsLogic() internal override {
// It's probably overly-cautious to check rewards on every call,
// but even when the pool has 1 extra reward token (most have 0) it only adds ~10-15k gas units,
// so more convenient to always check than to monitor for rewards changes.
addExtraRewards();
IConvexBaseRewardPool(getConvexPool()).getReward();
}
/// @dev Logic to be run during a withdrawal, specific to the integrated protocol.
/// Do not burn staking tokens, which already happens during __withdraw().
function __withdrawLogic(address _to, uint256 _amount) internal override {
IConvexBaseRewardPool(getConvexPool()).withdrawAndUnwrap(_amount, false);
ERC20(getCurveLpToken()).safeTransfer(_to, _amount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the associated Convex reward pool address
/// @return convexPool_ The reward pool
function getConvexPool() public view returns (address convexPool_) {
return convexPool;
}
/// @notice Gets the associated Convex reward pool id (pid)
/// @return convexPoolId_ The pid
function getConvexPoolId() public view returns (uint256 convexPoolId_) {
return convexPoolId;
}
/// @notice Gets the associated Curve LP token
/// @return curveLPToken_ The Curve LP token
function getCurveLpToken() public view returns (address curveLPToken_) {
return curveLPToken;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IConvexBaseRewardPool Interface
/// @author Enzyme Council <[email protected]>
interface IConvexBaseRewardPool {
function balanceOf(address) external view returns (uint256);
function extraRewards(uint256) external view returns (address);
function extraRewardsLength() external view returns (uint256);
function getReward() external returns (bool);
function withdraw(uint256, bool) external;
function withdrawAndUnwrap(uint256, bool) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title IConvexBooster Interface
/// @author Enzyme Council <[email protected]>
interface IConvexBooster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function deposit(
uint256,
uint256,
bool
) external returns (bool);
function poolInfo(uint256) external view returns (PoolInfo memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IConvexVirtualBalanceRewardPool Interface
/// @author Enzyme Council <[email protected]>
interface IConvexVirtualBalanceRewardPool {
function rewardToken() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface ICurveAddressProvider {
function get_address(uint256) external view returns (address);
function get_registry() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityPool interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityPool {
function coins(int128) external view returns (address);
function coins(uint256) external view returns (address);
function get_virtual_price() external view returns (uint256);
function underlying_coins(int128) external view returns (address);
function underlying_coins(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurvePoolOwner interface
/// @author Enzyme Council <[email protected]>
interface ICurvePoolOwner {
function withdraw_admin_fees(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveRegistryMain interface
/// @author Enzyme Council <[email protected]>
/// @notice Limited interface for the Curve Registry contract at ICurveAddressProvider.get_address(0)
interface ICurveRegistryMain {
function get_gauges(address) external view returns (address[10] memory, int128[10] memory);
function get_lp_token(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveRegistryMetapoolFactory interface
/// @author Enzyme Council <[email protected]>
/// @notice Limited interface for the Curve Registry contract at ICurveAddressProvider.get_address(3)
interface ICurveRegistryMetapoolFactory {
function get_gauge(address) external view returns (address);
function get_n_coins(address) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to aggregate amounts of the same assets
function __aggregateAssetAmounts(address[] memory _rawAssets, uint256[] memory _rawAmounts)
internal
pure
returns (address[] memory aggregatedAssets_, uint256[] memory aggregatedAmounts_)
{
if (_rawAssets.length == 0) {
return (aggregatedAssets_, aggregatedAmounts_);
}
uint256 aggregatedAssetCount = 1;
for (uint256 i = 1; i < _rawAssets.length; i++) {
bool contains;
for (uint256 j; j < i; j++) {
if (_rawAssets[i] == _rawAssets[j]) {
contains = true;
break;
}
}
if (!contains) {
aggregatedAssetCount++;
}
}
aggregatedAssets_ = new address[](aggregatedAssetCount);
aggregatedAmounts_ = new uint256[](aggregatedAssetCount);
uint256 aggregatedAssetIndex;
for (uint256 i; i < _rawAssets.length; i++) {
bool contains;
for (uint256 j; j < aggregatedAssetIndex; j++) {
if (_rawAssets[i] == aggregatedAssets_[j]) {
contains = true;
aggregatedAmounts_[j] += _rawAmounts[i];
break;
}
}
if (!contains) {
aggregatedAssets_[aggregatedAssetIndex] = _rawAssets[i];
aggregatedAmounts_[aggregatedAssetIndex] = _rawAmounts[i];
aggregatedAssetIndex++;
}
}
return (aggregatedAssets_, aggregatedAmounts_);
}
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IBeacon.sol";
/// @title BeaconProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract that uses the beacon pattern for instant upgrades
contract BeaconProxy {
address private immutable BEACON;
constructor(bytes memory _constructData, address _beacon) public {
BEACON = _beacon;
(bool success, bytes memory returnData) = IBeacon(_beacon).getCanonicalLib().delegatecall(
_constructData
);
require(success, string(returnData));
}
// solhint-disable-next-line no-complex-fallback
fallback() external payable {
address contractLogic = IBeacon(BEACON).getCanonicalLib();
assembly {
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
receive() external payable {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./BeaconProxy.sol";
import "./IBeaconProxyFactory.sol";
/// @title BeaconProxyFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice Factory contract that deploys beacon proxies
abstract contract BeaconProxyFactory is IBeaconProxyFactory {
event CanonicalLibSet(address nextCanonicalLib);
event ProxyDeployed(address indexed caller, address proxy, bytes constructData);
address private canonicalLib;
constructor(address _canonicalLib) public {
__setCanonicalLib(_canonicalLib);
}
/// @notice Deploys a new proxy instance
/// @param _constructData The constructor data with which to call `init()` on the deployed proxy
/// @return proxy_ The proxy address
function deployProxy(bytes memory _constructData) public override returns (address proxy_) {
proxy_ = address(new BeaconProxy(_constructData, address(this)));
emit ProxyDeployed(msg.sender, proxy_, _constructData);
return proxy_;
}
/// @notice Gets the canonical lib used by all proxies
/// @return canonicalLib_ The canonical lib
function getCanonicalLib() public view override returns (address canonicalLib_) {
return canonicalLib;
}
/// @notice Gets the contract owner
/// @return owner_ The contract owner
function getOwner() public view virtual returns (address owner_);
/// @notice Sets the next canonical lib used by all proxies
/// @param _nextCanonicalLib The next canonical lib
function setCanonicalLib(address _nextCanonicalLib) public override {
require(
msg.sender == getOwner(),
"setCanonicalLib: Only the owner can call this function"
);
__setCanonicalLib(_nextCanonicalLib);
}
/// @dev Helper to set the next canonical lib
function __setCanonicalLib(address _nextCanonicalLib) internal {
canonicalLib = _nextCanonicalLib;
emit CanonicalLibSet(_nextCanonicalLib);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
} | SPDX-License-Identifier: GPL-3.0/ @title AddressArray Library @author Enzyme Council <[email protected]> @notice A library to extend the address array data type STORAGE | library AddressArrayLib {
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
function deposit(
uint256,
uint256,
bool
) external returns (bool);
function poolInfo(uint256) external view returns (PoolInfo memory);
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
function deposit(
uint256,
uint256,
bool
) external returns (bool);
function poolInfo(uint256) external view returns (PoolInfo memory);
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
function deposit(
uint256,
uint256,
bool
) external returns (bool);
function poolInfo(uint256) external view returns (PoolInfo memory);
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
function deposit(
uint256,
uint256,
bool
) external returns (bool);
function poolInfo(uint256) external view returns (PoolInfo memory);
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
}
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
pragma solidity 0.6.12;
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
} else if (remainingItemsCount > 0) {
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
| 10,238,211 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
4948,
48,
17,
23,
18,
20,
19,
225,
5267,
1076,
18694,
225,
1374,
94,
2942,
73,
385,
465,
71,
330,
411,
63,
3652,
131,
259,
1117,
65,
34,
225,
432,
5313,
358,
2133,
326,
1758,
526,
501,
618,
2347,
15553,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
5267,
1076,
5664,
288,
203,
203,
565,
445,
1206,
3245,
1180,
12,
2867,
8526,
2502,
389,
2890,
16,
1758,
389,
1726,
12765,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
6430,
3723,
67,
13,
203,
565,
445,
443,
1724,
12,
203,
3639,
2254,
5034,
16,
203,
3639,
2254,
5034,
16,
203,
3639,
1426,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
2845,
966,
12,
11890,
5034,
13,
3903,
1476,
1135,
261,
2864,
966,
3778,
1769,
203,
97,
203,
203,
203,
565,
1220,
585,
353,
1087,
434,
326,
1374,
94,
2942,
73,
4547,
18,
203,
565,
261,
71,
13,
1374,
94,
2942,
73,
385,
465,
71,
330,
411,
63,
3652,
131,
259,
1117,
65,
34,
203,
565,
2457,
326,
1983,
8630,
1779,
16,
9582,
1476,
326,
511,
2871,
23396,
203,
565,
585,
716,
1703,
16859,
598,
333,
1084,
981,
18,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
203,
97,
203,
203,
203,
565,
1220,
585,
353,
1087,
434,
326,
1374,
94,
2942,
73,
4547,
18,
203,
203,
565,
261,
71,
13,
1374,
94,
2942,
73,
385,
465,
71,
330,
411,
63,
3652,
131,
259,
1117,
65,
34,
203,
203,
565,
2457,
326,
1983,
8630,
1779,
16,
9582,
1476,
326,
511,
2871,
23396,
203,
565,
585,
716,
1703,
16859,
598,
333,
1084,
981,
18,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
203,
97,
203,
203,
203,
565,
1220,
585,
353,
1087,
434,
326,
1374,
94,
2942,
73,
4547,
18,
2
] |
./full_match/1/0x13Bdb00E3Ad547aD392E9B4f1f91EDE8ACDb77CF/sources/contracts/CIV-Vault.sol | * @dev Fetches the user information for a given strategy _id. @param _id The _id of the strategy to fetch the information for. @param _epoch The starting index to fetch the information for. @return users An array of addresses of unique depositors./ Initialize the return array with the size equal to the range between the start and end indices Loop through the mapping to populate the return array | function getDepositors(
uint _id,
uint _epoch
)
external
view
checkStrategyExistence(_id)
returns (address[] memory users)
{
users = new address[](_epochInfo[_id][_epoch].totDepositors);
for (uint i = 0; i < _epochInfo[_id][_epoch].totDepositors; i++) {
users[i] = _depositors[_id][_epoch][i];
}
}
| 9,693,330 | [
1,
14288,
326,
729,
1779,
364,
279,
864,
6252,
389,
350,
18,
225,
389,
350,
1021,
389,
350,
434,
326,
6252,
358,
2158,
326,
1779,
364,
18,
225,
389,
12015,
1021,
5023,
770,
358,
2158,
326,
1779,
364,
18,
327,
3677,
1922,
526,
434,
6138,
434,
3089,
443,
1724,
1383,
18,
19,
9190,
326,
327,
526,
598,
326,
963,
3959,
358,
326,
1048,
3086,
326,
787,
471,
679,
4295,
9720,
3059,
326,
2874,
358,
6490,
326,
327,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
758,
1724,
1383,
12,
203,
3639,
2254,
389,
350,
16,
203,
3639,
2254,
389,
12015,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
866,
4525,
4786,
802,
24899,
350,
13,
203,
3639,
1135,
261,
2867,
8526,
3778,
3677,
13,
203,
565,
288,
21281,
3639,
3677,
273,
394,
1758,
8526,
24899,
12015,
966,
63,
67,
350,
6362,
67,
12015,
8009,
3307,
758,
1724,
1383,
1769,
203,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
12015,
966,
63,
67,
350,
6362,
67,
12015,
8009,
3307,
758,
1724,
1383,
31,
277,
27245,
288,
203,
5411,
3677,
63,
77,
65,
273,
389,
323,
1724,
1383,
63,
67,
350,
6362,
67,
12015,
6362,
77,
15533,
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
] |
// CD->09.11.2015
wordentry_set CannotBeNounAdjunct=
{
eng_noun:passing{}, // The zing of the passing bullet.
eng_noun:how{},
eng_noun:why{},
eng_noun:where{},
eng_noun:what{}, // What units make sense?
eng_noun:fighting{},
eng_noun:working{},
eng_noun:Belgian{},
eng_noun:sinking{}, // With a sinking heart
eng_noun:rising{}, // A rising market.
eng_noun:not{},
eng_noun:domestic{},
eng_noun:open{},
eng_noun:two{},
eng_noun:three{},
eng_noun:four{},
eng_noun:five{},
eng_noun:six{},
eng_noun:eight{},
eng_noun:night{},
eng_noun:ten{},
eng_noun:married{},
eng_noun:nominal{},
eng_noun:different{},
eng_noun:singing{}, // Listen to that singing bird
eng_noun:calico{}, // A calico cat.
eng_noun:caloric{}, // The caloric content of foods.
eng_noun:deep{}, // The canicular heat of the Deep South.
eng_noun:carpetbag{}, // A carpetbag government.
eng_noun:cereal{}, // A cereal beverage.
eng_noun:municipal{}, // A municipal park.
eng_noun:clerical{}, // Clerical work.
eng_noun:Constitutional{}, // Constitutional walk.
eng_noun:military{}, // Military law
eng_noun:nominative{}, // Nominative noun endings
eng_noun:numeral{}, // A numeral adjective.
eng_noun:oral{}, // An oral vaccine.
eng_noun:vocal{}, // A vocal assembly.
eng_noun:verbal{}, // A verbal protest.
eng_noun:blank{}, // A blank stare.
eng_noun:comparable{}, // Pianists of comparable ability.
eng_noun:summary{}, // A summary formulation of a wide-ranging subject.
eng_noun:undecided{}, // Undecided voters
eng_noun:absolute{}, // Absolute freedom
eng_noun:rank{}, // A rank outsider.
eng_noun:total{}, // A total disaster.
eng_noun:incomplete{}, // An incomplete forward pass.
eng_noun:half{}, // She gave me a half smile.
eng_noun:partial{}, // A partial monopoly.
eng_noun:comprehensive{}, // A comprehensive survey.
eng_noun:broad{}, // An invention with broad applications.
eng_noun:cosmopolitan{}, // An issue of cosmopolitan import.
eng_noun:universal{}, // Universal experience.
eng_noun:plenary{}, // A plenary session of the legislature.
eng_noun:super{}, // A super experiment.
eng_noun:thick{}, // Thick hair
eng_noun:crisp{}, // A crisp retort.
eng_noun:cryptic{}, // A cryptic note.
eng_noun:determinate{}, // A determinate answer to the problem.
eng_noun:conditional{}, // Conditional acceptance of the terms.
eng_noun:provisional{}, // A provisional government.
eng_noun:blunt{}, // The blunt truth.
eng_noun:crude{}, // The crude facts.
eng_noun:identical{}, // Identical triangles
eng_noun:extreme{}, // Egality represents an extreme leveling of society.
eng_noun:national{}, // We support the armed services in the name of national security.
eng_noun:class{}, // National independence takes priority over class struggle.
eng_noun:connective{}, // Connective tissue in animals.
eng_noun:invincible{}, // Her invincible spirit.
eng_noun:votive{}, // Votive prayers.
eng_noun:Contradictory{}, // Contradictory attributes of unjust justice and loving vindictiveness
eng_noun:controversial{}, // A controversial decision on affirmative action.
eng_noun:spectacular{}, // A spectacular rise in prices.
eng_noun:constant{}, // A constant lover.
eng_noun:free{}, // A staunch defender of free speech.
eng_noun:creative{}, // Creative work.
eng_noun:formative{}, // A formative experience.
eng_noun:affirmative{}, // A controversial decision on affirmative action.
eng_noun:back{}, // The back hall is an inconvenient place for the telephone.
eng_noun:local{}, // Local customs
eng_noun:legal{}, // The legal profession
eng_noun:Judicial{}, // Judicial system
eng_noun:illative{}, // The illative faculty of the mind.
eng_noun:incendiary{}, // An incendiary fire
eng_noun:imperial{},
eng_noun:British{}, // The imperial gallon was standardized legally throughout the British Empire
eng_noun:humanist{}, // The humanist belief in continuous emergent evolution.
eng_noun:horary{}, // The horary cycle
eng_noun:home{}, // My home town
eng_noun:graphic{}, // A graphic presentation of the data
eng_noun:generic{}, // The generic name
eng_noun:existentialist{}, // The existentialist character of his ideas
eng_noun:fishy{}, // The soup had a fishy smell.
eng_noun:Byzantine{}, // Byzantine monks
eng_noun:Occipital{}, // Occipital bone
eng_noun:Angular{}, // Angular momentum
eng_noun:Educational{}, // Educational psychology
eng_noun:Developmental{}, // Developmental psychology
eng_noun:Epileptic{}, // Epileptic seizure
eng_noun:Transdermal{}, // Transdermal estrogen
eng_noun:sectional{}, // A sectional view
eng_noun:African{}, // African languages{}, // African languages
eng_noun:Anglican{}, // An Anglican bishop
eng_noun:Christian{}, // Christian rites
eng_noun:Dutch{}, // Dutch painting
eng_noun:Danish{}, // Danish furniture
eng_noun:Norwegian{}, // Norwegian herring
eng_noun:Swedish{}, // Swedish punch
eng_noun:Finnish{}, // Finnish architecture
eng_noun:Austrian{}, // Austrian music
eng_noun:Mormon{}, // Mormon leaders
eng_noun:Methodist{}, // Methodist theology
eng_noun:Lutheran{}, // Lutheran doctrines
eng_noun:Bavarian{}, // Bavarian beer
eng_noun:Cuban{}, // Cuban rum
eng_noun:Salvadoran{}, // Salvadoran coffee
eng_noun:Asian{}, // Asian countries
eng_noun:European{}, // European Community
eng_noun:Korean{}, // Korean handicrafts
eng_noun:Colombian{}, // Colombian coffee
eng_noun:Argentinian{}, // Argentinian tango
eng_noun:Venezuelan{}, // Venezuelan oil
eng_noun:Panamanian{}, // Panamanian economy
eng_noun:Ecuadorian{}, // Ecuadorian folklore
eng_noun:Peruvian{}, // Peruvian artifacts
eng_noun:Chilean{}, // Chilean volcanoes
eng_noun:Tibetan{}, // Tibetan monks
eng_noun:Paradigmatic{}, // Paradigmatic learning
eng_noun:Japanese{}, // Japanese cars
eng_noun:Chinese{}, // Chinese food
eng_noun:Slovenian{}, // Slovenian independence
eng_noun:Croatian{}, // Croatian villages
eng_noun:Protestant{}, // A Protestant denomination
eng_noun:physical{}, // A study of the physical properties of atomic particles
eng_noun:street{}, // Liverpudlian street urchins
eng_noun:Haitian{}, // Haitian shantytowns
eng_noun:Guatemalan{}, // Guatemalan coffee
eng_noun:Gothic{}, // Gothic migrations
eng_noun:Gabonese{}, // Gabonese hills
eng_noun:Franciscan{}, // Franciscan monks
eng_noun:Ethiopian{}, // Ethiopian immigrants
eng_noun:Empiric{}, // Empiric treatment
eng_noun:Dominican{}, // Dominican monks
eng_noun:creole{}, // creole cooking
eng_noun:Malawian{}, // Malawian hills
eng_noun:Macedonian{}, // Macedonian hills
eng_noun:Liverpudlian{}, // Liverpudlian streets
eng_noun:Lilliputian{}, // The Lilliputian population
eng_noun:Libyan{}, // The Libyan desert
eng_noun:inevitable{}, // The inevitable result.
eng_noun:metal{}, // The steady dripping of water rusted the metal stopper in the sink.
eng_noun:motive{}, // A motive force.
eng_noun:incurable{}, // An incurable optimist.
eng_noun:static{}, // A static population.
eng_noun:chemical{}, // A reversible chemical reaction.
eng_noun:social{}, // A rise in crime symptomatic of social breakdown.
eng_noun:rash{}, // A rash symptomatic of scarlet fever.
eng_noun:marginal{}, // The marginal strip of beach.
eng_noun:certifiable{}, // A certifiable fact.
eng_noun:third{}, // The third generation of computers.
eng_noun:regular{}, // The regular sequence of the seasons.
eng_noun:incandescent{}, // An incandescent bulb.
eng_noun:delicate{}, // His delicate health.
eng_noun:human{}, // The human condition.
eng_noun:family{}, // He charted his family tree genealogically.
eng_noun:metric{}, // The metric system
eng_noun:special{}, // a special antenna for public relations
eng_noun:public{}, // a special antenna for public relations
eng_noun:living{}, // The relatedness of all living things.
eng_noun:animal{}, // The animal constituent of plankton.
eng_noun:proverbial{}, // The proverbial grasshopper
eng_noun:capitalist{}, // A capitalist nation
eng_noun:Utopian{}, // A Utopian novel
eng_noun:ceramic{}, // A ceramic dish
eng_noun:industrial{}, // The industrial base of Japan
eng_noun:divine{}, // a sort of divine madness
eng_noun:reading{}, // A diagnostic reading test
eng_noun:diagnostic{}, // A diagnostic reading test
eng_noun:citrus{}, // The citrus production of Florida
eng_noun:Cameroonian{}, // The Cameroonian capital
eng_noun:Fijian{}, // The Fijian population
eng_noun:feudatory{}, // A feudatory relationship
eng_noun:Djiboutian{}, // A Djiboutian storyteller
eng_noun:modern{}, // Economics in its modern disciplinary sense
eng_noun:Mongolian{}, // The Mongolian embassy
eng_noun:indicative{}, // Indicative mood
eng_noun:Pre-Raphaelite{}, // The Pre-Raphaelite painters
eng_noun:polynomial{}, // A polynomial expression
eng_noun:Philharmonic{}, // Philharmonic players
eng_noun:Paralytic{}, // Paralytic symptoms
eng_noun:ruling{}, // The Qatari ruling family
eng_noun:rapid{}, // His rapid manner of talking
eng_noun:pharmaceutical{}, // The pharmaceutical industry
eng_noun:Partitive{}, // Partitive tendencies in education
eng_noun:Participial{}, // Participial inflections
eng_noun:Parthian{}, // Parthian archeology
eng_noun:Papuan{}, // Papuan vowels
eng_noun:native{}, // Papuan native crafts
eng_noun:Reversionary{}, // Reversionary interest
eng_noun:folk{}, // Romany folk songs
eng_noun:gypsy{}, // A Gypsy fortune-teller
eng_noun:Rwandan{}, // Rwandan mountains
eng_noun:shakedown{},
eng_noun:Pyrrhic{}, // A Pyrrhic victory
eng_noun:Quadratic{}, // Quadratic equation
eng_noun:Antiphonal{}, // Antiphonal laughter
eng_noun:Processional{}, // Processional music
eng_noun:procedural{}, // A procedural violation
eng_noun:Seychellois{}, // Seychellois fishermen
eng_noun:Senegalese{}, // Senegalese villages
eng_noun:regional{}, // Regional flora
eng_noun:Singaporean{}, // Singaporean rubber
eng_noun:Siberian{}, // Siberian coal miners
eng_noun:Zairean{}, // Zairean elections
eng_noun:Yemeni{}, // Yemeni mountains
eng_noun:wheaten{}, // wheaten bread
eng_noun:Welsh{}, // The Welsh coast
eng_noun:Vietnamese{}, // Vietnamese boat people
eng_noun:vestal{}, // Vestal virgin
eng_noun:tutorial{}, // Tutorial sessions
eng_noun:Trinidadian{}, // Trinidadian rum
eng_noun:Syphilitic{}, // Syphilitic symptoms
eng_noun:tertian{}, // Tertian fever
eng_noun:textile{}, // Textile research
eng_noun:fresh{}, // Crispness of fresh lettuce
eng_noun:spastic{}, // A spastic colon
eng_noun:mutual{}, // The mutual adhesiveness of cells
eng_noun:scalar{}, // Scalar quantity
eng_noun:acrocentric{}, // An acrocentric chromosome
eng_noun:metacentric{}, // A metacentric chromosome
eng_noun:communist{}, // Communist Party
eng_noun:Hypoglycemic{}, // Hypoglycemic agents
eng_noun:Hypodermic{}, // Hypodermic needle
eng_noun:Serbian{}, // the three possible classes of Serbian nouns
eng_noun:continental{}, // The continental divide
eng_noun:diatomic{}, // A diatomic molecule
eng_noun:genital{}, // Genital herpes
eng_noun:mural{}, // Mural painting
eng_noun:frontal{}, // Frontal rainfall
eng_noun:Juvenile{}, // Juvenile diabetes
eng_noun:Ecclesiastic{}, // Ecclesiastic history
eng_noun:Antediluvian{}, // Antediluvian man
eng_noun:floral{}, // Floral organs
eng_noun:professional{}, // Professional training
eng_noun:ocular{}, // An ocular organ
eng_noun:gnostic{}, // Gnostic writings
eng_noun:Lacteal{}, // Lacteal fluids
eng_noun:Funicular{}, // Funicular railway
eng_noun:fiducial{}, // A fiducial point
eng_noun:fiduciary{}, // A fiduciary contract
eng_noun:Mauritanian{}, // Mauritanian tropical fish
eng_noun:Machiavellian{}, // Machiavellian thinking
eng_noun:Liberian{}, // Liberian ship owners
eng_noun:Latin{}, // Latin verb conjugations
eng_noun:Iranian{}, // Iranian security police
eng_noun:Indo-European{}, // Indo-European migrations
eng_noun:Exponential{}, // Exponential growth
eng_noun:Italian{}, // Italian cooking
eng_noun:German{}, // German philosophers
eng_noun:Anglo-Saxon{}, // poetry
eng_noun:Laryngeal{}, // Laryngeal infection
eng_noun:viral{}, // Viral infection
eng_noun:commercial{}, // Commercial law
eng_noun:molar{}, // molar weight
eng_noun:iambic{}, // iambic pentameter
eng_noun:jugular{}, // jugular vein
eng_noun:vocative{}, // Vocative verb endings
eng_noun:subjunctive{}, // Subjunctive verb endings
eng_noun:optative{}, // Optative verb endings
eng_noun:facial{}, // A facial massage
eng_noun:intravenous{}, // An intravenous inflammation
eng_noun:rental{}, // A rental car
eng_noun:ritual{}, // A ritual dance of Haiti
eng_noun:personal{}, // personal verb endings
eng_noun:pastoral{}, // a pastoral letter
eng_noun:lyric{}, // the lyric stage
eng_noun:hematic{}, // A hematic cyst
eng_noun:wide{}, // That team needs a decent wide player
eng_noun:sylvan{}, // A shady sylvan glade
eng_noun:hostile{}, // Freeze the assets of this hostile government.
eng_noun:seven{}, // The prisoner's resistance weakened after seven days.
eng_noun:mnemonic{}, // the mnemonic device
eng_noun:woolen{}, // a woolen sweater
eng_noun:Akkadian{}, // Let's eliminate the course on Akkadian hieroglyphics.
eng_noun:octal{}, // An octal digit.
eng_noun:audile{}, // An audile person.
eng_noun:acoustic{}, // Acoustic properties of a hall
eng_noun:Mercurial{}, // The Mercurial canals.
eng_noun:musical{}, // A musical evening
eng_noun:twelve{}, // Here is a hen with twelve chickens
eng_noun:wild{}, // I see neither human nor wild animal
eng_noun:arithmetic{}, // Some type of arithmetic computations produces an invalid result that exceeds the range of the data type involved in the computation
eng_noun:eleven{}, // The bell at eleven o'clock tells us that lesson is finished
eng_noun:nine{}, // Richard slept until nine o'clock
eng_noun:Disciplinary{}, // Disciplinary problems in the classroom
eng_noun:tatty{}, // An old house with dirty windows and tatty curtains
eng_noun:Antipodal{}, // Antipodal regions of the earth
eng_noun:reproductive{}, // Urbanization in Spain is distinctly correlated with a fall in reproductive rate.
eng_noun:luxury{}, // Sales of luxury cars dropped markedly.
eng_noun:several{}, // He gave liberally to several charities.
eng_noun:medical{}, // Amazingly, he finished medical school in three years.
eng_noun:all{}, // Visit us by all means.
eng_noun:prepositional{}, // The prepositional phrase here is used adverbially.
eng_noun:genitive{}, // The genitive noun is used attributively.
eng_noun:natural{}, // A natural conclusion follows thence.
eng_noun:global{}, // Greenspan's fraud: how two decades of his policies have undermined the global economy
eng_noun:Georgian{}, // The Georgian capital is Tbilisi.
eng_noun:final{}, // The final runners were far behind.
eng_noun:ninth{}, // The ninth century was the spiritually freest period.
eng_noun:iron{}, // That iron gate is made of iron that came from England
eng_noun:stone{}, // The moss undergrew the stone patio.
eng_noun:enemy{}, // The landscape was deforested by the enemy attacks.
eng_noun:remote{}, // The remote areas of the country were gradually built up.
eng_noun:upper{}, // This exercise will strengthen your upper body.
eng_noun:following{}, // Develop the function in the following form.
eng_noun:stock{}, // The stock market fluctuates.
eng_noun:sudden{}, // The sudden storm immobilized the traffic.
eng_noun:entire{}, // The bureaucracy paralyzes the entire operation.
eng_noun:political{}, // Reform a political system.
eng_noun:extra{}, // Add some extra plates to the dinner table.
eng_noun:plastic{}, // The temple was garishly decorated with bright plastic flowers.
eng_noun:bright{}, // The temple was garishly decorated with bright plastic flowers.
eng_noun:basic{}, // He light-heartedly overlooks some of the basic facts of life.
eng_noun:black{}, // She danced the part of the Black Swan very lyrically.
eng_noun:main{}, // He drove down the main road
eng_noun:next{}, // The boy in the next desk borrowed my pencil
eng_noun:first{}, // The first job is already done.
eng_noun:sweet{}, // These small apples have a SWEET taste
eng_noun:and{}, // the hammer AND sickle
eng_noun:will{}, // The boy WILL play with another dog
eng_noun:best{}, // He is my best friend
eng_noun:good{}, // He is a good player
eng_noun:big{}, // The big dog chased me
eng_noun:simple{},
eng_noun:invalid{}, // an invalid result exceeds the range of the data type involved in the computation
eng_noun:sharp{}, // A sharp knife cuts cleanly.
eng_noun:early{}, // An early riser gets up early.
eng_noun:straight{}, // Run in a straight line.
eng_noun:whole{}, // I ate a whole fish
eng_noun:new{}, // Have you seen my new bicycle?
eng_noun:second{}, // We were in the second class last year
eng_noun:small{}, // The small boy rings the bell
eng_noun:great{}, // The ship sank in the great storm
eng_noun:heavy{}, // Henry can lift that heavy box
eng_noun:past{}, // Don't sentimentalize the past events.
eng_noun:an{}, // We have an hour to burn.
eng_noun:running{}, // The running horse galloped down the road
eng_noun:one{},
eng_noun:no{},
eng_noun:yesterday{}, // I did the work yesterday
eng_noun:English{}, // He has an English book
eng_noun:Russian{},
eng_noun:French{}, // She spoke English with a French accent
eng_noun:Greek{}, // Ultimately, I have been studying Greek at evening classes.
eng_noun:particular{}, // Let's abstract away from this particular example.
eng_noun:over{}, // Let me think that over.
eng_noun:each{}, // Each partition acts like a separate hard drive
eng_noun:separate{}, // Each partition acts like a separate hard drive
eng_noun:hard{}, // Each partition acts like a separate hard drive
eng_noun:high{}, // The headmaster's desk stood on a high platform
eng_noun:right{}, // We didn't know the right time
eng_noun:white{}, // I see the big white cat
eng_noun:stupid{}, // a very stupid dog
eng_noun:most{}, // Most flare stars are dim red dwarfs
eng_noun:out{}, // Wrap the baby before taking her out.
eng_noun:at{},
eng_noun:clean{}, // The thieves made a clean getaway.
eng_noun:fine{}, // Don't sign a contract without reading the fine print.
eng_noun:wet{}, // The wet road was shining sleekly.
eng_noun:temporary{}, // The temporary camps were inadequately equipped.
eng_noun:single{}, // A single chicken was scratching forlornly in the yard.
eng_noun:thin{}, // The dress hung shapelessly on her thin body.
eng_noun:kind{}, // I must regretfully decline your kind invitation.
eng_noun:setting{}, // They traveled westward toward the setting sun.
eng_noun:former{}, // He treats his former wife civilly.
eng_noun:blue{}, // Birds flew zigzag across the blue sky.
eng_noun:relative{}, // This relative clause is used restrictively.
eng_noun:cold{},
eng_noun:common{}, // A common remedy is uncommonly difficult to find.
eng_noun:red{}, // I have two RED apples
eng_noun:lightning{},
eng_noun:hanging{},
eng_noun:cunning{},
eng_noun:dancing{},
eng_noun:foreboding{},
eng_noun:bearing{},
eng_noun:listing{},
eng_noun:standing{},
eng_noun:knowing{},
eng_noun:ongoing{},
eng_noun:fitting{},
eng_noun:mounting{},
eng_noun:ranking{},
eng_noun:thieving{},
eng_noun:cooking{},
eng_noun:pleading{},
eng_noun:travelling{},
eng_noun:testing{},
eng_noun:nursing{},
eng_noun:upbraiding{},
eng_noun:blinding{},
eng_noun:trotting{},
eng_noun:greening{},
eng_noun:whacking{},
eng_noun:vining{},
eng_noun:grudging{},
eng_noun:upset{},
eng_noun:evening{},
eng_noun:brown{},
eng_noun:adjective{},
eng_noun:adjectival{},
eng_noun:Fabian{},
eng_noun:abbreviate{},
eng_noun:abject{},
eng_noun:abluent{},
eng_noun:abortive{},
eng_noun:above{},
eng_noun:absolutist{},
eng_noun:abstractionist{},
eng_noun:Accadian{},
eng_noun:acceptant{},
eng_noun:Achean{},
eng_noun:orange{},
eng_noun:singular{},
eng_noun:andante{},
eng_noun:urban{},
eng_noun:mobile{},
eng_noun:wireless{},
eng_noun:epidemic{},
eng_noun:welcome{},
eng_noun:automatic{},
eng_noun:abstergent{},
eng_noun:absurd{},
eng_noun:general{},
eng_noun:Yiddish{},
eng_noun:Indian{},
eng_noun:Jacobian{},
eng_noun:minuscule{},
eng_noun:Slovene{},
eng_noun:gold{},
eng_noun:magenta{},
eng_noun:dual{},
eng_noun:weekend{},
eng_noun:counterfeit{},
eng_noun:parallel{},
eng_noun:pi{},
eng_noun:X - ray{},
eng_noun:antecedent{},
eng_noun:imperative{},
eng_noun:irregular{},
eng_noun:Castilian{},
eng_noun:pommy{},
eng_noun:quadrilateral{},
eng_noun:northeast{},
eng_noun:honey{},
eng_noun:male{},
eng_noun:anterior{},
eng_noun:collateral{},
eng_noun:weekly{},
eng_noun:quarterly{},
eng_noun:fuchsia{},
eng_noun:khaki{},
eng_noun:coral{},
eng_noun:lavender{},
eng_noun:olive{},
eng_noun:sienna{},
eng_noun:teal{},
eng_noun:taupe{},
eng_noun:amber{},
eng_noun:grape{},
eng_noun:avocado{},
eng_noun:auburn{},
eng_noun:buff{},
eng_noun:overweight{},
eng_noun:Melburnian{},
eng_noun:polycystine{},
eng_noun:canary{},
eng_noun:slim{},
eng_noun:Romanian{},
eng_noun:transgender{},
eng_noun:Muslim{},
eng_noun:blond{},
eng_noun:blonde{},
eng_noun:archaic{},
eng_noun:ideal{},
eng_noun:then{},
eng_noun:diminutive{},
eng_noun:ephemeral{},
eng_noun:stiff{},
eng_noun:fricative{},
eng_noun:cuckoo{},
eng_noun:short{},
eng_noun:salt{},
eng_noun:rough{},
eng_noun:sand{},
eng_noun:flame{},
eng_noun:horizontal{},
eng_noun:totalitarian{},
eng_noun:selenoid{},
eng_noun:flash{},
eng_noun:Ukrainian{},
eng_noun:objective{},
eng_noun:spoony{},
eng_noun:transsexual{},
eng_noun:upcast{},
eng_noun:incorrigible{},
eng_noun:reprehensible{},
eng_noun:Angolan{},
eng_noun:instrumental{},
eng_noun:maslin{},
eng_noun:dank{},
eng_noun:Faeroese{},
eng_noun:Hispano{},
eng_noun:acataleptic{},
eng_noun:alert{},
eng_noun:eclectic{},
eng_noun:precedent{},
eng_noun:intuitive{},
eng_noun:essential{},
eng_noun:Australian{},
eng_noun:quorate{},
eng_noun:hangdog{},
eng_noun:magic{},
eng_noun:due{},
eng_noun:alpha{},
eng_noun:beta{},
eng_noun:crazy{},
eng_noun:premier{},
eng_noun:sulfur{},
eng_noun:invertebrate{},
eng_noun:extraterrestrial{},
eng_noun:republican{},
eng_noun:neurotic{},
eng_noun:quick{},
eng_noun:Transylvanian{},
eng_noun:Tasmanian{},
eng_noun:Boolean{},
eng_noun:individual{},
eng_noun:Muscovite{},
eng_noun:psycho{},
eng_noun:ordinary{},
eng_noun:brash{},
eng_noun:maximum{},
eng_noun:micro{},
eng_noun:acerate{},
eng_noun:vegan{},
eng_noun:Saturnian{},
eng_noun:libertarian{},
eng_noun:characteristic{},
eng_noun:center{},
eng_noun:aqua{},
eng_noun:nonflammable{},
eng_noun:yearly{},
eng_noun:unknown{},
eng_noun:sandwich{},
eng_noun:hundred - first{},
eng_noun:hundred{},
eng_noun:Aruban{},
eng_noun:Azerbaijani{},
eng_noun:Bangladeshi{},
eng_noun:Belizean{},
eng_noun:Beninese{},
eng_noun:barbarian{},
eng_noun:Nigerien{},
eng_noun:Mauritian{},
eng_noun:Cambodian{},
eng_noun:Iraqi{},
eng_noun:Zimbabwean{},
eng_noun:Ugandan{},
eng_noun:Tuvaluan{},
eng_noun:Caymanian{},
eng_noun:Maldivian{},
eng_noun:Qatari{},
eng_noun:Samoan{},
eng_noun:Congolese{},
eng_noun:Eritrean{},
eng_noun:Nepalese{},
eng_noun:Jordanian{},
eng_noun:Kuwaiti{},
eng_noun:Malagasy{},
eng_noun:Corinthian{},
eng_noun:arcadian{},
eng_noun:Boeotian{},
eng_noun:Belizian{},
eng_noun:Kiribatian{},
eng_noun:Tokelauan{},
eng_noun:megalopolitan{},
eng_noun:trademark{},
eng_noun:Somalian{},
eng_noun:underline{},
eng_noun:zany{},
eng_noun:standout{},
eng_noun:Calabrian{},
eng_noun:monastic{},
eng_noun:land{},
eng_noun:Rosicrucian{},
eng_noun:virtual{},
eng_noun:retail{},
eng_noun:random{},
eng_noun:simian{},
eng_noun:roman{},
eng_noun:cosy{},
eng_noun:evergreen{},
eng_noun:puritan{},
eng_noun:nasty{},
eng_noun:blueberry{},
eng_noun:ersatz{},
eng_noun:nude{},
eng_noun:primavera{},
eng_noun:Marshallese{},
eng_noun:bimonthly{},
eng_noun:biweekly{},
eng_noun:decennial{},
eng_noun:bicentennial{},
eng_noun:trimillennial{},
eng_noun:killer{},
eng_noun:medium{},
eng_noun:homo{},
eng_noun:top{},
eng_noun:nudist{},
eng_noun:derogatory{},
eng_noun:wack{},
eng_noun:bulk{},
eng_noun:draft{},
eng_noun:semi - weekly{},
eng_noun:independent{},
eng_noun:alternative{},
eng_noun:sexist{},
eng_noun:ovine{},
eng_noun:opposite{},
eng_noun:sleepy{},
eng_noun:dependent{},
eng_noun:token{},
eng_noun:leviathan{},
eng_noun:dandy{},
eng_noun:pejorative{},
eng_noun:moccasin{},
eng_noun:active{},
eng_noun:actual{},
eng_noun:adhesive{},
eng_noun:adjacent{},
eng_noun:heterosexual{},
eng_noun:Buddhist{},
eng_noun:fils{},
eng_noun:vandal{},
eng_noun:ajar{},
eng_noun:sham{},
eng_noun:KIA{},
eng_noun:alternate{},
eng_noun:glutton{},
eng_noun:Asturian{},
eng_noun:intensive{},
eng_noun:amyl{},
eng_noun:anarchist{},
eng_noun:treble{},
eng_noun:ancient{},
eng_noun:Romany{},
eng_noun:Scottish{},
eng_noun:outside{},
eng_noun:agnostic{},
eng_noun:interstitial{},
eng_noun:plenty{},
eng_noun:functional{},
eng_noun:sesquipedalian{},
eng_noun:AWOL{},
eng_noun:episcopal{},
eng_noun:episcopalian{},
eng_noun:crescent{},
eng_noun:lunate{},
eng_noun:Thatcherite{},
eng_noun:serial{},
eng_noun:pedestrian{},
eng_noun:submarine{},
eng_noun:jolly{},
eng_noun:period{},
eng_noun:narrative{},
eng_noun:lowercase{},
eng_noun:fortnightly{},
eng_noun:racist{},
eng_noun:maglev{},
eng_noun:patient{},
eng_noun:stoic{},
eng_noun:print{},
eng_noun:radical{},
eng_noun:electrical{},
eng_noun:beef{},
eng_noun:supplicant{},
eng_noun:utmost{},
eng_noun:sour{},
eng_noun:moral{},
eng_noun:subversive{},
eng_noun:okay{},
eng_noun:hexadecimal{},
eng_noun:brave{},
eng_noun:incipient{},
eng_noun:Alsatian{},
eng_noun:damn{},
eng_noun:junior{},
eng_noun:Sikh{},
eng_noun:antique{},
eng_noun:med{},
eng_noun:possessive{},
eng_noun:kiasu{},
eng_noun:calm{},
eng_noun:Slovakian{},
eng_noun:horsey{},
eng_noun:tatterdemalion{},
eng_noun:Belarussian{},
eng_noun:Faroese{},
eng_noun:scotch{},
eng_noun:elective{},
eng_noun:select{},
eng_noun:cult{},
eng_noun:mercenary{},
eng_noun:vast{},
eng_noun:hardcore{},
eng_noun:eccentric{},
eng_noun:coordinate{},
eng_noun:conservative{},
eng_noun:dope{},
eng_noun:nondescript{},
eng_noun:Brobdingnagian{},
eng_noun:occidental{},
eng_noun:octuple{},
eng_noun:impossible{},
eng_noun:vanilla{},
eng_noun:bosom{},
eng_noun:azurine{},
eng_noun:axillar{},
eng_noun:awk{},
eng_noun:Avesta{},
eng_noun:savage{},
eng_noun:camp{},
eng_noun:icebox{},
eng_noun:alienate{},
eng_noun:Braille{},
eng_noun:medieval{},
eng_noun:yew{},
eng_noun:bilabial{},
eng_noun:lobster{},
eng_noun:scant{},
eng_noun:deaf{},
eng_noun:batty{},
eng_noun:artist{},
eng_noun:waterproof{},
eng_noun:technical{},
eng_noun:phosphorescent{},
eng_noun:googly{},
eng_noun:plosive{},
eng_noun:swish{},
eng_noun:Karelian{},
eng_noun:loden{},
eng_noun:clambake{},
eng_noun:velar{},
eng_noun:palatal{},
eng_noun:concomitant{},
eng_noun:leeward{},
eng_noun:plenipotentiary{},
eng_noun:virgin{},
eng_noun:adjutant{},
eng_noun:alar{},
eng_noun:neo - nazi{},
eng_noun:descendant{},
eng_noun:bygone{},
eng_noun:joint{},
eng_noun:passional{},
eng_noun:level{},
eng_noun:representative{},
eng_noun:Romaic{},
eng_noun:limit{},
eng_noun:trick{},
eng_noun:model{},
eng_noun:jazeraint{},
eng_noun:inchoate{},
eng_noun:phonetic{},
eng_noun:inchoactive{},
eng_noun:principal{},
eng_noun:tributary{},
eng_noun:pygmy{},
eng_noun:ribald{},
eng_noun:delivery{},
eng_noun:superior{},
eng_noun:lateral{},
eng_noun:reverse{},
eng_noun:endemic{},
eng_noun:cormorant{},
eng_noun:myopic{},
eng_noun:privy{},
eng_noun:verbatim{},
eng_noun:piggy{},
eng_noun:slinky{},
eng_noun:wizard{},
eng_noun:cocktail{},
eng_noun:cacuminal{},
eng_noun:blind{},
eng_noun:contrary{},
eng_noun:Novocastrian{},
eng_noun:limey{},
eng_noun:parvenu{},
eng_noun:Syracusan{},
eng_noun:ruddy{},
eng_noun:frail{},
eng_noun:bawd{},
eng_noun:borax{},
eng_noun:marcel{},
eng_noun:solute{},
eng_noun:swank{},
eng_noun:strait{},
eng_noun:botanical{},
eng_noun:cavalier{},
eng_noun:customary{},
eng_noun:devout{},
eng_noun:discount{},
eng_noun:disquiet{},
eng_noun:dominant{},
eng_noun:eleemosynary{},
eng_noun:equivocal{},
eng_noun:Erse{},
eng_noun:faint{},
eng_noun:farewell{},
eng_noun:feint{},
eng_noun:fellow{},
eng_noun:flirt{},
eng_noun:Fuegian{},
eng_noun:grand{},
eng_noun:hircine{},
eng_noun:hortatory{},
eng_noun:invective{},
eng_noun:mellow{},
eng_noun:migrant{},
eng_noun:ophidian{},
eng_noun:oyster{},
eng_noun:patrician{},
eng_noun:priority{},
eng_noun:prophylactic{},
eng_noun:sanguine{},
eng_noun:secondary{},
eng_noun:slight{},
eng_noun:snide{},
eng_noun:statistic{},
eng_noun:stray{},
eng_noun:moderate{},
eng_noun:teak{},
eng_noun:unlikely{},
eng_noun:whirlwind{},
eng_noun:formal{},
eng_noun:gimcrack{},
eng_noun:worthy{},
eng_noun:offside{},
eng_noun:auricular{},
eng_noun:reciprocal{},
eng_noun:phoney{},
eng_noun:desmoid{},
eng_noun:motel{},
eng_noun:Francophile{},
eng_noun:hyaline{},
eng_noun:Oregonian{},
eng_noun:offensive{},
eng_noun:larghetto{},
eng_noun:butch{},
eng_noun:tardy{},
eng_noun:Babylonian{},
eng_noun:miniature{},
eng_noun:adenoid{},
eng_noun:mammoth{},
eng_noun:diacritic{},
eng_noun:theatrical{},
eng_noun:mid - february{},
eng_noun:mid - june{},
eng_noun:mid - august{},
eng_noun:mid - fall{},
eng_noun:jean{},
eng_noun:sectarian{},
eng_noun:diabolic{},
eng_noun:progressive{},
eng_noun:tellurian{},
eng_noun:afferent{},
eng_noun:neutral{},
eng_noun:prompt{},
eng_noun:churchy{},
eng_noun:mammary{},
eng_noun:interim{},
eng_noun:Lesvonian{},
eng_noun:orderly{},
eng_noun:hood{},
eng_noun:googlish{},
eng_noun:nontrinitarian{},
eng_noun:cordial{},
eng_noun:asbestos{},
eng_noun:audible{},
eng_noun:tickle{},
eng_noun:kindred{},
eng_noun:Oliver{},
eng_noun:plus{},
eng_noun:Filipino{},
eng_noun:spiffy{},
eng_noun:organic{},
eng_noun:concave{},
eng_noun:repellent{},
eng_noun:embonpoint{},
eng_noun:precision{},
eng_noun:appositive{},
eng_noun:Chaldean{},
eng_noun:cetacean{},
eng_noun:sturdy{},
eng_noun:oriental{},
eng_noun:Balinese{},
eng_noun:instructive{},
eng_noun:itinerant{},
eng_noun:solo{},
eng_noun:familiar{},
eng_noun:narcotic{},
eng_noun:Walloon{},
eng_noun:capacity{},
eng_noun:pommie{},
eng_noun:daffodil{},
eng_noun:redeye{},
eng_noun:oval{},
eng_noun:geranium{},
eng_noun:custom{},
eng_noun:inland{},
eng_noun:excess{},
eng_noun:tinsel{},
eng_noun:canonical{},
eng_noun:oblong{},
eng_noun:commuter{},
eng_noun:agnate{},
eng_noun:cosmetic{},
eng_noun:moribund{},
eng_noun:preantepenultimate{},
eng_noun:mutant{},
eng_noun:faithful{},
eng_noun:catholic{},
eng_noun:exempt{},
eng_noun:traunch{},
eng_noun:plebeian{},
eng_noun:casual{},
eng_noun:suspect{},
eng_noun:alveolar{},
eng_noun:nonconformist{},
eng_noun:opiate{},
eng_noun:assistant{},
eng_noun:favourite{},
eng_noun:aerosol{},
eng_noun:autograph{},
eng_noun:hopeful{},
eng_noun:aphrodisiac{},
eng_noun:isometric{},
eng_noun:heliotrope{},
eng_noun:cynic{},
eng_noun:aero{},
eng_noun:flit{},
eng_noun:anti{},
eng_noun:sensitive{},
eng_noun:minus{},
eng_noun:septuagenarian{},
eng_noun:termagant{},
eng_noun:Etruscan{},
eng_noun:mimic{},
eng_noun:castaway{},
eng_noun:polycyclic{},
eng_noun:bicyclic{},
eng_noun:periodical{},
eng_noun:initial{},
eng_noun:antipodean{},
eng_noun:roundabout{},
eng_noun:comedogenic{},
eng_noun:psychic{},
eng_noun:frizzy{},
eng_noun:Andean{},
eng_noun:mutton{},
eng_noun:shortwave{},
eng_noun:illiterate{},
eng_noun:eugeroic{},
eng_noun:asthmatic{},
eng_noun:hominid{},
eng_noun:observable{},
eng_noun:observant{},
eng_noun:obverse{},
eng_noun:romantic{},
eng_noun:ultraconservative{},
eng_noun:ancillary{},
eng_noun:uggo{},
eng_noun:Caroline{},
eng_noun:diluent{},
eng_noun:deadpan{},
eng_noun:supernumerary{},
eng_noun:outboard{},
eng_noun:commonplace{},
eng_noun:knockdown{},
eng_noun:Yugoslav{},
eng_noun:nutrient{},
eng_noun:nymphomaniac{},
eng_noun:swarth{},
eng_noun:supine{},
eng_noun:solvent{},
eng_noun:blow - by - blow{},
eng_noun:extracurricular{},
eng_noun:westerly{},
eng_noun:woodland{},
eng_noun:memorial{},
eng_noun:likely{},
eng_noun:blow - up{},
eng_noun:blah{},
eng_noun:audio{},
eng_noun:wobbly{},
eng_noun:degenerate{},
eng_noun:desirable{},
eng_noun:workday{},
eng_noun:tribal{},
eng_noun:Elysium{},
eng_noun:jaded{},
eng_noun:doggy{},
eng_noun:upstage{},
eng_noun:Exoduster{},
eng_noun:Vatican{},
eng_noun:veteran{},
eng_noun:veterinary{},
eng_noun:virgate{},
eng_noun:immeasurable{},
eng_noun:flamboyant{},
eng_noun:quadragenarian{},
eng_noun:quintuplicate{},
eng_noun:ambient{},
eng_noun:Californian{},
eng_noun:haggard{},
eng_noun:umbilical{},
eng_noun:maudlin{},
eng_noun:unattractive{},
eng_noun:barefoot{},
eng_noun:dead - end{},
eng_noun:utilitarian{},
eng_noun:syllabic{},
eng_noun:preterite{},
eng_noun:bovine{},
eng_noun:polyzoan{},
eng_noun:shojo{},
eng_noun:bryozoan{},
eng_noun:italic{},
eng_noun:upstate{},
eng_noun:cleanup{},
eng_noun:petit{},
eng_noun:provincial{},
eng_noun:Malaysian{},
eng_noun:Freudian{},
eng_noun:Promethean{},
eng_noun:palmate{},
eng_noun:hairshirt{},
eng_noun:picky{},
eng_noun:upskirt{},
eng_noun:tandem{},
eng_noun:acrylic{},
eng_noun:wholemeal{},
eng_noun:adulterine{},
eng_noun:carotenoid{},
eng_noun:incognito{},
eng_noun:shoddy{},
eng_noun:knee - jerk{},
eng_noun:clumsy{},
eng_noun:noteworthy{},
eng_noun:transcendental{},
eng_noun:Finnophone{},
eng_noun:Russophone{},
eng_noun:Sinophone{},
eng_noun:Chewa{},
eng_noun:Manichaean{},
eng_noun:doggerel{},
eng_noun:Siamese{},
eng_noun:plantigrade{},
eng_noun:denialist{},
eng_noun:conscript{},
eng_noun:transitory{},
eng_noun:translative{},
eng_noun:brutalitarian{},
eng_noun:Eoarchean{},
eng_noun:Tonian{},
eng_noun:Holocene{},
eng_noun:Paleocene{},
eng_noun:unfortunate{},
eng_noun:antineoplastic{},
eng_noun:authoritarian{},
eng_noun:Laplacian{},
eng_noun:borderline{},
eng_noun:Eurasian{},
eng_noun:performant{},
eng_noun:multimedia{},
eng_noun:decadent{},
eng_noun:quinquagenarian{},
eng_noun:sibilant{},
eng_noun:topaz{},
eng_noun:claret{},
eng_noun:one - off{},
eng_noun:cinnabar{},
eng_noun:gainsboro{},
eng_noun:gunmetal - grey{},
eng_noun:brittle{},
eng_noun:vulnerary{},
eng_noun:hoar{},
eng_noun:postmodern{},
eng_noun:modernist{},
eng_noun:postmodernist{},
eng_noun:ethical{},
eng_noun:mazarine{},
eng_noun:pseudointellectual{},
eng_noun:pearly{},
eng_noun:preliminary{},
eng_noun:designer{},
eng_noun:penitentiary{},
eng_noun:hyoid{},
eng_noun:Attic{},
eng_noun:Ecuadorean{},
eng_noun:Ottoman{},
eng_noun:Renaissance{},
eng_noun:Salvadorean{},
eng_noun:Scorpion{},
eng_noun:Sicilian{},
eng_noun:Udmurt{},
eng_noun:Zen{},
eng_noun:boutique{},
eng_noun:cuneiform{},
eng_noun:champagne{},
eng_noun:hackney{},
eng_noun:capitate{},
eng_noun:ethmoid{},
eng_noun:interlocutory{},
eng_noun:unreliable{},
eng_noun:hereditary{},
eng_noun:wacko{},
eng_noun:turbinate{},
eng_noun:turbinal{},
eng_noun:mocha{},
eng_noun:feminist{},
eng_noun:easter{},
eng_noun:troglophile{},
eng_noun:ecru{},
eng_noun:piedmont{},
eng_noun:magnolia{},
eng_noun:head - on{},
eng_noun:Euro - sceptic{},
eng_noun:potty{},
eng_noun:nephritic{},
eng_noun:paratyphoid{},
eng_noun:doomsday{},
eng_noun:ocker{},
eng_noun:handheld{},
eng_noun:Shiite{},
eng_noun:Geraldine{},
eng_noun:quintuple{},
eng_noun:upland{},
eng_noun:ovoid{},
eng_noun:heavyweight{},
eng_noun:urticant{},
eng_noun:differential{},
eng_noun:guerrilla{},
eng_noun:literal{},
eng_noun:abhesive{},
eng_noun:semiautomatic{},
eng_noun:dink{},
eng_noun:tsarist{},
eng_noun:quantifiable{},
eng_noun:antidepressant{},
eng_noun:antimonarchist{},
eng_noun:dreadful{},
eng_noun:maxi{},
eng_noun:emphatic{},
eng_noun:anti - inflammatory{},
eng_noun:antimalarial{},
eng_noun:proletarian{},
eng_noun:Phoenician{},
eng_noun:Anglo - indian{},
eng_noun:teleost{},
eng_noun:parathyroid{},
eng_noun:smock{},
eng_noun:mockney{},
eng_noun:paraplegic{},
eng_noun:exquisite{},
eng_noun:flimsy{},
eng_noun:goofball{},
eng_noun:no - go{},
eng_noun:not - for - profit{},
eng_noun:colloid{},
eng_noun:proficient{},
eng_noun:intrusive{},
eng_noun:corkscrew{},
eng_noun:mattoid{},
eng_noun:shortie{},
eng_noun:ceremonial{},
eng_noun:germane{},
eng_noun:deviant{},
eng_noun:lunatic{},
eng_noun:tricolor{},
eng_noun:Hegelian{},
eng_noun:Calgarian{},
eng_noun:twilight{},
eng_noun:anticlerical{},
eng_noun:psychotic{},
eng_noun:jake{},
eng_noun:eligible{},
eng_noun:milquetoast{},
eng_noun:phocine{},
eng_noun:upbeat{},
eng_noun:aspic{},
eng_noun:Glagolitic{},
eng_noun:gewgaw{},
eng_noun:desktop{},
eng_noun:insomniac{},
eng_noun:incidental{},
eng_noun:dreary{},
eng_noun:aliped{},
eng_noun:prostrate{},
eng_noun:simoniac{},
eng_noun:alabaster{},
eng_noun:welter - weight{},
eng_noun:laggard{},
eng_noun:sophomore{},
eng_noun:bittersweet{},
eng_noun:westward{},
eng_noun:compassionate{},
eng_noun:bully{},
eng_noun:antirust{},
eng_noun:mammalian{},
eng_noun:paedo{},
eng_noun:antiterrorist{},
eng_noun:fantom{},
eng_noun:walk - off{},
eng_noun:scud{},
eng_noun:orthorexic{},
eng_noun:vermifuge{},
eng_noun:antispasmodic{},
eng_noun:benedictive{},
eng_noun:glossy{},
eng_noun:quinquennial{},
eng_noun:valetudinarian{},
eng_noun:nationalist{},
eng_noun:beserk{},
eng_noun:Thomist{},
eng_noun:ruderal{},
eng_noun:zygenid{},
eng_noun:gridelin{},
eng_noun:emergent{},
eng_noun:mezzanine{},
eng_noun:Nordic{},
eng_noun:traditionary{},
eng_noun:peripheral{},
eng_noun:egalitarian{},
eng_noun:thespian{},
eng_noun:Playboy{},
eng_noun:Lett{},
eng_noun:streetwise{},
eng_noun:tropic{},
eng_noun:bicuspid{},
eng_noun:pinpoint{},
eng_noun:chalybeate{},
eng_noun:delinquent{},
eng_noun:doctrinaire{},
eng_noun:peregrine{},
eng_noun:causal{},
eng_noun:hellion{},
eng_noun:octoploid{},
eng_noun:colly{},
eng_noun:backstage{},
eng_noun:centuple{},
eng_noun:metazoan{},
eng_noun:postgraduate{},
eng_noun:Visayan{},
eng_noun:all - in{},
eng_noun:second - rate{},
eng_noun:tandoori{},
eng_noun:perfective{},
eng_noun:preliterate{},
eng_noun:midair{},
eng_noun:confessional{},
eng_noun:Ionian{},
eng_noun:crypto{},
eng_noun:coelomate{},
eng_noun:comitative{},
eng_noun:Phrygian{},
eng_noun:aorist{},
eng_noun:Paralympian{},
eng_noun:unimpressive{},
eng_noun:futilitarian{},
eng_noun:operative{},
eng_noun:unfamiliar{},
eng_noun:conventual{},
eng_noun:modal{},
eng_noun:favorite{},
eng_noun:dusky{},
eng_noun:Mayan{},
eng_noun:third - rate{},
eng_noun:veggo{},
eng_noun:hereditarian{},
eng_noun:susceptible{},
eng_noun:nouveau{},
eng_noun:correspondent{},
eng_noun:bissextile{},
eng_noun:northward{},
eng_noun:expendable{},
eng_noun:experient{},
eng_noun:apocalyptic{},
eng_noun:clement{},
eng_noun:easterly{},
eng_noun:magistral{},
eng_noun:Choctaw{},
eng_noun:cometary{},
eng_noun:impracticable{},
eng_noun:alcaic{},
eng_noun:influent{},
eng_noun:unificationist{},
eng_noun:batrachian{},
eng_noun:cimmerian{},
eng_noun:digestive{},
eng_noun:unsuccessful{},
eng_noun:truant{},
eng_noun:Dacian{},
eng_noun:emollient{},
eng_noun:etesian{},
eng_noun:perishable{},
eng_noun:Newtonian{},
eng_noun:thermoplastic{},
eng_noun:thoroughbred{},
eng_noun:thunderstruck{},
eng_noun:Prussian{},
eng_noun:austral{},
eng_noun:eutherian{},
eng_noun:addolorato{},
eng_noun:touch - and - go{},
eng_noun:Unitarian{},
eng_noun:multinational{},
eng_noun:debit{},
eng_noun:montane{},
eng_noun:unproductive{},
eng_noun:irreconcilable{},
eng_noun:fractional{},
eng_noun:honorific{},
eng_noun:consequent{},
eng_noun:ultralight{},
eng_noun:scholastic{},
eng_noun:preppy{},
eng_noun:Hittite{},
eng_noun:dyspeptic{},
eng_noun:paperback{},
eng_noun:appellant{},
eng_noun:recombinant{},
eng_noun:sanitarian{},
eng_noun:Ossetic{},
eng_noun:surrealist{},
eng_noun:superplastic{},
eng_noun:copycat{},
eng_noun:fractal{},
eng_noun:naif{},
eng_noun:rheumatic{},
eng_noun:op - ed{},
eng_noun:litoral{},
eng_noun:laic{},
eng_noun:grownup{},
eng_noun:Quartodeciman{},
eng_noun:excelsior{},
eng_noun:prosthetic{},
eng_noun:schematic{},
eng_noun:prebendary{},
eng_noun:nonstop{},
eng_noun:caretaker{},
eng_noun:hatstand{},
eng_noun:seaside{},
eng_noun:matronymic{},
eng_noun:probiotic{},
eng_noun:Plutonian{},
eng_noun:monoclonal{},
eng_noun:Bostonian{},
eng_noun:fixative{},
eng_noun:arytenoid{},
eng_noun:hissy{},
eng_noun:cutthroat{},
eng_noun:predominant{},
eng_noun:teiid{},
eng_noun:quadrillionth{},
eng_noun:carotid{},
eng_noun:Lagrangian{},
eng_noun:dielectric{},
eng_noun:combustible{},
eng_noun:downstream{},
eng_noun:push - up{},
eng_noun:Berber{},
eng_noun:crapola{},
eng_noun:Geordie{},
eng_noun:Brummie{},
eng_noun:dotty{},
eng_noun:bendy{},
eng_noun:Aotearoan{},
eng_noun:Lusatian{},
eng_noun:dastard{},
eng_noun:assurgent{},
eng_noun:froggy{},
eng_noun:autistic{},
eng_noun:anorexic{},
eng_noun:cohortative{},
eng_noun:deist{},
eng_noun:polychrome{},
eng_noun:centauroid{},
eng_noun:metonymic{},
eng_noun:lenitive{},
eng_noun:vocable{},
eng_noun:bacchant{},
eng_noun:maladroit{},
eng_noun:Rastafarian{},
eng_noun:whist{},
eng_noun:homoiousian{},
eng_noun:polygastric{},
eng_noun:Discordian{},
eng_noun:chirpy{},
eng_noun:breakable{},
eng_noun:movable{},
eng_noun:immovable{},
eng_noun:unchangeable{},
eng_noun:guttural{},
eng_noun:southward{},
eng_noun:nonstandard{},
eng_noun:Theban{},
eng_noun:logistic{},
eng_noun:supertall{},
eng_noun:Maoist{},
eng_noun:prepollent{},
eng_noun:presbyterian{},
eng_noun:lowbrow{},
eng_noun:unquestionable{},
eng_noun:birdy{},
eng_noun:Canarian{},
eng_noun:heteroaromatic{},
eng_noun:abducent{},
eng_noun:jemmy{},
eng_noun:pandeist{},
eng_noun:fayre{},
eng_noun:scratch{},
eng_noun:dysthymic{},
eng_noun:chelicerate{},
eng_noun:organosilicon{},
eng_noun:tetraplicate{},
eng_noun:gamine{},
eng_noun:desiccant{},
eng_noun:irresponsible{},
eng_noun:singsong{},
eng_noun:southerly{},
eng_noun:Palauan{},
eng_noun:behavioralist{},
eng_noun:wormy{},
eng_noun:Carthusian{},
eng_noun:matrimonial{},
eng_noun:isolationist{},
eng_noun:blameless{},
eng_noun:imperforate{},
eng_noun:sing - song{},
eng_noun:Ngoni{},
eng_noun:Oscan{},
eng_noun:Melungeon{},
eng_noun:leathern{},
eng_noun:radge{},
eng_noun:aerospace{},
eng_noun:infralittoral{},
eng_noun:broon{},
eng_noun:tricenarian{},
eng_noun:constabulary{},
eng_noun:piezoelectric{},
eng_noun:fortean{},
eng_noun:mariachi{},
eng_noun:clarion{},
eng_noun:narcoleptic{},
eng_noun:stigmatic{},
eng_noun:recitative{},
eng_noun:braxy{},
eng_noun:deaf - mute{},
eng_noun:knee - high{},
eng_noun:shan{},
eng_noun:kiddy{},
eng_noun:adjoint{},
eng_noun:bombe{},
eng_noun:pre - op{},
eng_noun:punky{},
eng_noun:rough - and - tumble{},
eng_noun:stop - gap{},
eng_noun:egocentric{},
eng_noun:ergative{},
eng_noun:revivalist{},
eng_noun:mimetic{},
eng_noun:ducky{},
eng_noun:ebon{},
eng_noun:understage{},
eng_noun:somnifacient{},
eng_noun:inaugural{},
eng_noun:pulmonate{},
eng_noun:Moldovan{},
eng_noun:publique{},
eng_noun:run - on{},
eng_noun:denarian{},
eng_noun:sforzando{},
eng_noun:plebian{},
eng_noun:Windian{},
eng_noun:vendible{},
eng_noun:evangelical{},
eng_noun:poddy{},
eng_noun:uttermost{},
eng_noun:sparky{},
eng_noun:superordinate{},
eng_noun:pectinate{},
eng_noun:privative{},
eng_noun:Vegliot{},
eng_noun:accompagnato{},
eng_noun:Nilotic{},
eng_noun:superhuman{},
eng_noun:cast - iron{},
eng_noun:pose{},
eng_noun:quede{},
eng_noun:waxen{},
eng_noun:Iroquoian{},
eng_noun:curtal{},
eng_noun:stylistic{},
eng_noun:one - on - one{},
eng_noun:magique{},
eng_noun:deerskin{},
eng_noun:doeskin{},
eng_noun:frou - frou{},
eng_noun:duty - free{},
eng_noun:Nahua{},
eng_noun:polytechnic{},
eng_noun:proteid{},
eng_noun:dependable{},
eng_noun:ascendent{},
eng_noun:unpronounceable{},
eng_noun:geriatric{},
eng_noun:anticommunist{},
eng_noun:Austronesian{},
eng_noun:mesel{},
eng_noun:renewable{},
eng_noun:twisty{},
eng_noun:Quebecois{},
eng_noun:insensate{},
eng_noun:Comanche{},
eng_noun:crackerjack{},
eng_noun:Bielorussian{},
eng_noun:Moldovian{},
eng_noun:antipollution{},
eng_noun:appurtenant{},
eng_noun:dicky{},
eng_noun:ellipsoid{},
eng_noun:disposable{},
eng_noun:resale{},
eng_noun:devotional{},
eng_noun:unfruitful{},
eng_noun:microlaser{},
eng_noun:sacroiliac{},
eng_noun:Hibernian{},
eng_noun:eristic{},
eng_noun:expansionist{},
eng_noun:extempore{},
eng_noun:earthbound{},
eng_noun:eatable{},
eng_noun:fungoid{},
eng_noun:futurist{},
eng_noun:grown - up{},
eng_noun:bombproof{},
eng_noun:lapsarian{},
eng_noun:thigh - high{},
eng_noun:schizoid{},
eng_noun:nucleate{},
eng_noun:subsurface{},
eng_noun:smoggy{},
eng_noun:unwearable{},
eng_noun:suppliant{},
eng_noun:meridional{},
eng_noun:subwavelength{},
eng_noun:carnivoran{},
eng_noun:predicable{},
eng_noun:disyllabic{},
eng_noun:amygdalate{},
eng_noun:militarian{},
eng_noun:predicative{},
eng_noun:storybook{},
eng_noun:plainclothes{},
eng_noun:millenarian{},
eng_noun:deictic{},
eng_noun:dialup{},
eng_noun:spheroidal{},
eng_noun:Oxonian{},
eng_noun:terminative{},
eng_noun:ginny{},
eng_noun:indeterminant{},
eng_noun:nonprofit{},
eng_noun:historicist{},
eng_noun:streight{},
eng_noun:sextile{},
eng_noun:anticlinal{},
eng_noun:thermoelectric{},
eng_noun:jihadist{},
eng_noun:runtime{},
eng_noun:clericalist{},
eng_noun:coalescent{},
eng_noun:coalitionist{},
eng_noun:Javan{},
eng_noun:Okinawan{},
eng_noun:high - hat{},
eng_noun:determinative{},
eng_noun:redistributable{},
eng_noun:nacroleptic{},
eng_noun:stubby{},
eng_noun:frontpage{},
eng_noun:shorthorn{},
eng_noun:colonialist{},
eng_noun:come - hither{},
eng_noun:amenorrhoeic{},
eng_noun:nonzero{},
eng_noun:quadruplex{},
eng_noun:ringside{},
eng_noun:jannock{},
eng_noun:Tungusic{},
eng_noun:paraphilic{},
eng_noun:consumable{},
eng_noun:monoglot{},
eng_noun:corroborative{},
eng_noun:Orcadian{},
eng_noun:Shetlander{},
eng_noun:counteractive{},
eng_noun:Commie{},
eng_noun:placental{},
eng_noun:half - and - half{},
eng_noun:bluey{},
eng_noun:druggy{},
eng_noun:vigoroso{},
eng_noun:polyaromatic{},
eng_noun:paroxytone{},
eng_noun:polymorphonucleate{},
eng_noun:imparisyllabic{},
eng_noun:unmoral{},
eng_noun:brindle{},
eng_noun:suprasegmental{},
eng_noun:polypiarian{},
eng_noun:hydroid{},
eng_noun:preterm{},
eng_noun:tectiform{},
eng_noun:Lazarist{},
eng_noun:cytostatic{},
eng_noun:amygdaloid{},
eng_noun:flippy{},
eng_noun:Leonese{},
eng_noun:Valencian{},
eng_noun:acromegalic{},
eng_noun:Adelaidian{},
eng_noun:demoniac{},
eng_noun:tinhorn{},
eng_noun:chump - change{},
eng_noun:formalist{},
eng_noun:buffalo - skin{},
eng_noun:polyplacophoran{},
eng_noun:polygonial{},
eng_noun:actinopterygian{},
eng_noun:Edmontonian{},
eng_noun:broadleaf{},
eng_noun:aulic{},
eng_noun:equivoque{},
eng_noun:zetetic{},
eng_noun:Alabaman{},
eng_noun:coelurosaurian{},
eng_noun:hardcover{},
eng_noun:hortative{},
eng_noun:diaphoretic{},
eng_noun:intervarsity{},
eng_noun:primigravid{},
eng_noun:multistory{},
eng_noun:deflationary{},
eng_noun:determinable{},
eng_noun:drive - through{},
eng_noun:drop - in{},
eng_noun:luminal{},
eng_noun:make - up{},
eng_noun:pinchbeck{},
eng_noun:hardball{},
eng_noun:make - do{},
eng_noun:nonperishable{},
eng_noun:genethliac{},
eng_noun:tristate{},
eng_noun:alate{},
eng_noun:cut - off{},
eng_noun:Earthian{},
eng_noun:proinflammatory{},
eng_noun:reentrant{},
eng_noun:propellent{},
eng_noun:trimonthly{},
eng_noun:zig - zag{},
eng_noun:half - track{},
eng_noun:paraprofessional{},
eng_noun:praetorian{},
eng_noun:jackleg{},
eng_noun:sternutatory{},
eng_noun:ubersexual{},
eng_noun:precipitant{},
eng_noun:prekindergarten{},
eng_noun:monetarist{},
eng_noun:noneffective{},
eng_noun:measureless{},
eng_noun:immunosuppressive{},
eng_noun:multiform{},
eng_noun:multifamily{},
eng_noun:molluscan{},
eng_noun:emunctory{},
eng_noun:smoother{},
eng_noun:Antarctican{},
eng_noun:populist{},
eng_noun:neocolonialist{},
eng_noun:neutralist{},
eng_noun:butthurt{},
eng_noun:hit - and - run{},
eng_noun:trinomial{},
eng_noun:ofay{},
eng_noun:phasianid{},
eng_noun:intrant{},
eng_noun:alpinist{},
eng_noun:reconcilable{},
eng_noun:ceratopsid{},
eng_noun:underweight{},
eng_noun:melic{},
eng_noun:dyspraxic{},
eng_noun:protoctist{},
eng_noun:pseudocoelomate{},
eng_noun:pteropodine{},
eng_noun:Puebloan{},
eng_noun:adversative{},
eng_noun:returnable{},
eng_noun:dithyrambic{},
eng_noun:oppidan{},
eng_noun:equalitarian{},
eng_noun:downstyle{},
eng_noun:Biafran{},
eng_noun:organohalogen{},
eng_noun:organoiodine{},
eng_noun:crenate{},
eng_noun:Christofascist{},
eng_noun:footlong{},
eng_noun:tutelar{},
eng_noun:synchromesh{},
eng_noun:pentimal{},
eng_noun:replicant{},
eng_noun:non - human{},
eng_noun:squaloid{},
eng_noun:neopagan{},
eng_noun:Dakotan{},
eng_noun:nonexempt{},
eng_noun:Paphian{},
eng_noun:jerk - water{},
eng_noun:meristic{},
eng_noun:Galatian{},
eng_noun:paralysant{},
eng_noun:malglico{},
eng_noun:chelonian{},
eng_noun:nonnarcotic{},
eng_noun:nonobjective{},
eng_noun:benzenoid{},
eng_noun:nonreturnable{},
eng_noun:nonprofessional{},
eng_noun:nonofficial{},
eng_noun:nonresident{},
eng_noun:nonsympathizer{},
eng_noun:polynoid{},
eng_noun:Bozal{},
eng_noun:Darwinian{},
eng_noun:nematic{},
eng_noun:sociopathic{},
eng_noun:smectic{},
eng_noun:backstreet{},
eng_noun:processionary{},
eng_noun:Afghanistani{},
eng_noun:poikilotherm{},
eng_noun:gamomaniac{},
eng_noun:Franquist{},
eng_noun:Rhodesian{},
eng_noun:dement{},
eng_noun:unprovable{},
eng_noun:nitrenoid{},
eng_noun:Moravian{},
eng_noun:Gibraltarian{},
eng_noun:equipotential{},
eng_noun:salvationist{},
eng_noun:expiratory{},
eng_noun:Alabamian{},
eng_noun:ammonoid{},
eng_noun:aliquant{},
eng_noun:aphidian{},
eng_noun:eleutheromaniac{},
eng_noun:antifascist{},
eng_noun:amandine{},
eng_noun:versant{},
eng_noun:Kosovan{},
eng_noun:responsorial{},
eng_noun:for - profit{},
eng_noun:Patagonian{},
eng_noun:goony{},
eng_noun:buckshee{},
eng_noun:escharotic{},
eng_noun:technic{},
eng_noun:arsenical{},
eng_noun:corrigent{},
eng_noun:monoaromatic{},
eng_noun:organonitrogen{},
eng_noun:multiphase{},
eng_noun:ethoxy{},
eng_noun:aminoethoxy{},
eng_noun:asphyxiant{},
eng_noun:supramembrane{},
eng_noun:Titanian{},
eng_noun:Callistoan{},
eng_noun:corporatist{},
eng_noun:deere{},
eng_noun:sarmentose{},
eng_noun:Marist{},
eng_noun:nitroaryl{},
eng_noun:hexactine{},
eng_noun:embryoid{},
eng_noun:Japhetite{},
eng_noun:euploid{},
eng_noun:Lydian{},
eng_noun:inebriant{},
eng_noun:cholic{},
eng_noun:eutectoid{},
eng_noun:multivariate{},
eng_noun:natriuretic{},
eng_noun:nonmutant{},
eng_noun:multifunction{},
eng_noun:snotnose{},
eng_noun:exercitive{},
eng_noun:radiochemical{},
eng_noun:Jungian{},
eng_noun:Euroskeptic{},
eng_noun:querulent{},
eng_noun:Eutychian{},
eng_noun:Kurdistani{},
eng_noun:holo{},
eng_noun:Sienese{},
eng_noun:behabitive{},
eng_noun:commissive{},
eng_noun:Angevin{},
eng_noun:caudatan{},
eng_noun:dinocephalian{},
eng_noun:Rousseauian{},
eng_noun:Camunian{},
eng_noun:cooty{},
eng_noun:orthotic{},
eng_noun:antiscience{},
eng_noun:want - away{},
eng_noun:slimmer{},
eng_noun:semiliquid{},
eng_noun:renunciate{},
eng_noun:arval{},
eng_noun:tenuis{},
eng_noun:cameloid{},
eng_noun:multicast{},
eng_noun:Chaucerian{},
eng_noun:gradable{},
eng_noun:Kalmyk{},
eng_noun:brachycephalic{},
eng_noun:Mordovian{},
eng_noun:Tuvan{},
eng_noun:Buryatian{},
eng_noun:Kareli{},
eng_noun:Russki{},
eng_noun:polyschematist{},
eng_noun:polynemoid{},
eng_noun:lactoovovegetarian{},
eng_noun:tribrid{},
eng_noun:papish{},
eng_noun:megapod{},
eng_noun:audient{},
eng_noun:hemipteran{},
eng_noun:Judaean{},
eng_noun:Natufian{},
eng_noun:Philippian{},
eng_noun:mercantilist{},
eng_noun:sesquiquadrate{},
eng_noun:buffy{},
eng_noun:obscurant{},
eng_noun:immunotherapeutic{},
eng_noun:bracteate{},
eng_noun:Louisianan{},
eng_noun:jasperoid{},
eng_noun:paedophiliac{},
eng_noun:Xanthian{},
eng_noun:mirk{},
eng_noun:superpremium{},
eng_noun:Carolinian{},
eng_noun:Wyomingite{},
eng_noun:Delawarean{},
eng_noun:slapstickery{},
eng_noun:ultrarevolutionary{},
eng_noun:Technicolor{},
eng_noun:Cancerian{},
eng_noun:Geminian{},
eng_noun:Sammarinese{},
eng_noun:reconstructivist{},
eng_noun:postcanine{},
eng_noun:superexplosive{},
eng_noun:hymenopteran{},
eng_noun:lepidopteran{},
eng_noun:lucinid{},
eng_noun:Ithacan{},
eng_noun:pogonophoran{},
eng_noun:sepiolid{},
eng_noun:nutriceutical{},
eng_noun:butoh{},
eng_noun:cutover{},
eng_noun:chitty{},
eng_noun:semifluid{},
eng_noun:perciform{},
eng_noun:supermajor{},
eng_noun:Manichean{},
eng_noun:marly{},
eng_noun:mammaliaform{},
eng_noun:somnolytic{},
eng_noun:caridoid{},
eng_noun:mountant{},
eng_noun:one - piece{},
eng_noun:jugal{},
eng_noun:unlockable{},
eng_noun:articulatory{},
eng_noun:indexical{},
eng_noun:mesocephalic{},
eng_noun:collagist{},
eng_noun:Comoran{},
eng_noun:Monacan{},
eng_noun:Kittsian{},
eng_noun:homarine{},
eng_noun:compostable{},
eng_noun:techno - utopian{},
eng_noun:ultrashort{},
eng_noun:cerumenolytic{},
eng_noun:computerphobic{},
eng_noun:allopolyploid{},
eng_noun:amphidiploid{},
eng_noun:informatic{},
eng_noun:ameriginal{},
eng_noun:whacko{},
eng_noun:neurochemical{},
eng_noun:antiphonary{},
eng_noun:antiepileptic{},
eng_noun:unaccusative{},
eng_noun:postcareer{},
eng_noun:premarket{},
eng_noun:postgame{},
eng_noun:localist{},
eng_noun:antimodern{},
eng_noun:nonexecutive{},
eng_noun:midseason{},
eng_noun:neoliberal{},
eng_noun:Yeniseian{},
eng_noun:delipidate{},
eng_noun:bistable{},
eng_noun:psychostimulant{},
eng_noun:Thessalonican{},
eng_noun:four - poster{},
eng_noun:midsong{},
eng_noun:Caesarist{},
eng_noun:Sabbatian{},
eng_noun:equative{},
eng_noun:Dolomite{},
eng_noun:Atacaman{},
eng_noun:bilevel{},
eng_noun:ultrafundamentalist{},
eng_noun:Goan{},
eng_noun:Maharashtrian{},
eng_noun:Mangalorean{},
eng_noun:Malayali{},
eng_noun:Mumbaikar{},
eng_noun:Mapuche{},
eng_noun:nonschool{},
eng_noun:floaty{},
eng_noun:low - pass{},
eng_noun:psittacine{},
eng_noun:prosimian{},
eng_noun:oceanview{},
eng_noun:nonblack{},
eng_noun:nongay{},
eng_noun:antimilitarist{},
eng_noun:supermax{},
eng_noun:extremal{},
eng_noun:skookum{},
eng_noun:Picard{},
eng_noun:nonbilaterian{},
eng_noun:segregant{},
eng_noun:greyscale{},
eng_noun:diffusionist{},
eng_noun:ethnobotanical{},
eng_noun:universalist{},
eng_noun:glossopharyngeal{},
eng_noun:serialist{},
eng_noun:nonmusical{},
eng_noun:prehuman{},
eng_noun:anticapitalist{},
eng_noun:antiauthoritarian{},
eng_noun:authenticist{},
eng_noun:antiracist{},
eng_noun:contextualist{},
eng_noun:deconstructionist{},
eng_noun:softcover{},
eng_noun:nondance{},
eng_noun:semivegetarian{},
eng_noun:subregional{},
eng_noun:nonliterate{},
eng_noun:nonfamily{},
eng_noun:decisionist{},
eng_noun:evidentialist{},
eng_noun:conventionalist{},
eng_noun:compatibilist{},
eng_noun:symbolist{},
eng_noun:nonparty{},
eng_noun:regionalist{},
eng_noun:multi - storey{},
eng_noun:antinuke{},
eng_noun:readymade{},
eng_noun:structureless{},
eng_noun:suspensory{},
eng_noun:automatist{},
eng_noun:anticoagulation{},
eng_noun:midroll{},
eng_noun:poststructuralist{},
eng_noun:situationist{},
eng_noun:Mallorcan{},
eng_noun:Mallorquin{},
eng_noun:mumsy{},
eng_noun:nondyslexic{},
eng_noun:dead - set{},
eng_noun:crowdy{},
eng_noun:antirad{},
eng_noun:nonrecyclable{},
eng_noun:superspeed{},
eng_noun:backcast{},
eng_noun:nonclass{},
eng_noun:Hitlerite{},
eng_noun:manuary{},
eng_noun:multiplane{},
eng_noun:cheapass{},
eng_noun:cyberutopian{},
eng_noun:meseraic{},
eng_noun:vasorelaxant{},
eng_noun:nonhybrid{},
eng_noun:antisecretory{},
eng_noun:Lusitanian{},
eng_noun:Marlovian{},
eng_noun:Martiniquais{},
eng_noun:librul{},
eng_noun:Sirian{},
eng_noun:bunodont{},
eng_noun:peaker{},
eng_noun:dissolvent{},
eng_noun:noncola{},
eng_noun:nonsuicide{},
eng_noun:Araucanian{},
eng_noun:preggo{},
eng_noun:bioidentical{},
eng_noun:Bloquiste{},
eng_noun:matrist{},
eng_noun:midsession{},
eng_noun:non - relative{},
eng_noun:normotensive{},
eng_noun:nonvitamin{},
eng_noun:ballotechnic{},
eng_noun:antinationalist{},
eng_noun:antidepressive{},
eng_noun:supersessionist{},
eng_noun:posthuman{},
eng_noun:Meccan{},
eng_noun:Bucharestian{},
eng_noun:Belgradian{},
eng_noun:Nicosian{},
eng_noun:Sofian{},
eng_noun:Zagrebian{},
eng_noun:Osloite{},
eng_noun:Jakartan{},
eng_noun:Rangoonese{},
eng_noun:Kabulese{},
eng_noun:Baghdadi{},
eng_noun:pushbutton{},
eng_noun:Bushist{},
eng_noun:purgatoric{},
eng_noun:Megarian{},
eng_noun:Ivoirian{},
eng_noun:Sabaean{},
eng_noun:tufty{},
eng_noun:roughspun{},
eng_noun:antiphlogistic{},
eng_noun:deskside{},
eng_noun:Anglian{},
eng_noun:jimcrack{},
eng_noun:pre - socratic{},
eng_noun:Kalmuck{},
eng_noun:eobiotic{},
eng_noun:roll - on{},
eng_noun:largemouth{},
eng_noun:chemophobic{},
eng_noun:anorexigenic{},
eng_noun:Muscovian{},
eng_noun:entent{},
eng_noun:hypothenar{},
eng_noun:finikin{},
eng_noun:pensionary{},
eng_noun:antihistaminic{},
eng_noun:flatscreen{},
eng_noun:sourdine{},
eng_noun:nonaffected{},
eng_noun:Colophonian{},
eng_noun:noncrime{},
eng_noun:nonpsychotic{},
eng_noun:nonschizophrenic{},
eng_noun:nonuniversity{},
eng_noun:nonpagan{},
eng_noun:nonstative{},
eng_noun:noncancer{},
eng_noun:antiflatulent{},
eng_noun:nonindividual{},
eng_noun:nonhomosexual{},
eng_noun:antielitist{},
eng_noun:antiformalist{},
eng_noun:anticharm{},
eng_noun:nonfemale{},
eng_noun:Hebridean{},
eng_noun:antiholiday{},
eng_noun:Salian{},
eng_noun:scorpionate{},
eng_noun:nonalcohol{},
eng_noun:nonequal{},
eng_noun:epic{},
eng_noun:antiinfective{},
eng_noun:antipsoriatic{},
eng_noun:Masovian{},
eng_noun:radioprotective{},
eng_noun:Memphite{},
eng_noun:nondissident{},
eng_noun:multicuspid{},
eng_noun:nonvirus{},
eng_noun:nonfungible{},
eng_noun:nonprotectionist{},
eng_noun:noninnocent{},
eng_noun:nonadult{},
eng_noun:integrant{},
eng_noun:Osakan{},
eng_noun:nontranssexual{},
eng_noun:nonadolescent{},
eng_noun:muscid{},
eng_noun:champian{},
eng_noun:nonlesbian{},
eng_noun:nonmystic{},
eng_noun:occipitofrontal{},
eng_noun:nonsquare{},
eng_noun:superheavy{},
eng_noun:nonafrican{},
eng_noun:intercycle{},
eng_noun:nanofluid{},
eng_noun:sapphirine{},
eng_noun:nonequestrian{},
eng_noun:alkynyl{},
eng_noun:nonrelationship{},
eng_noun:carryable{},
eng_noun:Spinozist{},
eng_noun:paleoconservative{},
eng_noun:nonemployment{},
eng_noun:tetracuspid{},
eng_noun:schemey{},
eng_noun:Lemurian{},
eng_noun:millikelvin{},
eng_noun:incog{},
eng_noun:antifield{},
eng_noun:anticatarrhal{},
eng_noun:nonagreement{},
eng_noun:nonpolicy{},
eng_noun:superluxury{},
eng_noun:resolvent{},
eng_noun:multinomial{},
eng_noun:antithrombotic{},
eng_noun:multicomplex{},
eng_noun:antileukemic{},
eng_noun:antileukaemic{},
eng_noun:Transjordanian{},
eng_noun:nonpathology{},
eng_noun:nonradical{},
eng_noun:Mimantean{},
eng_noun:Ecumenopolitan{},
eng_noun:alkadienyl{},
eng_noun:nonsystem{},
eng_noun:bignose{},
eng_noun:submonolayer{},
eng_noun:carcinostatic{},
eng_noun:nonrepublic{},
eng_noun:nonjuvenile{},
eng_noun:implex{},
eng_noun:prec.{},
eng_noun:nondesigner{},
eng_noun:noninvestment{},
eng_noun:Franco - manitoban{},
eng_noun:antirheumatic{},
eng_noun:overside{},
eng_noun:superwide{},
eng_noun:second - to - last{},
eng_noun:digastric{},
eng_noun:calefactory{},
eng_noun:cancroid{},
eng_noun:capitulary{},
eng_noun:vasopressor{},
eng_noun:cavicorn{},
eng_noun:extravasate{},
eng_noun:antiunitary{},
eng_noun:Proto - iranian{},
eng_noun:cebine{},
eng_noun:ranid{},
eng_noun:Lacedemonian{},
eng_noun:shitfuck{},
eng_noun:Numidian{},
eng_noun:mooey{},
eng_noun:Servian{},
eng_noun:southron{},
eng_noun:Hanoverian{},
eng_noun:Sassanian{},
eng_noun:Sasanid{},
eng_noun:Manichaeist{},
eng_noun:presphenoid{},
eng_noun:Erewhonian{},
eng_noun:Yerevanian{},
eng_noun:stiddy{},
eng_noun:noncharismatic{},
eng_noun:nonethnic{},
eng_noun:rammy{},
eng_noun:quot.{},
eng_noun:nonfugitive{},
eng_noun:Transvaalian{},
eng_noun:Saxonian{},
eng_noun:Livornian{},
eng_noun:Marquesan{},
eng_noun:fucoid{},
eng_noun:congratulant{},
eng_noun:antidiarrhoeic{},
eng_noun:heterometal{},
eng_noun:fluoroaromatic{},
eng_noun:nonevergreen{},
eng_noun:hematinic{},
eng_noun:sextan{},
eng_noun:spagiric{},
eng_noun:Ghanan{},
eng_noun:vomitive{},
eng_noun:vitalist{},
eng_noun:vesicatory{},
eng_noun:ex - pat{},
eng_noun:Mazandarani{},
eng_noun:necessitarian{},
eng_noun:residentiary{},
eng_noun:nonblonde{},
eng_noun:invitatory{},
eng_noun:inequivalve{},
eng_noun:equivalve{},
eng_noun:Tarentine{},
eng_noun:Gallophone{},
eng_noun:sideway{},
eng_noun:Kittitian{},
eng_noun:Rhenish{},
eng_noun:antidivision{},
eng_noun:exclusionist{},
eng_noun:dozenal{},
eng_noun:tony{},
eng_noun:cyprinoid{},
eng_noun:loxodont{},
eng_noun:dilambdodont{},
eng_noun:labyrinthodont{},
eng_noun:antirepublican{},
eng_noun:antisyphilitic{},
eng_noun:antiromantic{},
eng_noun:antiarthritic{},
eng_noun:agrypnotic{},
eng_noun:multiplay{},
eng_noun:nonunity{},
eng_noun:sparoid{},
eng_noun:preadult{},
eng_noun:nonperennial{},
eng_noun:Khurrite{},
eng_noun:emulgent{},
eng_noun:attrahent{},
eng_noun:awesome - sauce{},
eng_noun:awesomesauce{},
eng_noun:nonassociation{},
eng_noun:Toisanese{},
eng_noun:Taishanese{},
eng_noun:neotraditionalist{},
eng_noun:serbophile{},
eng_noun:Barcelonian{},
eng_noun:Sevillian{},
eng_noun:Bilbaoan{},
eng_noun:goodwilly{},
eng_noun:transpondian{},
eng_noun:schizophasic{},
eng_noun:Exmoorian{},
eng_noun:Gergovian{},
eng_noun:headful{},
eng_noun:nonfeature{},
eng_noun:antisnob{},
eng_noun:Pentecostalist{},
eng_noun:anchal{},
eng_noun:pomosexual{},
eng_noun:Nueir{},
eng_noun:fissiped{},
eng_noun:mass - energy{},
eng_noun:appeasatory{},
eng_noun:bummy{},
eng_noun:multicable{},
eng_noun:Directoire{},
eng_noun:alabastre{},
eng_noun:nonextremist{},
eng_noun:Philipino{},
eng_noun:Humean{},
eng_noun:Humeian{},
eng_noun:Humian{},
eng_noun:Novgorodian{},
eng_noun:thrice - monthly{},
eng_noun:Trifluvien{},
eng_noun:Trifluvienne{},
eng_noun:Belgravian{},
eng_noun:Gandharan{},
eng_noun:swike{},
eng_noun:tinclad{},
eng_noun:robosexual{},
eng_noun:schizosexual{},
eng_noun:skimble - skamble{},
eng_noun:noncancellation{},
eng_noun:Bessarabian{},
eng_noun:portside{},
eng_noun:Ostian{},
eng_noun:looksist{},
eng_noun:Neo - pythagorean{},
eng_noun:midstorm{},
eng_noun:prasine{},
eng_noun:Tarragonan{},
eng_noun:masculist{},
eng_noun:Malaitan{},
eng_noun:subsalt{},
eng_noun:injectible{},
eng_noun:splitist{},
eng_noun:Dahomeyan{},
eng_noun:sternutative{},
eng_noun:Zamoran{},
eng_noun:iguanian{},
eng_noun:parasomniac{},
eng_noun:zygodactyle{},
eng_noun:ziphioid{},
eng_noun:jibberish{},
eng_noun:papionine{},
eng_noun:Feejeean{},
eng_noun:slappy{},
eng_noun:Atlantan{},
eng_noun:wayn{},
eng_noun:turkophone{},
eng_noun:connexive{},
eng_noun:Segovian{},
eng_noun:Wollof{},
eng_noun:antiequalitarian{},
eng_noun:gneissoid{},
eng_noun:Icelandish{},
eng_noun:odontalgic{},
eng_noun:nonchain{},
eng_noun:antiparty{},
eng_noun:prework{},
eng_noun:Rumelian{},
eng_noun:nondependent{},
eng_noun:antirationalist{},
eng_noun:antiprogressive{},
eng_noun:antinociceptive{},
eng_noun:preshave{},
eng_noun:friendy{},
eng_noun:juniour{},
eng_noun:Shirburnian{},
eng_noun:lampriform{},
eng_noun:Palestinean{},
eng_noun:plastick{},
eng_noun:Homoean{},
eng_noun:clashy{},
eng_noun:Malayalee{},
eng_noun:multilobe{},
eng_noun:unworth{},
eng_noun:Monothelete{},
eng_noun:mystick{},
eng_noun:hieroglyphick{},
eng_noun:scholastick{},
eng_noun:ecclesiastick{},
eng_noun:panick{},
eng_noun:Theatine{},
eng_noun:diuretick{},
eng_noun:eccentrick{},
eng_noun:emetick{},
eng_noun:endemick{},
eng_noun:fanatick{},
eng_noun:georgick{},
eng_noun:hectick{},
eng_noun:heretick{},
eng_noun:hysterick{},
eng_noun:iambick{},
eng_noun:melancholick{},
eng_noun:metaphysick{},
eng_noun:Pindarick{},
eng_noun:polemick{},
eng_noun:posteriour{},
eng_noun:Romantick{},
eng_noun:soporifick{},
eng_noun:styptick{},
eng_noun:Stoick{},
eng_noun:nonsonant{},
eng_noun:perticular{},
eng_noun:antihydropic{},
eng_noun:Orkneyan{},
eng_noun:Kurilian{},
eng_noun:doggrel{},
eng_noun:tropick{},
eng_noun:neo - creo{},
eng_noun:bitch - ass{},
eng_noun:arfarfanarf{},
eng_noun:Cephalonian{},
eng_noun:preelection{},
eng_noun:distillatory{},
eng_noun:underhead{},
eng_noun:lamellibranchiate{},
eng_noun:interpause{},
eng_noun:bezoardic{},
eng_noun:theaterical{},
eng_noun:antepileptic{},
eng_noun:Asmonean{},
eng_noun:Biscayan{},
eng_noun:supermaterial{},
eng_noun:reservatory{},
eng_noun:gould{},
eng_noun:foreshot{},
eng_noun:metronymic{},
eng_noun:gallaunt{},
eng_noun:Turanian{},
eng_noun:dickgirl{},
eng_noun:Hutchinsonian{},
eng_noun:fouth{},
eng_noun:Waldensian{},
eng_noun:nash{},
eng_noun:Universalian{},
eng_noun:Tribecan{},
eng_noun:Tyrian{},
eng_noun:nautiloid{},
eng_noun:Socotran{},
eng_noun:curvative{},
eng_noun:depressomotor{},
eng_noun:nucleobranch{},
eng_noun:elasmobranchiate{},
eng_noun:shlenter{},
eng_noun:preobservation{},
eng_noun:antihydrophobic{},
eng_noun:Khazarian{},
eng_noun:neurosyphilitic{},
eng_noun:superdominant{},
eng_noun:ophiurioid{},
eng_noun:ostracoid{},
eng_noun:payen{},
eng_noun:absorbefacient{},
eng_noun:interneural{},
eng_noun:Thuringian{},
eng_noun:classick{},
eng_noun:Shelbyvillian{},
eng_noun:pluriliteral{},
eng_noun:ischuretic{},
eng_noun:tympanohyal{},
eng_noun:carborexic{},
eng_noun:beesome{},
eng_noun:epipterygoid{},
eng_noun:freelage{},
eng_noun:freeledge{},
eng_noun:interrenal{},
eng_noun:Observantine{},
eng_noun:hypobranchial{},
eng_noun:crackerass{},
eng_noun:subopercular{},
eng_noun:Brunonian{},
eng_noun:antipsoric{},
eng_noun:cloam{},
eng_noun:clome{},
eng_noun:sage{},
eng_noun:hand{},
eng_noun:bloom{},
eng_noun:firm{},
eng_noun:grave{},
eng_noun:compact{},
eng_noun:abrupt{},
eng_noun:major{},
eng_noun:window{},
eng_noun:winter{},
eng_noun:exit{},
eng_noun:adulterant{},
eng_noun:ageless{},
eng_noun:antacid{},
eng_noun:anthozoan{},
eng_noun:arboreal{},
eng_noun:asiatic{},
eng_noun:argent{},
eng_noun:aroid{},
eng_noun:bareback{},
eng_noun:batiste{},
eng_noun:bigamy{},
eng_noun:binominal{},
eng_noun:braggart{},
eng_noun:bouffant{},
eng_noun:buccaneer{},
eng_noun:chorine{},
eng_noun:chappy{},
eng_noun:carpal{},
eng_noun:confederate{},
eng_noun:corporal{},
eng_noun:crystalloid{},
eng_noun:combatant{},
eng_noun:cotton{},
eng_noun:covenant{},
eng_noun:coverall{},
eng_noun:cycloid{},
eng_noun:contemplative{},
eng_noun:complex{},
eng_noun:contrast{},
eng_noun:downstairs{},
eng_noun:disincentive{},
eng_noun:druid{},
eng_noun:expectorant{},
eng_noun:encaustic{},
eng_noun:fave{},
eng_noun:fawn{},
eng_noun:fossil{},
eng_noun:freestyle{},
eng_noun:gaudy{},
eng_noun:incentive{},
eng_noun:instant{},
eng_noun:holothurian{},
eng_noun:holstein{},
eng_noun:hominoid{},
eng_noun:itinerary{},
eng_noun:lean{},
eng_noun:interglacial{},
eng_noun:labiovelar{},
eng_noun:laconian{},
eng_noun:julian{},
eng_noun:lamarckism{},
eng_noun:kamikaze{},
eng_noun:maximal{},
eng_noun:minimum{},
eng_noun:livelong{},
eng_noun:maigre{},
eng_noun:medley{},
eng_noun:mammal{},
eng_noun:maniac{},
eng_noun:mohican{},
eng_noun:manual{},
eng_noun:lubricant{},
eng_noun:monogenesis{},
eng_noun:midland{},
eng_noun:moot{},
eng_noun:northumbrian{},
eng_noun:novelty{},
eng_noun:optimum{},
eng_noun:oxytone{},
eng_noun:mulatto{},
eng_noun:nescient{},
eng_noun:neurology{},
eng_noun:orography{},
eng_noun:murrey{},
eng_noun:nile{},
eng_noun:nitrous{},
eng_noun:octosyllable{},
eng_noun:outcast{},
eng_noun:nonpareil{},
eng_noun:overglaze{},
eng_noun:penult{},
eng_noun:perennial{},
eng_noun:parliamentarian{},
eng_noun:party{},
eng_noun:perpendicular{},
eng_noun:psychotherapy{},
eng_noun:ragtime{},
eng_noun:prole{},
eng_noun:premolar{},
eng_noun:rear{},
eng_noun:rodent{},
eng_noun:reptile{},
eng_noun:respondent{},
eng_noun:restorative{},
eng_noun:retardate{},
eng_noun:refrigeratory{},
eng_noun:reverend{},
eng_noun:revolutionary{},
eng_noun:sexennial{},
eng_noun:sextuple{},
eng_noun:sole{},
eng_noun:southpaw{},
eng_noun:septcentenary{},
eng_noun:sigmoid{},
eng_noun:signatory{},
eng_noun:sundry{},
eng_noun:tan{},
eng_noun:straightaway{},
eng_noun:supremacist{},
eng_noun:stable{},
eng_noun:subcontrary{},
eng_noun:submultiple{},
eng_noun:subscript{},
eng_noun:steel{},
eng_noun:substituent{},
eng_noun:tense{},
eng_noun:uliginose{},
eng_noun:ultimate{},
eng_noun:triplicate{},
eng_noun:warrigal{},
eng_noun:wrong{},
eng_noun:vicegerent{},
eng_noun:whit{},
eng_noun:viverrid{},
eng_noun:plain{},
eng_noun:limp{},
eng_noun:bible{},
eng_noun:donovan{},
eng_noun:hesperian{},
eng_noun:mexica{},
eng_noun:murcian{},
eng_noun:qallunaaq{},
eng_noun:velcro{},
eng_noun:cleft{},
eng_noun:lush{},
eng_noun:creed{},
eng_noun:arched{},
eng_noun:bicorn{},
eng_noun:lesser{},
eng_noun:mizzen{},
eng_noun:cimeter{},
eng_noun:gallican{},
eng_noun:filicoid{},
eng_noun:podagric{},
eng_noun:palmiped{},
eng_noun:squamate{},
eng_noun:incompetent{},
eng_noun:repercussive{},
eng_noun:consuetudinary{},
eng_noun:bona{},
eng_noun:bung{},
eng_noun:tagrag{},
eng_noun:cocket{},
eng_noun:game{},
eng_noun:rate{},
eng_noun:nova{},
eng_noun:wont{},
eng_noun:algal{},
eng_noun:offal{},
eng_noun:bluff{},
eng_noun:piano{},
eng_noun:prime{},
eng_noun:pokey{},
eng_noun:rummy{},
eng_noun:contra{},
eng_noun:grunge{},
eng_noun:poison{},
eng_noun:allegro{},
eng_noun:analyte{},
eng_noun:subject{},
eng_noun:olivine{},
eng_noun:singlet{},
eng_noun:topping{},
eng_noun:runaway{},
eng_noun:meaning{},
eng_noun:gangland{},
eng_noun:midfield{},
eng_noun:amnesiac{},
eng_noun:dementia{},
eng_noun:underage{},
eng_noun:civilian{},
eng_noun:halftone{},
eng_noun:malonate{},
eng_noun:initiate{},
eng_noun:glyceryl{},
eng_noun:archrival{},
eng_noun:monoblock{},
eng_noun:ponderosa{},
eng_noun:threonine{},
eng_noun:absurdist{},
eng_noun:hydration{},
eng_noun:millinery{},
eng_noun:firstborn{},
eng_noun:leucovorin{},
eng_noun:riverfront{},
eng_noun:agglomerate{},
eng_noun:exonuclease{},
eng_noun:creationist{},
eng_noun:rechargeable{},
eng_noun:recreational{},
eng_noun:vaudevillian{},
eng_noun:antihypertensive{},
eng_noun:coloured{},
eng_noun:wraparound{},
eng_noun:fizgig{},
eng_noun:derivate{},
eng_noun:trilingual{},
eng_noun:semi{},
eng_noun:encyclical{},
eng_noun:hentai{},
eng_noun:blobber{},
eng_noun:lipoid{},
eng_noun:saint{},
eng_noun:deductible{},
eng_noun:humanoid{},
eng_noun:cruciform{},
eng_noun:gallant{},
eng_noun:vagabond{},
eng_noun:adagio{},
eng_noun:paratransit{},
eng_noun:biochemical{},
eng_noun:hoop{},
eng_noun:voluptuary{},
eng_noun:reach{},
eng_noun:reprobate{},
eng_noun:navarrese{},
eng_noun:crescendo{},
eng_noun:freehold{},
eng_noun:multicellular{},
eng_noun:desiderative{},
eng_noun:bald{},
eng_noun:maroon{},
eng_noun:tercentennial{},
eng_noun:tun{},
eng_noun:doris{},
eng_noun:enclitic{},
eng_noun:mini{},
eng_noun:summa{},
eng_noun:fleet{},
eng_noun:romance{},
eng_noun:continuative{},
eng_noun:float{},
eng_noun:fore{},
eng_noun:dark{},
eng_noun:plainchant{},
eng_noun:obligato{},
eng_noun:catenary{},
eng_noun:psychosurgery{},
eng_noun:fair{},
eng_noun:sexagesimal{},
eng_noun:cossack{},
eng_noun:new york{},
eng_noun:kook{},
eng_noun:laterite{},
eng_noun:interventionist{},
eng_noun:promo{},
eng_noun:hairsplitting{},
eng_noun:blowhard{},
eng_noun:majuscule{},
eng_noun:county{},
eng_noun:bilingual{},
eng_noun:mineral{},
eng_noun:adept{},
eng_noun:natal{},
eng_noun:lay{},
eng_noun:papist{},
eng_noun:novel{},
eng_noun:tiptop{},
eng_noun:default{},
eng_noun:Hayekian{},
eng_noun:preordination{},
eng_noun:triphibian{},
eng_noun:peery{},
eng_noun:antiacetylcholinesterase{},
eng_noun:deafmute{},
eng_noun:postdisco{},
eng_noun:vegetive{},
eng_noun:lyrick{},
eng_noun:monastick{},
eng_noun:italick{},
eng_noun:epidemick{},
eng_noun:exotick{},
eng_noun:dynamick{},
eng_noun:eclectick{},
eng_noun:epileptick{},
eng_noun:escharotick{},
eng_noun:quadratick{},
eng_noun:sudorifick{},
eng_noun:Koorilian{},
eng_noun:Thibetan{},
eng_noun:urodelian{},
eng_noun:pre - cana{},
eng_noun:metallorganic{},
eng_noun:might - be{},
eng_noun:urohyal{},
eng_noun:Pestalozzian{},
eng_noun:Genevese{},
eng_noun:maxillopalatine{},
eng_noun:utilitarianist{},
eng_noun:dodecastyle{},
eng_noun:uncuth{},
eng_noun:Esculapian{},
eng_noun:circumjovial{},
eng_noun:aflagellate{},
eng_noun:aromatick{},
eng_noun:antiparalytic{},
eng_noun:technoid{},
eng_noun:laniary{},
eng_noun:epipharyngeal{},
eng_noun:far{},
eng_noun:which{},
eng_noun:day{},
eng_noun:counter{},
eng_noun:ill{},
eng_noun:adrenal{},
eng_noun:anabolic{},
eng_noun:anglophobe{},
eng_noun:bedouin{},
eng_noun:binomial{},
eng_noun:circular{},
eng_noun:coward{},
eng_noun:crackpot{},
eng_noun:downstate{},
eng_noun:downwind{},
eng_noun:decorative{},
eng_noun:diamagnetic{},
eng_noun:estonian{},
eng_noun:gourmand{},
eng_noun:glare{},
eng_noun:illuminant{},
eng_noun:herbal{},
eng_noun:justiciary{},
eng_noun:malacostracan{},
eng_noun:metalloid{},
eng_noun:luddite{},
eng_noun:opponent{},
eng_noun:nemertean{},
eng_noun:pontifical{},
eng_noun:pseud{},
eng_noun:proboscidean{},
eng_noun:raven{},
eng_noun:quartile{},
eng_noun:regent{},
eng_noun:relaxant{},
eng_noun:spiracle{},
eng_noun:tart{},
eng_noun:tricolour{},
eng_noun:wholegrain{},
eng_noun:well{},
eng_noun:hollow{},
eng_noun:cambrian{},
eng_noun:chaldee{},
eng_noun:pauline{},
eng_noun:textuary{},
eng_noun:cathedra{},
eng_noun:braggadocian{},
eng_noun:self{},
eng_noun:sear{},
eng_noun:haut{},
eng_noun:foul{},
eng_noun:nomen{},
eng_noun:tailor{},
eng_noun:billiard{},
eng_noun:colubrid{},
eng_noun:converse{},
eng_noun:mercurian{},
eng_noun:nighttime{},
eng_noun:antisense{},
eng_noun:southside{},
eng_noun:plaintext{},
eng_noun:antivirus{},
eng_noun:teleporter{},
eng_noun:middleweight{},
eng_noun:dissociative{},
eng_noun:maniraptoran{},
eng_noun:preselection{},
eng_noun:chloroformate{},
eng_noun:concessionary{},
eng_noun:flip{},
eng_noun:interlinear{},
eng_noun:fait{},
eng_noun:dipteran{},
eng_noun:yonder{},
eng_noun:semblant{},
eng_noun:turbo{},
eng_noun:loggerhead{},
eng_noun:platonic{},
eng_noun:corrective{},
eng_noun:slavonian{},
eng_noun:preadolescent{},
eng_noun:purgatory{},
eng_noun:choroid{},
eng_noun:net{},
eng_noun:glamour{},
eng_noun:dud{},
eng_noun:elder{},
eng_noun:postseason{},
eng_noun:carmine{},
eng_noun:feeling{},
eng_noun:darling{},
eng_noun:fishing{},
eng_noun:opening{},
eng_noun:ballooning{},
eng_noun:daring{},
eng_noun:farming{},
eng_noun:birthing{},
eng_noun:screaming{},
eng_noun:wayfaring{},
eng_noun:Acadian{},
eng_noun:alien{},
eng_noun:country{},
eng_noun:market{},
eng_noun:current{},
eng_noun:academic{},
eng_noun:accessory{},
eng_noun:accusative{},
eng_noun:Algerian{},
eng_noun:derivative{},
eng_noun:Brazilian{},
eng_noun:green{},
eng_noun:purple{},
eng_noun:polyglot{},
eng_noun:consonant{},
eng_noun:adamant{},
eng_noun:Indonesian{},
eng_noun:north{},
eng_noun:rainbow{},
eng_noun:bisque{},
eng_noun:cream{},
eng_noun:ivory{},
eng_noun:ebony{},
eng_noun:saffron{},
eng_noun:lilac{},
eng_noun:ochre{},
eng_noun:silly{},
eng_noun:primrose{},
eng_noun:fascist{},
eng_noun:emerald{},
eng_noun:marinara{},
eng_noun:Taiwanese{},
eng_noun:Desi{},
eng_noun:Lithuanian{},
eng_noun:brief{},
eng_noun:spin{},
eng_noun:cover{},
eng_noun:blanket{},
eng_noun:electric{},
eng_noun:shallow{},
eng_noun:sorry{},
eng_noun:vertical{},
eng_noun:analog{},
eng_noun:corporate{},
eng_noun:yon{},
eng_noun:Manchu{},
eng_noun:mock{},
eng_noun:gourmet{},
eng_noun:coffee{},
eng_noun:diurnal{},
eng_noun:original{},
eng_noun:ordinal{},
eng_noun:flight{},
eng_noun:buggy{},
eng_noun:PC{},
eng_noun:steam{},
eng_noun:holy{},
eng_noun:weird{},
eng_noun:tangent{},
eng_noun:negro{},
eng_noun:Bahraini{},
eng_noun:Bolivian{},
eng_noun:Uzbek{},
eng_noun:Jamaican{},
eng_noun:Moroccan{},
eng_noun:Mozambican{},
eng_noun:Chadian{},
eng_noun:Burmese{},
eng_noun:burkinabe{},
eng_noun:Nauruan{},
eng_noun:Micronesian{},
eng_noun:Montserratian{},
eng_noun:Niuean{},
eng_noun:Adrianopolitan{},
eng_noun:soporific{},
eng_noun:Ilocano{},
eng_noun:flamingo{},
eng_noun:festival{},
eng_noun:perspective{},
eng_noun:reliable{},
eng_noun:double{},
eng_noun:kitsch{},
eng_noun:bimillennial{},
eng_noun:diamond{},
eng_noun:heuristic{},
eng_noun:practical{},
eng_noun:empty{},
eng_noun:pyro{},
eng_noun:rogue{},
eng_noun:angelic{},
eng_noun:ornamental{},
eng_noun:expert{},
eng_noun:regulation{},
eng_noun:bisexual{},
eng_noun:remainder{},
eng_noun:uppercase{},
eng_noun:panic{},
eng_noun:component{},
eng_noun:middle{},
eng_noun:maybe{},
eng_noun:oak{},
eng_noun:Islamist{},
eng_noun:roast{},
eng_noun:royal{},
eng_noun:les{},
eng_noun:spiral{},
eng_noun:incident{},
eng_noun:chronic{},
eng_noun:hypothetical{},
eng_noun:penitent{},
eng_noun:aggravative{},
eng_noun:ambulatory{},
eng_noun:giant{},
eng_noun:ay{},
eng_noun:hetty{},
eng_noun:Chechen{},
eng_noun:fatty{},
eng_noun:atheist{},
eng_noun:oblique{},
eng_noun:mild{},
eng_noun:mortal{},
eng_noun:sticky{},
eng_noun:blag{},
eng_noun:lingual{},
eng_noun:pectoral{},
eng_noun:magnetic{},
eng_noun:beryl{},
eng_noun:cornflower{},
eng_noun:subsidiary{},
eng_noun:crispy{},
eng_noun:surrogate{},
eng_noun:virtuoso{},
eng_noun:vivid{},
eng_noun:barren{},
eng_noun:aggro{},
eng_noun:brassy{},
eng_noun:cerise{},
eng_noun:onyx{},
eng_noun:phobic{},
eng_noun:Tory{},
eng_noun:asexual{},
eng_noun:banner{},
eng_noun:midweek{},
eng_noun:mother - of - pearl{},
eng_noun:operant{},
eng_noun:provocative{},
eng_noun:surplus{},
eng_noun:tabby{},
eng_noun:tithe{},
eng_noun:bunny{},
eng_noun:pantheist{},
eng_noun:quantum{},
eng_noun:mid - october{},
eng_noun:mid - march{},
eng_noun:ruminant{},
eng_noun:emetic{},
eng_noun:dexter{},
eng_noun:adolescent{},
eng_noun:lovely{},
eng_noun:pygmalion{},
eng_noun:demotic{},
eng_noun:variant{},
eng_noun:anesthetic{},
eng_noun:thermal{},
eng_noun:sore{},
eng_noun:motor{},
eng_noun:foster{},
eng_noun:Inuit{},
eng_noun:ageist{},
eng_noun:nostalgic{},
eng_noun:aliquot{},
eng_noun:chapel{},
eng_noun:gentle{},
eng_noun:bumper{},
eng_noun:submissive{},
eng_noun:auxiliary{},
eng_noun:radiant{},
eng_noun:woody{},
eng_noun:shank{},
eng_noun:aliphatic{},
eng_noun:editorial{},
eng_noun:soviet{},
eng_noun:fond{},
eng_noun:uniform{},
eng_noun:grande{},
eng_noun:anthropoid{},
eng_noun:intimate{},
eng_noun:chipotle{},
eng_noun:downcast{},
eng_noun:pneumatic{},
eng_noun:fluorescent{},
eng_noun:crank{},
eng_noun:executive{},
eng_noun:heterocyclic{},
eng_noun:cantheist{},
eng_noun:horrible{},
eng_noun:wrath{},
eng_noun:oxytocic{},
eng_noun:stimulant{},
eng_noun:flocculent{},
eng_noun:triskaidekaphobic{},
eng_noun:deadweight{},
eng_noun:warm - up{},
eng_noun:slap - back{},
eng_noun:tactic{},
eng_noun:Hindu{},
eng_noun:wayside{},
eng_noun:droll{},
eng_noun:Victorian{},
eng_noun:Marxist{},
eng_noun:flank{},
eng_noun:utile{},
eng_noun:Urartian{},
eng_noun:underneath{},
eng_noun:craven{},
eng_noun:pedal{},
eng_noun:ormolu{},
eng_noun:Cryogenian{},
eng_noun:blockbuster{},
eng_noun:convalescent{},
eng_noun:specialist{},
eng_noun:labiate{},
eng_noun:anhedral{},
eng_noun:virid{},
eng_noun:cerulean{},
eng_noun:celadon{},
eng_noun:buckskin{},
eng_noun:butterscotch{},
eng_noun:cinereous{},
eng_noun:citrine{},
eng_noun:dirigible{},
eng_noun:antiseptic{},
eng_noun:stammel{},
eng_noun:subfusc{},
eng_noun:terra - cotta{},
eng_noun:amaranthine{},
eng_noun:breakthrough{},
eng_noun:measurable{},
eng_noun:Brythonic{},
eng_noun:purpure{},
eng_noun:polysyllabic{},
eng_noun:detergent{},
eng_noun:Aztec{},
eng_noun:Cantonese{},
eng_noun:Maltese{},
eng_noun:Walachian{},
eng_noun:navicular{},
eng_noun:triquetral{},
eng_noun:mickle{},
eng_noun:Taoist{},
eng_noun:prognostic{},
eng_noun:Eurosceptic{},
eng_noun:stalwart{},
eng_noun:getaway{},
eng_noun:lapidary{},
eng_noun:mendicant{},
eng_noun:retrofit{},
eng_noun:dissident{},
eng_noun:anticonvulsant{},
eng_noun:Blairite{},
eng_noun:expedient{},
eng_noun:pyrotic{},
eng_noun:relict{},
eng_noun:Canuck{},
eng_noun:troy{},
eng_noun:Cajun{},
eng_noun:delectable{},
eng_noun:docent{},
eng_noun:neoteric{},
eng_noun:burlesque{},
eng_noun:malfeasant{},
eng_noun:elegiac{},
eng_noun:chickenshit{},
eng_noun:mystic{},
eng_noun:charismatic{},
eng_noun:composite{},
eng_noun:extremist{},
eng_noun:antistatic{},
eng_noun:recyclable{},
eng_noun:plug - in{},
eng_noun:agrarian{},
eng_noun:tetraploid{},
eng_noun:gammy{},
eng_noun:cheapo{},
eng_noun:trendy{},
eng_noun:bootleg{},
eng_noun:protozoan{},
eng_noun:damson{},
eng_noun:spartan{},
eng_noun:hammy{},
eng_noun:essive{},
eng_noun:yachty{},
eng_noun:topiary{},
eng_noun:unwonted{},
eng_noun:unpredictable{},
eng_noun:Tridentine{},
eng_noun:monochrome{},
eng_noun:mosaic{},
eng_noun:chinky{},
eng_noun:coloratura{},
eng_noun:epidural{},
eng_noun:resultant{},
eng_noun:consumptive{},
eng_noun:sedative{},
eng_noun:initiative{},
eng_noun:carbolic{},
eng_noun:underarm{},
eng_noun:heteroclitic{},
eng_noun:quadruplicate{},
eng_noun:Dalmatian{},
eng_noun:obsidian{},
eng_noun:Ossetian{},
eng_noun:vermillion{},
eng_noun:parenthetical{},
eng_noun:epispastic{},
eng_noun:midcareer{},
eng_noun:peg - leg{},
eng_noun:perfecto{},
eng_noun:mignon{},
eng_noun:incomparable{},
eng_noun:hourly{},
eng_noun:irreducible{},
eng_noun:chauvinist{},
eng_noun:downslope{},
eng_noun:Mycenaean{},
eng_noun:retentive{},
eng_noun:seltzer{},
eng_noun:pincer{},
eng_noun:decillionth{},
eng_noun:zillionth{},
eng_noun:excommunicate{},
eng_noun:stirrup{},
eng_noun:goldy{},
eng_noun:Assyrian{},
eng_noun:drinkable{},
eng_noun:fallback{},
eng_noun:chipper{},
eng_noun:implosive{},
eng_noun:psychotomimetic{},
eng_noun:intoxicant{},
eng_noun:vermeil{},
eng_noun:imperfective{},
eng_noun:fremd{},
eng_noun:cayenne{},
eng_noun:juridical{},
eng_noun:marriageable{},
eng_noun:Straussian{},
eng_noun:Bashkir{},
eng_noun:solitaire{},
eng_noun:downstage{},
eng_noun:mortuary{},
eng_noun:ferroelectric{},
eng_noun:mair{},
eng_noun:outbound{},
eng_noun:valedictory{},
eng_noun:larrikin{},
eng_noun:panzoist{},
eng_noun:Vegliote{},
eng_noun:extrusive{},
eng_noun:hymeneal{},
eng_noun:visitant{},
eng_noun:multiracial{},
eng_noun:polymorphonuclear{},
eng_noun:swidden{},
eng_noun:sensationalist{},
eng_noun:Newfie{},
eng_noun:nonacid{},
eng_noun:parabolic{},
eng_noun:jumbo{},
eng_noun:dolichocephalic{},
eng_noun:roborant{},
eng_noun:beat - up{},
eng_noun:zebrine{},
eng_noun:hypnotizable{},
eng_noun:lenticular{},
eng_noun:Thessalonian{},
eng_noun:coequal{},
eng_noun:sourdough{},
eng_noun:instructional{},
eng_noun:sit - down{},
eng_noun:communicant{},
eng_noun:sequent{},
eng_noun:constructionist{},
eng_noun:Atlantean{},
eng_noun:Mende{},
eng_noun:infective{},
eng_noun:polysilicon{},
eng_noun:unperceptive{},
eng_noun:unknowable{},
eng_noun:Reichian{},
eng_noun:undefeatable{},
eng_noun:miz{},
eng_noun:globalist{},
eng_noun:unsuspicious{},
eng_noun:metatherian{},
eng_noun:Mazanderani{},
eng_noun:Mccarthyite{},
eng_noun:horseflesh{},
eng_noun:extern{},
eng_noun:patch - up{},
eng_noun:Chinggisid{},
eng_noun:dactylic{},
eng_noun:outstation{},
eng_noun:Islamofascist{},
eng_noun:Kymric{},
eng_noun:intrastate{},
eng_noun:Confucian{},
eng_noun:incommensurable{},
eng_noun:arachnoid{},
eng_noun:dogtrot{},
eng_noun:downbeat{},
eng_noun:ticky - tacky{},
eng_noun:newsy{},
eng_noun:Ligurian{},
eng_noun:nonacademic{},
eng_noun:antiretroviral{},
eng_noun:alternant{},
eng_noun:postnoun{},
eng_noun:Pelasgian{},
eng_noun:subtonic{},
eng_noun:affluential{},
eng_noun:upstyle{},
eng_noun:down - style{},
eng_noun:unionist{},
eng_noun:globoid{},
eng_noun:Appalachian{},
eng_noun:graminoid{},
eng_noun:slam - bang{},
eng_noun:splittist{},
eng_noun:levirate{},
eng_noun:Japonica{},
eng_noun:noncriminal{},
eng_noun:Washingtonian{},
eng_noun:haplodiploid{},
eng_noun:nonintellectual{},
eng_noun:keene{},
eng_noun:Scythian{},
eng_noun:conductant{},
eng_noun:administrant{},
eng_noun:omphaloskeptic{},
eng_noun:binational{},
eng_noun:omnilingual{},
eng_noun:aminoethyl{},
eng_noun:Europan{},
eng_noun:meshuggener{},
eng_noun:Carian{},
eng_noun:Czechoslovak{},
eng_noun:phytopharmaceutical{},
eng_noun:bedrel{},
eng_noun:nonprotein{},
eng_noun:sympathomimetic{},
eng_noun:microphase{},
eng_noun:antihemorrhagic{},
eng_noun:antirachitic{},
eng_noun:rejectionist{},
eng_noun:verdictive{},
eng_noun:shortcrust{},
eng_noun:Labradorian{},
eng_noun:coin - op{},
eng_noun:Dagestani{},
eng_noun:intersex{},
eng_noun:tricuspid{},
eng_noun:paintery{},
eng_noun:antilithic{},
eng_noun:constitutionalist{},
eng_noun:amphiprostyle{},
eng_noun:Stuckist{},
eng_noun:pedophiliac{},
eng_noun:therian{},
eng_noun:Piscean{},
eng_noun:Libran{},
eng_noun:lepetodrilid{},
eng_noun:nuchal{},
eng_noun:melony{},
eng_noun:aquaholic{},
eng_noun:rectosigmoid{},
eng_noun:Guadeloupian{},
eng_noun:supralittoral{},
eng_noun:postcapillary{},
eng_noun:yogist{},
eng_noun:unergative{},
eng_noun:Camun{},
eng_noun:nondiabetic{},
eng_noun:nonstate{},
eng_noun:Tanganyikan{},
eng_noun:tetradactyl{},
eng_noun:Genoan{},
eng_noun:nonroyal{},
eng_noun:counterterrorist{},
eng_noun:Magdeburgian{},
eng_noun:auteurist{},
eng_noun:galliform{},
eng_noun:nondurable{},
eng_noun:externalist{},
eng_noun:sortal{},
eng_noun:multitouch{},
eng_noun:photorealist{},
eng_noun:midmarket{},
eng_noun:paternalist{},
eng_noun:postadolescent{},
eng_noun:autosexual{},
eng_noun:prestimulation{},
eng_noun:aliterate{},
eng_noun:cyberian{},
eng_noun:noncountry{},
eng_noun:intermorph{},
eng_noun:reassortant{},
eng_noun:quinoid{},
eng_noun:gastrokinetic{},
eng_noun:Martiniquan{},
eng_noun:antihyperglycemic{},
eng_noun:midgame{},
eng_noun:Pequiste{},
eng_noun:nonrelative{},
eng_noun:habiline{},
eng_noun:nonasthmatic{},
eng_noun:nonmortal{},
eng_noun:selachian{},
eng_noun:Varsovian{},
eng_noun:Budapestian{},
eng_noun:Lisboner{},
eng_noun:Tallinner{},
eng_noun:elevenish{},
eng_noun:Medinan{},
eng_noun:Megrelian{},
eng_noun:Sabean{},
eng_noun:lemuroid{},
eng_noun:oolitic{},
eng_noun:Sahelian{},
eng_noun:forprofit{},
eng_noun:Katangese{},
eng_noun:farmaceutical{},
eng_noun:multiduplex{},
eng_noun:shelly{},
eng_noun:cocktailian{},
eng_noun:biomusical{},
eng_noun:Ordophone{},
eng_noun:anti - christian{},
eng_noun:Zapotecan{},
eng_noun:nonserial{},
eng_noun:Brutalist{},
eng_noun:uniglot{},
eng_noun:nonheterosexual{},
eng_noun:noninjury{},
eng_noun:nonnovel{},
eng_noun:Transcaucasian{},
eng_noun:Medean{},
eng_noun:nonpolynomial{},
eng_noun:Pompeiian{},
eng_noun:nonpsychic{},
eng_noun:noncompound{},
eng_noun:Londonian{},
eng_noun:noncrystal{},
eng_noun:algebroid{},
eng_noun:operculate{},
eng_noun:ablutophiliac{},
eng_noun:shortfin{},
eng_noun:nonliberal{},
eng_noun:Calmuck{},
eng_noun:superinvariant{},
eng_noun:equant{},
eng_noun:predoc{},
eng_noun:lumbricine{},
eng_noun:tabanid{},
eng_noun:multiskyrmion{},
eng_noun:conditionate{},
eng_noun:Manichee{},
eng_noun:Shimerian{},
eng_noun:stipendiary{},
eng_noun:postcommunist{},
eng_noun:Antiochan{},
eng_noun:Hartlepudlian{},
eng_noun:nonresistor{},
eng_noun:hydatoid{},
eng_noun:epinician{},
eng_noun:hyperepidemic{},
eng_noun:mid - season{},
eng_noun:outland{},
eng_noun:anticonvulsive{},
eng_noun:acoelomate{},
eng_noun:misocapnist{},
eng_noun:Torontarian{},
eng_noun:Cabindan{},
eng_noun:theocratical{},
eng_noun:Pannonian{},
eng_noun:Sogdian{},
eng_noun:unthrift{},
eng_noun:Barcelonan{},
eng_noun:Navarran{},
eng_noun:feudalist{},
eng_noun:Paracelsian{},
eng_noun:nibbly{},
eng_noun:Wykehamist{},
eng_noun:perlative{},
eng_noun:umbratile{},
eng_noun:Oviedan{},
eng_noun:cybertopian{},
eng_noun:nonretirement{},
eng_noun:Palamite{},
eng_noun:neosocialist{},
eng_noun:suprematist{},
eng_noun:culturist{},
eng_noun:homeful{},
eng_noun:nonroyalty{},
eng_noun:Wessexian{},
eng_noun:Jugoslavian{},
eng_noun:Idumean{},
eng_noun:psychoneurotic{},
eng_noun:zoantharian{},
eng_noun:Butlerian{},
eng_noun:whity{},
eng_noun:polyodont{},
eng_noun:dicty{},
eng_noun:nongroup{},
eng_noun:acting{},
eng_noun:striking{},
eng_noun:taking{},
eng_noun:piping{},
eng_noun:bleeding{},
eng_noun:boding{},
eng_noun:ageing{},
eng_noun:youngling{},
eng_noun:bitter{},
eng_noun:head{},
eng_noun:abortifacient{},
eng_noun:accessary{},
eng_noun:plural{},
eng_noun:autumn{},
eng_noun:Polish{},
eng_noun:zero{},
eng_noun:Irish{},
eng_noun:Mexican{},
eng_noun:Spanish{},
eng_noun:absorbent{},
eng_noun:Afghan{},
eng_noun:dilettante{},
eng_noun:henna{},
eng_noun:cherry{},
eng_noun:mauve{},
eng_noun:edible{},
eng_noun:Hawaiian{},
eng_noun:Zuni{},
eng_noun:Hebrew{},
eng_noun:square{},
eng_noun:myriad{},
eng_noun:adjunct{},
eng_noun:concrete{},
eng_noun:neuter{},
eng_noun:west{},
eng_noun:ordinate{},
eng_noun:northwest{},
eng_noun:cyan{},
eng_noun:gun{},
eng_noun:cinnamon{},
eng_noun:melancholy{},
eng_noun:Adelaidean{},
eng_noun:polycystid{},
eng_noun:adherent{},
eng_noun:graduate{},
eng_noun:business{},
eng_noun:contemporary{},
eng_noun:wildcat{},
eng_noun:dairy{},
eng_noun:expletive{},
eng_noun:dead{},
eng_noun:dull{},
eng_noun:crown{},
eng_noun:feminine{},
eng_noun:clutch{},
eng_noun:kin{},
eng_noun:homosexual{},
eng_noun:Cypriot{},
eng_noun:Emirian{},
eng_noun:Antiguan{},
eng_noun:Antillean{},
eng_noun:obsessive{},
eng_noun:garden{},
eng_noun:paper{},
eng_noun:oddball{},
eng_noun:damp{},
eng_noun:neon{},
eng_noun:platinum{},
eng_noun:Scandinavian{},
eng_noun:gut{},
eng_noun:Achaean{},
eng_noun:minion{},
eng_noun:vegetarian{},
eng_noun:Tagalog{},
eng_noun:flammable{},
eng_noun:acute{},
eng_noun:cross{},
eng_noun:Botswanan{},
eng_noun:Nigerian{},
eng_noun:lesbian{},
eng_noun:Honduran{},
eng_noun:Guamanian{},
eng_noun:Guyanese{},
eng_noun:Syrian{},
eng_noun:Tajik{},
eng_noun:Surinamese{},
eng_noun:Lao{},
eng_noun:Magnesian{},
eng_noun:Nicaraguan{},
eng_noun:Tanzanian{},
eng_noun:Wallachian{},
eng_noun:mushroom{},
eng_noun:biennial{},
eng_noun:occult{},
eng_noun:castrato{},
eng_noun:wheat{},
eng_noun:minor{},
eng_noun:Francophone{},
eng_noun:pretty{},
eng_noun:puce{},
eng_noun:annual{},
eng_noun:Urdu{},
eng_noun:rad{},
eng_noun:similar{},
eng_noun:arch{},
eng_noun:diagonal{},
eng_noun:jelly{},
eng_noun:largo{},
eng_noun:snug{},
eng_noun:hardy{},
eng_noun:skinny{},
eng_noun:amiss{},
eng_noun:clairvoyant{},
eng_noun:brilliant{},
eng_noun:antiquarian{},
eng_noun:anosmic{},
eng_noun:bastard{},
eng_noun:bubbly{},
eng_noun:average{},
eng_noun:venti{},
eng_noun:inverse{},
eng_noun:poly{},
eng_noun:shithouse{},
eng_noun:cesarean{},
eng_noun:Keynesian{},
eng_noun:senior{},
eng_noun:analogue{},
eng_noun:celibate{},
eng_noun:offbeat{},
eng_noun:fou{},
eng_noun:equine{},
eng_noun:positive{},
eng_noun:belligerent{},
eng_noun:part{},
eng_noun:avocative{},
eng_noun:turnkey{},
eng_noun:apostate{},
eng_noun:patronymic{},
eng_noun:granny{},
eng_noun:amphibian{},
eng_noun:Shakespearean{},
eng_noun:pocket{},
eng_noun:resident{},
eng_noun:Livonian{},
eng_noun:immortal{},
eng_noun:makeshift{},
eng_noun:material{},
eng_noun:dyslexic{},
eng_noun:orphan{},
eng_noun:eagre{},
eng_noun:colic{},
eng_noun:Norman{},
eng_noun:nasal{},
eng_noun:tantamount{},
eng_noun:Islamite{},
eng_noun:inferior{},
eng_noun:pandemic{},
eng_noun:beloved{},
eng_noun:epoxy{},
eng_noun:macho{},
eng_noun:plumb{},
eng_noun:slurry{},
eng_noun:bridal{},
eng_noun:circumstantial{},
eng_noun:eager{},
eng_noun:expatriate{},
eng_noun:liege{},
eng_noun:mignonette{},
eng_noun:skimp{},
eng_noun:slack{},
eng_noun:tally{},
eng_noun:unicellular{},
eng_noun:vassal{},
eng_noun:trip{},
eng_noun:corrosive{},
eng_noun:lastborn{},
eng_noun:international{},
eng_noun:derelict{},
eng_noun:aspirate{},
eng_noun:retractable{},
eng_noun:legion{},
eng_noun:Bajan{},
eng_noun:sissy{},
eng_noun:mid - may{},
eng_noun:mid - autumn{},
eng_noun:hepatic{},
eng_noun:cathartic{},
eng_noun:addictive{},
eng_noun:fairytale{},
eng_noun:innocent{},
eng_noun:metacarpal{},
eng_noun:opaque{},
eng_noun:grotesque{},
eng_noun:noble{},
eng_noun:equestrian{},
eng_noun:Ilokano{},
eng_noun:everyday{},
eng_noun:specific{},
eng_noun:Syriac{},
eng_noun:western{},
eng_noun:circumflex{},
eng_noun:bomber{},
eng_noun:household{},
eng_noun:defensive{},
eng_noun:portable{},
eng_noun:atypical{},
eng_noun:phantom{},
eng_noun:illegal{},
eng_noun:centenarian{},
eng_noun:Ulster{},
eng_noun:multiple{},
eng_noun:gross{},
eng_noun:oatmeal{},
eng_noun:helter - skelter{},
eng_noun:furry{},
eng_noun:heteroclite{},
eng_noun:intangible{},
eng_noun:canine{},
eng_noun:gutter{},
eng_noun:inner{},
eng_noun:coy{},
eng_noun:angiosperm{},
eng_noun:greeny{},
eng_noun:menial{},
eng_noun:melancholic{},
eng_noun:cripple{},
eng_noun:contraband{},
eng_noun:suave{},
eng_noun:influential{},
eng_noun:duplicate{},
eng_noun:colonial{},
eng_noun:coeval{},
eng_noun:conspecific{},
eng_noun:heterospecific{},
eng_noun:chordate{},
eng_noun:gradual{},
eng_noun:vinyl{},
eng_noun:vitreous{},
eng_noun:stannary{},
eng_noun:moldy{},
eng_noun:peekaboo{},
eng_noun:morning - after{},
eng_noun:germanophone{},
eng_noun:lax{},
eng_noun:monosyllabic{},
eng_noun:perse{},
eng_noun:meta{},
eng_noun:sable{},
eng_noun:digitigrade{},
eng_noun:transorbital{},
eng_noun:Hadean{},
eng_noun:Ectasian{},
eng_noun:Cisuralian{},
eng_noun:deodorant{},
eng_noun:lightweight{},
eng_noun:sexagenarian{},
eng_noun:Serb{},
eng_noun:cornsilk{},
eng_noun:rustic{},
eng_noun:heather{},
eng_noun:honeydew{},
eng_noun:incarnadine{},
eng_noun:malachite{},
eng_noun:hairpin{},
eng_noun:intermediate{},
eng_noun:monotreme{},
eng_noun:cuboid{},
eng_noun:metatarsal{},
eng_noun:Ewe{},
eng_noun:Grit{},
eng_noun:Kiwi{},
eng_noun:Samaritan{},
eng_noun:bonny{},
eng_noun:sesamoid{},
eng_noun:kneejerk{},
eng_noun:refractory{},
eng_noun:lowdown{},
eng_noun:antibiotic{},
eng_noun:Paleolithic{},
eng_noun:breakaway{},
eng_noun:povvo{},
eng_noun:leftover{},
eng_noun:Neptunian{},
eng_noun:antiknock{},
eng_noun:GI{},
eng_noun:Jovian{},
eng_noun:smartass{},
eng_noun:antivivisectionist{},
eng_noun:bohemian{},
eng_noun:midi{},
eng_noun:schemie{},
eng_noun:antichristian{},
eng_noun:pineal{},
eng_noun:lymphatic{},
eng_noun:collective{},
eng_noun:aspirational{},
eng_noun:fribble{},
eng_noun:anaesthetic{},
eng_noun:haploid{},
eng_noun:Devanagari{},
eng_noun:effluent{},
eng_noun:cozy{},
eng_noun:receivable{},
eng_noun:Haligonian{},
eng_noun:tricolpate{},
eng_noun:freelance{},
eng_noun:luke{},
eng_noun:antiparallel{},
eng_noun:directional{},
eng_noun:distaff{},
eng_noun:antiarrhythmic{},
eng_noun:requisite{},
eng_noun:antitrust{},
eng_noun:reactionary{},
eng_noun:dapple{},
eng_noun:reflex{},
eng_noun:Baptist{},
eng_noun:jet - black{},
eng_noun:Aleut{},
eng_noun:equinoctial{},
eng_noun:baptismal{},
eng_noun:antimissile{},
eng_noun:linden{},
eng_noun:Lycian{},
eng_noun:humanitarian{},
eng_noun:hickory{},
eng_noun:diametral{},
eng_noun:moony{},
eng_noun:intercostal{},
eng_noun:abessive{},
eng_noun:Hessian{},
eng_noun:needful{},
eng_noun:Aleutian{},
eng_noun:ensuite{},
eng_noun:dodecyl{},
eng_noun:incumbent{},
eng_noun:cycloplegic{},
eng_noun:depressive{},
eng_noun:glassy{},
eng_noun:bijou{},
eng_noun:hyperborean{},
eng_noun:Laodicean{},
eng_noun:inboard{},
eng_noun:diehard{},
eng_noun:trillionth{},
eng_noun:Tyrolean{},
eng_noun:cricoid{},
eng_noun:lusk{},
eng_noun:ponent{},
eng_noun:postpositive{},
eng_noun:Carolingian{},
eng_noun:riverside{},
eng_noun:denominative{},
eng_noun:cinderblock{},
eng_noun:saltwater{},
eng_noun:ptarmic{},
eng_noun:equilateral{},
eng_noun:prohibitive{},
eng_noun:Beotian{},
eng_noun:paisley{},
eng_noun:bolshie{},
eng_noun:polyacoustic{},
eng_noun:lardy{},
eng_noun:polybromide{},
eng_noun:saurian{},
eng_noun:ack - ack{},
eng_noun:anthelmintic{},
eng_noun:sav{},
eng_noun:lesbigay{},
eng_noun:Montenegrin{},
eng_noun:carminative{},
eng_noun:suction{},
eng_noun:Oceanian{},
eng_noun:northerly{},
eng_noun:suicidal{},
eng_noun:spiritualist{},
eng_noun:co - ordinate{},
eng_noun:pitmatic{},
eng_noun:nanoscale{},
eng_noun:adoptionist{},
eng_noun:athel{},
eng_noun:virginal{},
eng_noun:Tokyoite{},
eng_noun:Galwegian{},
eng_noun:wussy{},
eng_noun:claustrophobic{},
eng_noun:neanderthal{},
eng_noun:water - repellent{},
eng_noun:denary{},
eng_noun:Sudovian{},
eng_noun:confederationist{},
eng_noun:wrinkly{},
eng_noun:two - piece{},
eng_noun:Hindoo{},
eng_noun:sackful{},
eng_noun:helminthic{},
eng_noun:Earthican{},
eng_noun:tabletop{},
eng_noun:unpalatable{},
eng_noun:mitigant{},
eng_noun:apotreptic{},
eng_noun:darnedest{},
eng_noun:untouchable{},
eng_noun:hooky{},
eng_noun:intersexual{},
eng_noun:subnormal{},
eng_noun:uninsured{},
eng_noun:monoploid{},
eng_noun:glenoid{},
eng_noun:Australopithecine{},
eng_noun:opioid{},
eng_noun:purist{},
eng_noun:codependent{},
eng_noun:Umbrian{},
eng_noun:semipro{},
eng_noun:gentilic{},
eng_noun:multiplicative{},
eng_noun:falsificationist{},
eng_noun:nonreproductive{},
eng_noun:Miztec{},
eng_noun:hugger - mugger{},
eng_noun:lactovegetarian{},
eng_noun:molariform{},
eng_noun:Druze{},
eng_noun:ataractic{},
eng_noun:polypharmaceutical{},
eng_noun:cheapjack{},
eng_noun:manufactory{},
eng_noun:extractive{},
eng_noun:coliform{},
eng_noun:pendent{},
eng_noun:unregenerate{},
eng_noun:quickset{},
eng_noun:properispomenon{},
eng_noun:genderqueer{},
eng_noun:Acheulian{},
eng_noun:precognitive{},
eng_noun:throwaway{},
eng_noun:optoelectronic{},
eng_noun:watchet{},
eng_noun:Transnistrian{},
eng_noun:cryptofascist{},
eng_noun:Pohnpeian{},
eng_noun:preflight{},
eng_noun:purty{},
eng_noun:ragtag{},
eng_noun:Filipina{},
eng_noun:Sicanian{},
eng_noun:Dundonian{},
eng_noun:decapod{},
eng_noun:tip - top{},
eng_noun:hyracoid{},
eng_noun:daimonic{},
eng_noun:protostomian{},
eng_noun:proturan{},
eng_noun:psittacosaurid{},
eng_noun:pteropod{},
eng_noun:Pueblan{},
eng_noun:organofluorine{},
eng_noun:nonwhite{},
eng_noun:preorder{},
eng_noun:criss - cross{},
eng_noun:cyprinid{},
eng_noun:invasionist{},
eng_noun:nonnative{},
eng_noun:cholesteric{},
eng_noun:cepheid{},
eng_noun:bughouse{},
eng_noun:catawampus{},
eng_noun:mammillary{},
eng_noun:sarcoid{},
eng_noun:hypergeometric{},
eng_noun:Cantabrigian{},
eng_noun:murrion{},
eng_noun:cheveril{},
eng_noun:split - squad{},
eng_noun:pharmaceutic{},
eng_noun:aminomethoxy{},
eng_noun:nitroaromatic{},
eng_noun:Nassuvian{},
eng_noun:carriable{},
eng_noun:sinusoid{},
eng_noun:nonbiodegradable{},
eng_noun:proteinomimetic{},
eng_noun:untime{},
eng_noun:salientian{},
eng_noun:Nietzschean{},
eng_noun:Venizelist{},
eng_noun:univariate{},
eng_noun:Reginan{},
eng_noun:edentate{},
eng_noun:Mordvinian{},
eng_noun:Buryat{},
eng_noun:Udmurtian{},
eng_noun:polynemid{},
eng_noun:megapode{},
eng_noun:duoplural{},
eng_noun:xerophytic{},
eng_noun:Cumbrian{},
eng_noun:Salopian{},
eng_noun:unicursal{},
eng_noun:Montanan{},
eng_noun:prostyle{},
eng_noun:Xaverian{},
eng_noun:hemichordate{},
eng_noun:Sagittarian{},
eng_noun:scombrid{},
eng_noun:thyasirid{},
eng_noun:virostatic{},
eng_noun:musculotropic{},
eng_noun:Catalonian{},
eng_noun:disphenoid{},
eng_noun:hobohemian{},
eng_noun:Argentinean{},
eng_noun:technoutopian{},
eng_noun:allotetraploid{},
eng_noun:practic{},
eng_noun:Illinoisan{},
eng_noun:cartilaginoid{},
eng_noun:diamante{},
eng_noun:beachside{},
eng_noun:depositary{},
eng_noun:nonbank{},
eng_noun:mucolytic{},
eng_noun:didacticist{},
eng_noun:institutionalist{},
eng_noun:umbre{},
eng_noun:Jansenist{},
eng_noun:Savonian{},
eng_noun:Madagascarian{},
eng_noun:Madeiran{},
eng_noun:ticky{},
eng_noun:knockabout{},
eng_noun:curbside{},
eng_noun:postfeminist{},
eng_noun:indolic{},
eng_noun:unilateralist{},
eng_noun:tephritid{},
eng_noun:cardio{},
eng_noun:boine{},
eng_noun:prestart{},
eng_noun:internalist{},
eng_noun:primitivist{},
eng_noun:Baconian{},
eng_noun:midtempo{},
eng_noun:Seljuk{},
eng_noun:dualist{},
eng_noun:inferentialist{},
eng_noun:Malabarian{},
eng_noun:midmeal{},
eng_noun:superheavyweight{},
eng_noun:anti - rad{},
eng_noun:sexcentenary{},
eng_noun:anticholesterol{},
eng_noun:functionless{},
eng_noun:corsive{},
eng_noun:Marcosian{},
eng_noun:venitive{},
eng_noun:hemiplegic{},
eng_noun:jaden{},
eng_noun:dispensationalist{},
eng_noun:Helsinkian{},
eng_noun:Seoulite{},
eng_noun:beardy{},
eng_noun:zalambdodont{},
eng_noun:misotheist{},
eng_noun:Bahian{},
eng_noun:valgus{},
eng_noun:antepaenultimate{},
eng_noun:latitudinarian{},
eng_noun:albuminoid{},
eng_noun:eclecticist{},
eng_noun:nonprimitive{},
eng_noun:antidemocracy{},
eng_noun:antimonial{},
eng_noun:calmative{},
eng_noun:deadeye{},
eng_noun:prefeminism{},
eng_noun:slipover{},
eng_noun:prototherian{},
eng_noun:quadrumane{},
eng_noun:agnathan{},
eng_noun:speciest{},
eng_noun:syrphid{},
eng_noun:nonanxiety{},
eng_noun:Pawnee{},
eng_noun:subharmonic{},
eng_noun:Zambezian{},
eng_noun:feodatory{},
eng_noun:antiasthmatic{},
eng_noun:bifundamental{},
eng_noun:interarrival{},
eng_noun:litho{},
eng_noun:subfilter{},
eng_noun:bimillenary{},
eng_noun:Arietian{},
eng_noun:beavery{},
eng_noun:declensionist{},
eng_noun:overdede{},
eng_noun:comprovincial{},
eng_noun:nonmarxist{},
eng_noun:gymnic{},
eng_noun:Nisibene{},
eng_noun:Antiochene{},
eng_noun:fielden{},
eng_noun:Ruritanian{},
eng_noun:Muscatian{},
eng_noun:nonelitist{},
eng_noun:thalline{},
eng_noun:sternocleidomastoid{},
eng_noun:Catalanophile{},
eng_noun:blinky{},
eng_noun:nontime{},
eng_noun:cubital{},
eng_noun:specky{},
eng_noun:Raelian{},
eng_noun:antistrange{},
eng_noun:selenodont{},
eng_noun:dropside{},
eng_noun:lapidarian{},
eng_noun:antisexist{},
eng_noun:anticonsumer{},
eng_noun:antiluetic{},
eng_noun:Seljuq{},
eng_noun:cheapie{},
eng_noun:Maxwellian{},
eng_noun:ecbolic{},
eng_noun:Kamchatkan{},
eng_noun:Amerasian{},
eng_noun:Hoisanese{},
eng_noun:Judaica{},
eng_noun:antifebrile{},
eng_noun:Flavian{},
eng_noun:Julio - claudian{},
eng_noun:offscum{},
eng_noun:mensk{},
eng_noun:coterminal{},
eng_noun:nonobservable{},
eng_noun:twissel{},
eng_noun:amenorrheic{},
eng_noun:ivorine{},
eng_noun:antialarmist{},
eng_noun:superiour{},
eng_noun:questuary{},
eng_noun:pneumoniac{},
eng_noun:antiegalitarian{},
eng_noun:Bloomfieldian{},
eng_noun:Kiriwinan{},
eng_noun:qued{},
eng_noun:asthmatick{},
eng_noun:diagnostick{},
eng_noun:ethick{},
eng_noun:cathartick{},
eng_noun:epispastick{},
eng_noun:vinny{},
eng_noun:sweetkin{},
eng_noun:roddy{},
eng_noun:podunk{},
eng_noun:Havanese{},
eng_noun:nasoturbinate{},
eng_noun:giaunt{},
eng_noun:lithotriptic{},
eng_noun:bodyswap{},
eng_noun:periotic{},
eng_noun:roughtail{},
eng_noun:experimentarian{},
eng_noun:Chaldaic{},
eng_noun:Transoxianan{},
eng_noun:postobservation{},
eng_noun:sphingine{},
eng_noun:frolick{},
eng_noun:ascetick{},
eng_noun:relaxative{},
eng_noun:anticriticism{},
eng_noun:antidotary{},
eng_noun:polystyle{},
eng_noun:antemetic{},
eng_noun:festucine{},
eng_noun:spring{},
eng_noun:fast{},
eng_noun:light{},
eng_noun:goose{},
eng_noun:broadloom{},
eng_noun:clamour{},
eng_noun:cleric{},
eng_noun:corollary{},
eng_noun:continuant{},
eng_noun:cranny{},
eng_noun:compound{},
eng_noun:durative{},
eng_noun:earthenware{},
eng_noun:exponent{},
eng_noun:emigrant{},
eng_noun:flagellant{},
eng_noun:folio{},
eng_noun:holograph{},
eng_noun:javanese{},
eng_noun:intermediary{},
eng_noun:interrogative{},
eng_noun:lakeside{},
eng_noun:livery{},
eng_noun:manifold{},
eng_noun:mongrel{},
eng_noun:monitory{},
eng_noun:monomial{},
eng_noun:matey{},
eng_noun:oolite{},
eng_noun:netherlander{},
eng_noun:myriapod{},
eng_noun:parnassian{},
eng_noun:prismoid{},
eng_noun:precious{},
eng_noun:quatercentenary{},
eng_noun:preservative{},
eng_noun:reflexive{},
eng_noun:refrigerant{},
eng_noun:slub{},
eng_noun:superintendent{},
eng_noun:surd{},
eng_noun:squab{},
eng_noun:swash{},
eng_noun:statuary{},
eng_noun:tylopod{},
eng_noun:unison{},
eng_noun:ultramarine{},
eng_noun:tunicate{},
eng_noun:transmigrant{},
eng_noun:albanian{},
eng_noun:blu - ray{},
eng_noun:gullah{},
eng_noun:samogitian{},
eng_noun:hedge{},
eng_noun:savory{},
eng_noun:indie{},
eng_noun:ortho{},
eng_noun:affine{},
eng_noun:probit{},
eng_noun:minute{},
eng_noun:presto{},
eng_noun:rawhide{},
eng_noun:retinal{},
eng_noun:earnest{},
eng_noun:maltose{},
eng_noun:kibbutz{},
eng_noun:emeritus{},
eng_noun:hatchback{},
eng_noun:preseason{},
eng_noun:greenfield{},
eng_noun:multiethnic{},
eng_noun:suppressant{},
eng_noun:quadriplegic{},
eng_noun:hypertensive{},
eng_noun:ornithischian{},
eng_noun:regal{},
eng_noun:missionary{},
eng_noun:endomorph{},
eng_noun:pendentive{},
eng_noun:comforter{},
eng_noun:fulness{},
eng_noun:legato{},
eng_noun:existent{},
eng_noun:longing{},
eng_noun:inebriate{},
eng_noun:yugoslavian{},
eng_noun:mean{},
eng_noun:highbrow{},
eng_noun:tarnation{},
eng_noun:beautification{},
eng_noun:sooth{},
eng_noun:Broadway{},
eng_noun:Aspergerian{},
eng_noun:recce{},
eng_noun:doppio{},
eng_noun:Chicano{},
eng_noun:Teflon{},
eng_noun:unreachable{},
eng_noun:quant{},
eng_noun:Avar{},
eng_noun:inspissant{},
eng_noun:Hurrian{},
eng_noun:Mestee{},
eng_noun:incombustible{},
eng_noun:stainless{},
eng_noun:secessionist{},
eng_noun:jacquard{},
eng_noun:reformatory{},
eng_noun:unaffected{},
eng_noun:Socratic{},
eng_noun:completist{},
eng_noun:antifeminist{},
eng_noun:complimentary{},
eng_noun:subtropical{},
eng_noun:Michigander{},
eng_noun:non - profit{},
eng_noun:whistle - stop{},
eng_noun:fairyland{},
eng_noun:uncommunicative{},
eng_noun:newlywed{},
eng_noun:jerkwater{},
eng_noun:phytochemical{},
eng_noun:teratoid{},
eng_noun:hysteric{},
eng_noun:flagellate{},
eng_noun:futanari{},
eng_noun:sympathizer{},
eng_noun:one - shot{},
eng_noun:polypod{},
eng_noun:Westphalian{},
eng_noun:bimetallist{},
eng_noun:deterrent{},
eng_noun:hair - trigger{},
eng_noun:uninjured{},
eng_noun:expressionist{},
eng_noun:neuroleptic{},
eng_noun:sandgrounder{},
eng_noun:dropdown{},
eng_noun:commemorative{},
eng_noun:comestible{},
eng_noun:delphine{},
eng_noun:somatroph{},
eng_noun:agentive{},
eng_noun:usufructuary{},
eng_noun:briny{},
eng_noun:opaline{},
eng_noun:recreant{},
eng_noun:cartooney{},
eng_noun:protectionist{},
eng_noun:objectivist{},
eng_noun:Circassian{},
eng_noun:unresponsive{},
eng_noun:nutzoid{},
eng_noun:invitational{},
eng_noun:tetradecimal{},
eng_noun:cosignatory{},
eng_noun:hexapod{},
eng_noun:instakill{},
eng_noun:streetcorner{},
eng_noun:polyfluoro{},
eng_noun:unprintable{},
eng_noun:classist{},
eng_noun:Rexist{},
eng_noun:tricorn{},
eng_noun:Laestrygonian{},
eng_noun:federalist{},
eng_noun:singalong{},
eng_noun:pachycaul{},
eng_noun:foldout{},
eng_noun:polyplacophore{},
eng_noun:Genevan{},
eng_noun:nonsectarian{},
eng_noun:hegemonist{},
eng_noun:declaratory{},
eng_noun:prelim{},
eng_noun:nutbar{},
eng_noun:drip - dry{},
eng_noun:Rhodian{},
eng_noun:Czechoslovakian{},
eng_noun:maxillary{},
eng_noun:Lapp{},
eng_noun:Anglo - american{},
eng_noun:roan{},
eng_noun:immunosuppressant{},
eng_noun:hermeneutic{},
eng_noun:quadral{},
eng_noun:metapodial{},
eng_noun:protoctistan{},
eng_noun:penitant{},
eng_noun:bandpass{},
eng_noun:Kantean{},
eng_noun:dirigist{},
eng_noun:incuse{},
eng_noun:liberticide{},
eng_noun:Zapotec{},
eng_noun:Kievan{},
eng_noun:Missourian{},
eng_noun:intercity{},
eng_noun:underfloor{},
eng_noun:antient{},
eng_noun:trimotor{},
eng_noun:intervenient{},
eng_noun:Anatolian{},
eng_noun:cestode{},
eng_noun:antitranspirant{},
eng_noun:alleviative{},
eng_noun:fav{},
eng_noun:pooer{},
eng_noun:aminomethyl{},
eng_noun:Jacobean{},
eng_noun:extinguishant{},
eng_noun:Mesopotamian{},
eng_noun:Lancastrian{},
eng_noun:nonchemical{},
eng_noun:antimuscarinic{},
eng_noun:biquadratic{},
eng_noun:sudorific{},
eng_noun:Euro - skeptic{},
eng_noun:prog{},
eng_noun:bowery{},
eng_noun:topgallant{},
eng_noun:coralline{},
eng_noun:bivariate{},
eng_noun:camelback{},
eng_noun:decrescent{},
eng_noun:excitant{},
eng_noun:Brayon{},
eng_noun:white - shoe{},
eng_noun:Ephesian{},
eng_noun:sheepy{},
eng_noun:Swati{},
eng_noun:oppugnant{},
eng_noun:Louisianian{},
eng_noun:nonterminal{},
eng_noun:Sacramentarian{},
eng_noun:glomalean{},
eng_noun:plathelminth{},
eng_noun:siboglinid{},
eng_noun:lissamphibian{},
eng_noun:sulphoaluminate{},
eng_noun:fastigiate{},
eng_noun:determinist{},
eng_noun:quincentenary{},
eng_noun:quadratojugal{},
eng_noun:Pitcairner{},
eng_noun:wah - wah{},
eng_noun:permeant{},
eng_noun:Istrian{},
eng_noun:prediagnosis{},
eng_noun:ingressive{},
eng_noun:patientive{},
eng_noun:anarcho - syndicalist{},
eng_noun:bayfront{},
eng_noun:wackadoo{},
eng_noun:superspecial{},
eng_noun:midrise{},
eng_noun:nonsecret{},
eng_noun:spectralist{},
eng_noun:nonsenior{},
eng_noun:communitarian{},
eng_noun:nonlocal{},
eng_noun:Maduran{},
eng_noun:ultraliberal{},
eng_noun:multidisciplinarian{},
eng_noun:nonstudent{},
eng_noun:parachordal{},
eng_noun:Sartrean{},
eng_noun:mainstage{},
eng_noun:eliminativist{},
eng_noun:bicoastal{},
eng_noun:nongame{},
eng_noun:biconditional{},
eng_noun:nonhistone{},
eng_noun:multistorey{},
eng_noun:sandbelt{},
eng_noun:interdune{},
eng_noun:antiracism{},
eng_noun:expressivist{},
eng_noun:immunoabsorbent{},
eng_noun:anticipant{},
eng_noun:postintegration{},
eng_noun:reductivist{},
eng_noun:midcalf{},
eng_noun:subadult{},
eng_noun:bolshy{},
eng_noun:antispasmatic{},
eng_noun:Manhattanite{},
eng_noun:lobstery{},
eng_noun:Springfieldian{},
eng_noun:betamimetic{},
eng_noun:Cincinnatian{},
eng_noun:Mascarene{},
eng_noun:assessorial{},
eng_noun:antigalactic{},
eng_noun:precapitalist{},
eng_noun:prestudy{},
eng_noun:nondepressive{},
eng_noun:antihelminthic{},
eng_noun:surform{},
eng_noun:Bratislavan{},
eng_noun:Delhian{},
eng_noun:nonmale{},
eng_noun:multitheist{},
eng_noun:Turkoman{},
eng_noun:Tajikistani{},
eng_noun:speciesist{},
eng_noun:Balaamite{},
eng_noun:nonanesthetic{},
eng_noun:anticestodal{},
eng_noun:hydrocholeretic{},
eng_noun:catastrophist{},
eng_noun:Antwerpian{},
eng_noun:post - apocalyptic{},
eng_noun:carryon{},
eng_noun:pracademic{},
eng_noun:jabberwocky{},
eng_noun:nonsedative{},
eng_noun:nonpollen{},
eng_noun:preinflation{},
eng_noun:anthro{},
eng_noun:selenomethionyl{},
eng_noun:nonceramic{},
eng_noun:ersatzist{},
eng_noun:nontangible{},
eng_noun:nonrevolutionary{},
eng_noun:nonvisionary{},
eng_noun:nonwestern{},
eng_noun:nonequalitarian{},
eng_noun:multigrade{},
eng_noun:nondrug{},
eng_noun:preprofessional{},
eng_noun:nonantique{},
eng_noun:nonedible{},
eng_noun:semiclassic{},
eng_noun:syrphian{},
eng_noun:palaeoconservative{},
eng_noun:macrorealist{},
eng_noun:rakehell{},
eng_noun:triggery{},
eng_noun:hepatotoxicant{},
eng_noun:Keresan{},
eng_noun:nontaxation{},
eng_noun:biflagellate{},
eng_noun:nonphobic{},
eng_noun:Hellenophile{},
eng_noun:Hibernophile{},
eng_noun:ghosty{},
eng_noun:viverrine{},
eng_noun:tipulid{},
eng_noun:Urartean{},
eng_noun:nonlabial{},
eng_noun:specieist{},
eng_noun:antimicrobic{},
eng_noun:multi - touch{},
eng_noun:megapolitan{},
eng_noun:Blackpudlian{},
eng_noun:Aostan{},
eng_noun:abortient{},
eng_noun:salmonoid{},
eng_noun:nongoal{},
eng_noun:winky{},
eng_noun:Nestorian{},
eng_noun:circumbendibus{},
eng_noun:nonrevisionist{},
eng_noun:mornay{},
eng_noun:serotine{},
eng_noun:interester{},
eng_noun:disestablishmentarian{},
eng_noun:exessive{},
eng_noun:antirevolutionary{},
eng_noun:unshrinkable{},
eng_noun:bardie{},
eng_noun:pure - bred{},
eng_noun:strippy{},
eng_noun:Azorean{},
eng_noun:Erasmian{},
eng_noun:oorie{},
eng_noun:Cappadocian{},
eng_noun:Saragossan{},
eng_noun:Malagan{},
eng_noun:Volscian{},
eng_noun:Callistan{},
eng_noun:lunary{},
eng_noun:pedosexual{},
eng_noun:Montessorian{},
eng_noun:non - paper{},
eng_noun:Tatarian{},
eng_noun:deltoideus{},
eng_noun:anticollectivist{},
eng_noun:deconstructivist{},
eng_noun:creekside{},
eng_noun:nonevangelical{},
eng_noun:cestoid{},
eng_noun:Rothbardian{},
eng_noun:Monrovian{},
eng_noun:Danubian{},
eng_noun:naticoid{},
eng_noun:labrish{},
eng_noun:quintate{},
eng_noun:sextate{},
eng_noun:miscome{},
eng_noun:antiallergenic{},
eng_noun:schizophreniac{},
eng_noun:productivist{},
eng_noun:academick{},
eng_noun:multicycle{},
eng_noun:specifick{},
eng_noun:prognostick{},
eng_noun:cynick{},
eng_noun:hypochondriack{},
eng_noun:macaronick{},
eng_noun:narcotick{},
eng_noun:nephritick{},
eng_noun:optick{},
eng_noun:patronymick{},
eng_noun:schismatick{},
eng_noun:Armorican{},
eng_noun:telepsychic{},
eng_noun:antizymotic{},
eng_noun:gremial{},
eng_noun:tingid{},
eng_noun:appurtenaunt{},
eng_noun:attendaunt{},
eng_noun:Ceylonese{},
eng_noun:mightand{},
eng_noun:Limenean{},
eng_noun:haustellate{},
eng_noun:deodourant{},
eng_noun:armourial{},
eng_noun:subterrany{},
eng_noun:interopercular{},
eng_noun:craftable{},
eng_noun:non - op{},
eng_noun:ctenoidean{},
eng_noun:evenold{},
eng_noun:left{},
eng_noun:stern{},
eng_noun:bicentenary{},
eng_noun:catoptric{},
eng_noun:caucasian{},
eng_noun:discontent{},
eng_noun:downhill{},
eng_noun:desert{},
eng_noun:decongestant{},
eng_noun:devonian{},
eng_noun:dialectic{},
eng_noun:ferroconcrete{},
eng_noun:fibroid{},
eng_noun:hardback{},
eng_noun:hotshot{},
eng_noun:jain{},
eng_noun:litigant{},
eng_noun:mod{},
eng_noun:patent{},
eng_noun:pet{},
eng_noun:paramilitary{},
eng_noun:pongid{},
eng_noun:pyknic{},
eng_noun:pyroelectric{},
eng_noun:ratite{},
eng_noun:recessional{},
eng_noun:roughcast{},
eng_noun:savoyard{},
eng_noun:sceptic{},
eng_noun:still{},
eng_noun:tantivy{},
eng_noun:terry{},
eng_noun:tetrastyle{},
eng_noun:thermophile{},
eng_noun:transgenic{},
eng_noun:auvergnese{},
eng_noun:koepanger{},
eng_noun:xian{},
eng_noun:nappy{},
eng_noun:armorial{},
eng_noun:excrescent{},
eng_noun:ware{},
eng_noun:sitfast{},
eng_noun:seater{},
eng_noun:uphill{},
eng_noun:upward{},
eng_noun:lookup{},
eng_noun:alumina{},
eng_noun:poverty{},
eng_noun:homebrew{},
eng_noun:disjunct{},
eng_noun:tailwheel{},
eng_noun:centennial{},
eng_noun:subordinate{},
eng_noun:buttery{},
eng_noun:afghani{},
eng_noun:round{},
eng_noun:cursive{},
eng_noun:pro{},
eng_noun:tender{},
eng_noun:rundown{},
eng_noun:ringworm{},
eng_noun:chiffon{},
eng_noun:malapert{},
eng_noun:brow{},
eng_noun:ruby{},
eng_noun:pizzicato{},
eng_noun:blanc{},
eng_noun:low{},
eng_noun:wikipedian{},
eng_noun:usonian{},
eng_noun:midterm{},
eng_noun:interlock{},
eng_noun:arachnid{},
eng_noun:auditory{},
eng_noun:gilt{},
eng_noun:closing{},
eng_noun:binding{},
eng_noun:cutting{},
eng_noun:filling{},
eng_noun:flowering{},
eng_noun:wandering{},
eng_noun:backing{},
eng_noun:walking{},
eng_noun:sightseeing{},
eng_noun:exhilarating{},
eng_noun:watering{},
eng_noun:raving{},
eng_noun:conjugate{},
eng_noun:content{},
eng_noun:overcast{},
eng_noun:standardbred{},
eng_noun:substantive{},
eng_noun:abirritant{},
eng_noun:abrasive{},
eng_noun:abrogate{},
eng_noun:birth{},
eng_noun:secret{},
eng_noun:standard{},
eng_noun:Catalan{},
eng_noun:banana{},
eng_noun:beige{},
eng_noun:violet{},
eng_noun:young{},
eng_noun:dative{},
eng_noun:superlative{},
eng_noun:southwest{},
eng_noun:quaint{},
eng_noun:female{},
eng_noun:tin{},
eng_noun:slate{},
eng_noun:vermilion{},
eng_noun:strawberry{},
eng_noun:lemon{},
eng_noun:safe{},
eng_noun:vernacular{},
eng_noun:gibberish{},
eng_noun:Canadian{},
eng_noun:Bulgarian{},
eng_noun:ilk{},
eng_noun:funeral{},
eng_noun:interior{},
eng_noun:bourgeois{},
eng_noun:vertebrate{},
eng_noun:sovereign{},
eng_noun:solid{},
eng_noun:smooth{},
eng_noun:celestial{},
eng_noun:ebb{},
eng_noun:Anguillan{},
eng_noun:Corsican{},
eng_noun:queer{},
eng_noun:nazi{},
eng_noun:void{},
eng_noun:Ashkenazi{},
eng_noun:arsenic{},
eng_noun:terminal{},
eng_noun:Persian{},
eng_noun:Philistine{},
eng_noun:laureate{},
eng_noun:laudative{},
eng_noun:acescent{},
eng_noun:wholesale{},
eng_noun:nice{},
eng_noun:primary{},
eng_noun:Aragonese{},
eng_noun:Belarusian{},
eng_noun:Sudanese{},
eng_noun:Palestinian{},
eng_noun:Kazakh{},
eng_noun:Burundian{},
eng_noun:Uruguayan{},
eng_noun:Vanuatuan{},
eng_noun:Malian{},
eng_noun:Turkmen{},
eng_noun:Namibian{},
eng_noun:Comorian{},
eng_noun:Viennese{},
eng_noun:Ghanaian{},
eng_noun:Laotian{},
eng_noun:Omani{},
eng_noun:Constantinopolitan{},
eng_noun:signal{},
eng_noun:ambisexual{},
eng_noun:Friulian{},
eng_noun:front{},
eng_noun:pirate{},
eng_noun:tricentennial{},
eng_noun:Bengali{},
eng_noun:Marathi{},
eng_noun:Sinhalese{},
eng_noun:trunk{},
eng_noun:series{},
eng_noun:anal{},
eng_noun:vain{},
eng_noun:marine{},
eng_noun:socialist{},
eng_noun:biannual{},
eng_noun:glottal{},
eng_noun:visionary{},
eng_noun:Polynesian{},
eng_noun:eutectic{},
eng_noun:alpine{},
eng_noun:amateur{},
eng_noun:private{},
eng_noun:Malay{},
eng_noun:heretic{},
eng_noun:choice{},
eng_noun:flatbed{},
eng_noun:Arminian{},
eng_noun:elastic{},
eng_noun:lieutenant{},
eng_noun:bottom{},
eng_noun:feral{},
eng_noun:shotgun{},
eng_noun:moderato{},
eng_noun:diminuendo{},
eng_noun:quicksilver{},
eng_noun:tenor{},
eng_noun:chivalrous{},
eng_noun:albino{},
eng_noun:boilerplate{},
eng_noun:Bosnian{},
eng_noun:elect{},
eng_noun:exclusive{},
eng_noun:gentile{},
eng_noun:octic{},
eng_noun:picayune{},
eng_noun:aculeate{},
eng_noun:agglutinant{},
eng_noun:Aventine{},
eng_noun:Paki{},
eng_noun:jammy{},
eng_noun:necessary{},
eng_noun:proof{},
eng_noun:halcyon{},
eng_noun:integral{},
eng_noun:mundane{},
eng_noun:fuzzy{},
eng_noun:floppy{},
eng_noun:immutable{},
eng_noun:Aryan{},
eng_noun:terrorist{},
eng_noun:mordant{},
eng_noun:straw{},
eng_noun:stereo{},
eng_noun:tattletale{},
eng_noun:Aramaic{},
eng_noun:Nepali{},
eng_noun:export{},
eng_noun:sport{},
eng_noun:insurgent{},
eng_noun:coronary{},
eng_noun:inflatable{},
eng_noun:damask{},
eng_noun:prodigal{},
eng_noun:passionate{},
eng_noun:amino{},
eng_noun:bawdy{},
eng_noun:chic{},
eng_noun:chuff{},
eng_noun:nubile{},
eng_noun:berserk{},
eng_noun:blithe{},
eng_noun:brute{},
eng_noun:canny{},
eng_noun:compulsory{},
eng_noun:elite{},
eng_noun:official{},
eng_noun:punk{},
eng_noun:scrimp{},
eng_noun:sleek{},
eng_noun:sleigh{},
eng_noun:solitary{},
eng_noun:stuffy{},
eng_noun:tentative{},
eng_noun:ingrate{},
eng_noun:bacchanal{},
eng_noun:Mancunian{},
eng_noun:suede{},
eng_noun:mid - september{},
eng_noun:mid - january{},
eng_noun:terrestrial{},
eng_noun:negative{},
eng_noun:invariant{},
eng_noun:equivalent{},
eng_noun:antitussive{},
eng_noun:charter{},
eng_noun:rum{},
eng_noun:skim{},
eng_noun:ungulate{},
eng_noun:octogenarian{},
eng_noun:zigzag{},
eng_noun:filk{},
eng_noun:premium{},
eng_noun:miscreant{},
eng_noun:subarctic{},
eng_noun:pansy{},
eng_noun:tertiary{},
eng_noun:pissant{},
eng_noun:randy{},
eng_noun:twin{},
eng_noun:pre - adamite{},
eng_noun:unconventional{},
eng_noun:maverick{},
eng_noun:acrocephalic{},
eng_noun:voluntary{},
eng_noun:Zionist{},
eng_noun:junky{},
eng_noun:ecstatic{},
eng_noun:polyester{},
eng_noun:oneirocritic{},
eng_noun:anodyne{},
eng_noun:inorganic{},
eng_noun:merry{},
eng_noun:prat{},
eng_noun:oxyacetylene{},
eng_noun:Chuvash{},
eng_noun:cactus{},
eng_noun:ascetic{},
eng_noun:Whovian{},
eng_noun:decubitis{},
eng_noun:varietal{},
eng_noun:tawny{},
eng_noun:backup{},
eng_noun:laxative{},
eng_noun:consistent{},
eng_noun:stopgap{},
eng_noun:veggie{},
eng_noun:incoherent{},
eng_noun:dependant{},
eng_noun:nightly{},
eng_noun:polyzoic{},
eng_noun:transitionist{},
eng_noun:profane{},
eng_noun:primo{},
eng_noun:identikit{},
eng_noun:legislative{},
eng_noun:crummy{},
eng_noun:creo{},
eng_noun:columnar{},
eng_noun:straightedge{},
eng_noun:hallucinogenic{},
eng_noun:deponent{},
eng_noun:danophone{},
eng_noun:convertible{},
eng_noun:budget{},
eng_noun:Guadalupian{},
eng_noun:Furongian{},
eng_noun:durable{},
eng_noun:slick{},
eng_noun:burgundy{},
eng_noun:eggshell{},
eng_noun:Herzegovinian{},
eng_noun:sociolinguistic{},
eng_noun:attendant{},
eng_noun:cupreous{},
eng_noun:trim{},
eng_noun:antibacterial{},
eng_noun:idyllic{},
eng_noun:ginge{},
eng_noun:Croat{},
eng_noun:sorrel{},
eng_noun:nitro{},
eng_noun:Democrat{},
eng_noun:Latino{},
eng_noun:Tuscan{},
eng_noun:tarsal{},
eng_noun:didactyl{},
eng_noun:constituent{},
eng_noun:Mesolithic{},
eng_noun:duodecimal{},
eng_noun:abram{},
eng_noun:tercentenary{},
eng_noun:symbiotic{},
eng_noun:semidocumentary{},
eng_noun:scurvy{},
eng_noun:anticoagulant{},
eng_noun:bioterrorist{},
eng_noun:antarthritic{},
eng_noun:loony{},
eng_noun:Arabian{},
eng_noun:diploid{},
eng_noun:cardioid{},
eng_noun:tubby{},
eng_noun:Zoroastrian{},
eng_noun:interrogatory{},
eng_noun:annelid{},
eng_noun:parasitic{},
eng_noun:conglomerate{},
eng_noun:directive{},
eng_noun:antiperiodic{},
eng_noun:rapier{},
eng_noun:diazo{},
eng_noun:crisscross{},
eng_noun:all - american{},
eng_noun:bake - off{},
eng_noun:ungenerous{},
eng_noun:Extremaduran{},
eng_noun:empyrean{},
eng_noun:uncopyrightable{},
eng_noun:gorgon{},
eng_noun:purebred{},
eng_noun:preventive{},
eng_noun:polyploid{},
eng_noun:lippy{},
eng_noun:deltoid{},
eng_noun:saline{},
eng_noun:antasthmatic{},
eng_noun:prerogative{},
eng_noun:stormy{},
eng_noun:vulcanoid{},
eng_noun:inessive{},
eng_noun:bipartisan{},
eng_noun:spotty{},
eng_noun:three - quarter{},
eng_noun:fire - retardant{},
eng_noun:psychedelic{},
eng_noun:bellicist{},
eng_noun:Minorcan{},
eng_noun:trumpery{},
eng_noun:revanchist{},
eng_noun:triennial{},
eng_noun:manipulative{},
eng_noun:throw - away{},
eng_noun:Tchaikovskian{},
eng_noun:top - up{},
eng_noun:niggard{},
eng_noun:wind - up{},
eng_noun:chemic{},
eng_noun:radial{},
eng_noun:biologic{},
eng_noun:macaronic{},
eng_noun:voyeurist{},
eng_noun:Molossian{},
eng_noun:polemical{},
eng_noun:schizophrenic{},
eng_noun:preteen{},
eng_noun:upfront{},
eng_noun:putty{},
eng_noun:nosey{},
eng_noun:cretic{},
eng_noun:imperialist{},
eng_noun:Kampuchean{},
eng_noun:leftist{},
eng_noun:toxophilite{},
eng_noun:rollercoaster{},
eng_noun:teratogenic{},
eng_noun:prepositive{},
eng_noun:retromingent{},
eng_noun:longhair{},
eng_noun:roadside{},
eng_noun:duotrigintillionth{},
eng_noun:elegiack{},
eng_noun:phthisick{},
eng_noun:preconsent{},
eng_noun:Etrurian{},
eng_noun:loppard{},
eng_noun:Eusebian{},
eng_noun:falwe{},
eng_noun:Deweyan{},
eng_noun:methylic{},
eng_noun:multinumber{},
eng_noun:predelinquent{},
eng_noun:dentilabial{},
eng_noun:minour{},
eng_noun:supraoccipital{},
eng_noun:peripatetick{},
eng_noun:honourific{},
eng_noun:antidysenteric{},
eng_noun:scholastical{},
eng_noun:return{},
eng_noun:anuran{},
eng_noun:convulsant{},
eng_noun:detective{},
eng_noun:determinant{},
eng_noun:duff{},
eng_noun:fairy{},
eng_noun:farrago{},
eng_noun:fugitive{},
eng_noun:fun{},
eng_noun:forfeit{},
eng_noun:fustian{},
eng_noun:husky{},
eng_noun:inexperience{},
eng_noun:morisco{},
eng_noun:moline{},
eng_noun:monoacid{},
eng_noun:orthopteran{},
eng_noun:muzzy{},
eng_noun:nomad{},
eng_noun:nancy{},
eng_noun:olympian{},
eng_noun:pasty{},
eng_noun:proponent{},
eng_noun:rebel{},
eng_noun:rosy{},
eng_noun:rubato{},
eng_noun:schismatic{},
eng_noun:schizo{},
eng_noun:sound{},
eng_noun:siccative{},
eng_noun:substitute{},
eng_noun:unitary{},
eng_noun:typhoid{},
eng_noun:topical{},
eng_noun:windy{},
eng_noun:abstract{},
eng_noun:augustinian{},
eng_noun:calymmian{},
eng_noun:indo - aryan{},
eng_noun:patavine{},
eng_noun:hawk{},
eng_noun:mole{},
eng_noun:pixy{},
eng_noun:callow{},
eng_noun:scholar{},
eng_noun:counterfactual{},
eng_noun:gay{},
eng_noun:max{},
eng_noun:bound{},
eng_noun:frost{},
eng_noun:clitic{},
eng_noun:oolong{},
eng_noun:raster{},
eng_noun:colonic{},
eng_noun:coronal{},
eng_noun:proline{},
eng_noun:wearable{},
eng_noun:parkland{},
eng_noun:crosshead{},
eng_noun:screwball{},
eng_noun:sublimate{},
eng_noun:nearshore{},
eng_noun:hydrolase{},
eng_noun:portugese{},
eng_noun:harbourside{},
eng_noun:preproduction{},
eng_noun:wan{},
eng_noun:triceps{},
eng_noun:deface{},
eng_noun:ginger{},
eng_noun:august{},
eng_noun:hotfoot{},
eng_noun:notable{},
eng_noun:bass{},
eng_noun:kong{},
eng_noun:sonorant{},
eng_noun:candy{},
eng_noun:mute{},
eng_noun:base{},
eng_noun:fat{},
eng_noun:underwater{},
eng_noun:adjuvant{},
eng_noun:hyperbole{},
eng_noun:baritone{},
eng_noun:proclitic{},
eng_noun:airspace{},
eng_noun:chiropractic{},
eng_noun:crossing{},
eng_noun:something{},
eng_noun:heating{},
eng_noun:fledgling{},
eng_noun:understanding{},
eng_noun:serving{},
eng_noun:burning{},
eng_noun:vaulting{},
eng_noun:facing{},
eng_noun:sitting{},
eng_noun:unwitting{},
eng_noun:spanking{},
eng_noun:heaving{},
eng_noun:present{},
eng_noun:abdominal{},
eng_noun:aberrant{},
eng_noun:aboriginal{},
eng_noun:acanthopterygian{},
eng_noun:accidental{},
eng_noun:accordion{},
eng_noun:acid{},
eng_noun:quality{},
eng_noun:qualitative{},
eng_noun:woodwind{},
eng_noun:epizootic{},
eng_noun:now{},
eng_noun:Portuguese{},
eng_noun:accountant{},
eng_noun:grey{},
eng_noun:Saxon{},
eng_noun:Turkish{},
eng_noun:Slovak{},
eng_noun:Hungarian{},
eng_noun:Czech{},
eng_noun:Thai{},
eng_noun:Afrikaans{},
eng_noun:chartreuse{},
eng_noun:monthly{},
eng_noun:navy{},
eng_noun:bronze{},
eng_noun:tangerine{},
eng_noun:sapphire{},
eng_noun:chestnut{},
eng_noun:capital{},
eng_noun:Basque{},
eng_noun:comic{},
eng_noun:aesthetic{},
eng_noun:fluid{},
eng_noun:American{},
eng_noun:Andorran{},
eng_noun:adult{},
eng_noun:Hispanic{},
eng_noun:additive{},
eng_noun:classic{},
eng_noun:null{},
eng_noun:daily{},
eng_noun:cubic{},
eng_noun:argentine{},
eng_noun:manifest{},
eng_noun:android{},
eng_noun:almond{},
eng_noun:Latvian{},
eng_noun:Bhutanese{},
eng_noun:Paraguayan{},
eng_noun:Kenyan{},
eng_noun:Gambian{},
eng_noun:Zambian{},
eng_noun:Bruneian{},
eng_noun:Tongan{},
eng_noun:Euboean{},
eng_noun:Guadeloupean{},
eng_noun:Salvadorian{},
eng_noun:Martinican{},
eng_noun:Reunionese{},
eng_noun:Rwandese{},
eng_noun:Somali{},
eng_noun:Bermudian{},
eng_noun:sabbatical{},
eng_noun:knockout{},
eng_noun:shiny{},
eng_noun:ape{},
eng_noun:Achaian{},
eng_noun:Anglophone{},
eng_noun:trust{},
eng_noun:ghetto{},
eng_noun:millennial{},
eng_noun:Tamil{},
eng_noun:Panjabi{},
eng_noun:aerial{},
eng_noun:hippie{},
eng_noun:ethnic{},
eng_noun:Aberdonian{},
eng_noun:ultracrepidarian{},
eng_noun:advance{},
eng_noun:chattel{},
eng_noun:tangible{},
eng_noun:overall{},
eng_noun:alterative{},
eng_noun:ugly{},
eng_noun:antic{},
eng_noun:binary{},
eng_noun:quadriliteral{},
eng_noun:xenophobic{},
eng_noun:alcoholic{},
eng_noun:wanton{},
eng_noun:augmentative{},
eng_noun:flexitarian{},
eng_noun:cognate{},
eng_noun:spruce{},
eng_noun:duplex{},
eng_noun:transversal{},
eng_noun:fade{},
eng_noun:noir{},
eng_noun:hippy{},
eng_noun:discriminant{},
eng_noun:fancy{},
eng_noun:marsupial{},
eng_noun:Arab{},
eng_noun:intestate{},
eng_noun:intramural{},
eng_noun:underground{},
eng_noun:latest{},
eng_noun:collectible{},
eng_noun:statist{},
eng_noun:velopharyngeal{},
eng_noun:flexible{},
eng_noun:master{},
eng_noun:enzootic{},
eng_noun:nippy{},
eng_noun:TWOC{},
eng_noun:cutaway{},
eng_noun:Scouse{},
eng_noun:hebrephrenic{},
eng_noun:fanatic{},
eng_noun:gala{},
eng_noun:medial{},
eng_noun:tensor{},
eng_noun:unary{},
eng_noun:contingent{},
eng_noun:fundamental{},
eng_noun:intellectual{},
eng_noun:peripatetic{},
eng_noun:potential{},
eng_noun:primitive{},
eng_noun:starch{},
eng_noun:stout{},
eng_noun:caustic{},
eng_noun:udal{},
eng_noun:phony{},
eng_noun:concordant{},
eng_noun:mid - july{},
eng_noun:midsummer{},
eng_noun:negroid{},
eng_noun:Mohammedan{},
eng_noun:chameleon{},
eng_noun:transient{},
eng_noun:broody{},
eng_noun:rookie{},
eng_noun:consanguineous{},
eng_noun:daredevil{},
eng_noun:brunette{},
eng_noun:indigent{},
eng_noun:inert{},
eng_noun:posterior{},
eng_noun:culinary{},
eng_noun:clamshell{},
eng_noun:columbine{},
eng_noun:plush{},
eng_noun:petunia{},
eng_noun:silent{},
eng_noun:demographic{},
eng_noun:previous{},
eng_noun:collaborative{},
eng_noun:journal{},
eng_noun:gossamer{},
eng_noun:snub{},
eng_noun:armchair{},
eng_noun:upright{},
eng_noun:monotone{},
eng_noun:insectoid{},
eng_noun:nonagenarian{},
eng_noun:federal{},
eng_noun:chill{},
eng_noun:diabetic{},
eng_noun:projectile{},
eng_noun:synthetic{},
eng_noun:one - to - one{},
eng_noun:Glaswegian{},
eng_noun:heterodyne{},
eng_noun:visual{},
eng_noun:heteropod{},
eng_noun:Whitsun{},
eng_noun:Samian{},
eng_noun:apolitical{},
eng_noun:flannel{},
eng_noun:taboo{},
eng_noun:pally{},
eng_noun:multiplex{},
eng_noun:guilty{},
eng_noun:outpatient{},
eng_noun:ith{},
eng_noun:erratic{},
eng_noun:crystalline{},
eng_noun:impromptu{},
eng_noun:haywire{},
eng_noun:crusty{},
eng_noun:vintage{},
eng_noun:airborne{},
eng_noun:brahmin{},
eng_noun:contraceptive{},
eng_noun:backhand{},
eng_noun:whiff{},
eng_noun:mainstream{},
eng_noun:bravura{},
eng_noun:adipose{},
eng_noun:overnight{},
eng_noun:inanimate{},
eng_noun:ultra{},
eng_noun:parental{},
eng_noun:flush{},
eng_noun:coo{},
eng_noun:yogi{},
eng_noun:deliverable{},
eng_noun:ballpark{},
eng_noun:scenic{},
eng_noun:pavonine{},
eng_noun:Eocene{},
eng_noun:dainty{},
eng_noun:cellular{},
eng_noun:cuttie{},
eng_noun:libertine{},
eng_noun:residual{},
eng_noun:singulative{},
eng_noun:back - up{},
eng_noun:oxblood{},
eng_noun:Guinean{},
eng_noun:hamate{},
eng_noun:Himalayan{},
eng_noun:Proctor{},
eng_noun:Wiccan{},
eng_noun:collegiate{},
eng_noun:vertebral{},
eng_noun:chemotherapeutic{},
eng_noun:pituitary{},
eng_noun:Gurkha{},
eng_noun:Sunni{},
eng_noun:go - ahead{},
eng_noun:kalua{},
eng_noun:semi - automatic{},
eng_noun:microcephalic{},
eng_noun:taxable{},
eng_noun:palliative{},
eng_noun:anticorrosive{},
eng_noun:antimodernist{},
eng_noun:elliptical{},
eng_noun:coeliac{},
eng_noun:endocrine{},
eng_noun:plump{},
eng_noun:chelate{},
eng_noun:centenary{},
eng_noun:Zwinglian{},
eng_noun:deadbeat{},
eng_noun:sentient{},
eng_noun:antimicrobial{},
eng_noun:antipsychotic{},
eng_noun:correlative{},
eng_noun:passerine{},
eng_noun:didactic{},
eng_noun:alkaline{},
eng_noun:no - name{},
eng_noun:saccharine{},
eng_noun:fraught{},
eng_noun:letterbox{},
eng_noun:windup{},
eng_noun:matte{},
eng_noun:Nazarene{},
eng_noun:aspirant{},
eng_noun:oceanfront{},
eng_noun:resistant{},
eng_noun:dernier{},
eng_noun:chemopreventive{},
eng_noun:depressant{},
eng_noun:bantam{},
eng_noun:immigrant{},
eng_noun:masticatory{},
eng_noun:redwood{},
eng_noun:Delphic{},
eng_noun:Silesian{},
eng_noun:Pomeranian{},
eng_noun:anticatholic{},
eng_noun:Damocloid{},
eng_noun:propaedeutic{},
eng_noun:militant{},
eng_noun:scapular{},
eng_noun:flame - retardant{},
eng_noun:seesaw{},
eng_noun:Madrilenian{},
eng_noun:suzerain{},
eng_noun:unsalable{},
eng_noun:subaltern{},
eng_noun:rowdy{},
eng_noun:hoyden{},
eng_noun:propre{},
eng_noun:tortoiseshell{},
eng_noun:Shinto{},
eng_noun:Grecophone{},
eng_noun:harmonic{},
eng_noun:esthetic{},
eng_noun:irritant{},
eng_noun:Malayan{},
eng_noun:clathrate{},
eng_noun:diocesan{},
eng_noun:phenolic{},
eng_noun:Irani{},
eng_noun:cataleptic{},
eng_noun:titular{},
eng_noun:hectic{},
eng_noun:organoid{},
eng_noun:xiphosuran{},
eng_noun:proparoxytone{},
eng_noun:Minoan{},
eng_noun:curly{},
eng_noun:southeasterly{},
eng_noun:vesicant{},
eng_noun:midlife{},
eng_noun:workaholic{},
eng_noun:interactive{},
eng_noun:quintillionth{},
eng_noun:noetic{},
eng_noun:misty{},
eng_noun:styptic{},
eng_noun:chippy{},
eng_noun:upslope{},
eng_noun:plumbous{},
eng_noun:otalgic{},
eng_noun:minimalist{},
eng_noun:executable{},
eng_noun:duodecillionth{},
eng_noun:alterable{},
eng_noun:carbenoid{},
eng_noun:pictorial{},
eng_noun:locomotive{},
eng_noun:advisory{},
eng_noun:ashcan{},
eng_noun:telephoto{},
eng_noun:neorealist{},
eng_noun:Sumerian{},
eng_noun:mountaintop{},
eng_noun:jingoist{},
eng_noun:suffragan{},
eng_noun:Milanese{},
eng_noun:lachrymatory{},
eng_noun:pre - game{},
eng_noun:middlebrow{},
eng_noun:co - dependent{},
eng_noun:reverential{},
eng_noun:omnitheist{},
eng_noun:masculinist{},
eng_noun:anionic{},
eng_noun:eutrophic{},
eng_noun:trine{},
eng_noun:courtly{},
eng_noun:polysomic{},
eng_noun:anorectic{},
eng_noun:aphasic{},
eng_noun:bigeminal{},
eng_noun:biomedical{},
eng_noun:tetrapod{},
eng_noun:Belarusan{},
eng_noun:sexagenary{},
eng_noun:Benedictine{},
eng_noun:interstadial{},
eng_noun:Cestrian{},
eng_noun:triplex{},
eng_noun:raglan{},
eng_noun:univalve{},
eng_noun:subteen{},
eng_noun:subhuman{},
eng_noun:dilly{},
eng_noun:postern{},
eng_noun:inessential{},
eng_noun:Coptic{},
eng_noun:copyrightable{},
eng_noun:nymphomanic{},
eng_noun:congregationalist{},
eng_noun:pentadecimal{},
eng_noun:Mensan{},
eng_noun:triumphalist{},
eng_noun:hardline{},
eng_noun:performative{},
eng_noun:ever - present{},
eng_noun:Skinnerian{},
eng_noun:Manitoban{},
eng_noun:grandioso{},
eng_noun:percipient{},
eng_noun:appellative{},
eng_noun:ceratopsian{},
eng_noun:close - up{},
eng_noun:Miwokan{},
eng_noun:retardant{},
eng_noun:aversive{},
eng_noun:nonnegotiable{},
eng_noun:cash - flow{},
eng_noun:drystone{},
eng_noun:metamict{},
eng_noun:platinoid{},
eng_noun:indigene{},
eng_noun:three - ply{},
eng_noun:minikin{},
eng_noun:Formosan{},
eng_noun:indiscernible{},
eng_noun:crypto - fascist{},
eng_noun:Kantian{},
eng_noun:Tocharian{},
eng_noun:mentalist{},
eng_noun:Pahari{},
eng_noun:ready - made{},
eng_noun:mesoscale{},
eng_noun:innumerate{},
eng_noun:internationalist{},
eng_noun:adjunctive{},
eng_noun:volitive{},
eng_noun:transmembrane{},
eng_noun:odorant{},
eng_noun:allelochemical{},
eng_noun:cubozoan{},
eng_noun:intershell{},
eng_noun:nonrenewable{},
eng_noun:constat{},
eng_noun:antifeedant{},
eng_noun:revisionist{},
eng_noun:nonbelligerent{},
eng_noun:injectable{},
eng_noun:frontline{},
eng_noun:goodwife{},
eng_noun:nonhuman{},
eng_noun:Arizonan{},
eng_noun:nonmilitant{},
eng_noun:gazillionth{},
eng_noun:shadowless{},
eng_noun:abortogenic{},
eng_noun:fireward{},
eng_noun:quadrinomial{},
eng_noun:placeable{},
eng_noun:amoeboid{},
eng_noun:analeptic{},
eng_noun:Kosovar{},
eng_noun:antipain{},
eng_noun:Almain{},
eng_noun:multichannel{},
eng_noun:coorse{},
eng_noun:Manzonian{},
eng_noun:penetrant{},
eng_noun:bdelloid{},
eng_noun:antinicotinic{},
eng_noun:lew{},
eng_noun:saluretic{},
eng_noun:antifolate{},
eng_noun:renunciant{},
eng_noun:halfwidth{},
eng_noun:hawse{},
eng_noun:febricitant{},
eng_noun:Kyivan{},
eng_noun:interlayer{},
eng_noun:noninteger{},
eng_noun:organomercurial{},
eng_noun:smoothbore{},
eng_noun:superrich{},
eng_noun:Muhammadan{},
eng_noun:coacervate{},
eng_noun:multienzyme{},
eng_noun:trinary{},
eng_noun:macroeconomic{},
eng_noun:scopophiliac{},
eng_noun:Buriat{},
eng_noun:calefacient{},
eng_noun:Kazakhstani{},
eng_noun:Colossian{},
eng_noun:Salesian{},
eng_noun:nonstaple{},
eng_noun:Astroturf{},
eng_noun:consequentialist{},
eng_noun:Vincentian{},
eng_noun:non - terminal{},
eng_noun:descriptivist{},
eng_noun:Capricornian{},
eng_noun:Virgoan{},
eng_noun:Taurean{},
eng_noun:Leonian{},
eng_noun:saurischian{},
eng_noun:notoungulate{},
eng_noun:hench{},
eng_noun:unquantifiable{},
eng_noun:hysteroid{},
eng_noun:Hispanian{},
eng_noun:septothecal{},
eng_noun:eevn{},
eng_noun:half - width{},
eng_noun:cyberfeminist{},
eng_noun:tusky{},
eng_noun:ecumenist{},
eng_noun:salmonid{},
eng_noun:postsectarian{},
eng_noun:prediabetic{},
eng_noun:antiphase{},
eng_noun:subliterate{},
eng_noun:errhine{},
eng_noun:orangey{},
eng_noun:Balzacian{},
eng_noun:high - pass{},
eng_noun:maximalist{},
eng_noun:enate{},
eng_noun:CFNM{},
eng_noun:Gascon{},
eng_noun:eventualist{},
eng_noun:pseudovirgin{},
eng_noun:basisphenoid{},
eng_noun:dinosaurian{},
eng_noun:cytoprotective{},
eng_noun:noncompete{},
eng_noun:myelosuppressive{},
eng_noun:subjectivist{},
eng_noun:centralist{},
eng_noun:noncognate{},
eng_noun:nonanimal{},
eng_noun:inegalitarian{},
eng_noun:nonmarried{},
eng_noun:symptomless{},
eng_noun:multiculturalist{},
eng_noun:midcap{},
eng_noun:nonrival{},
eng_noun:whirly{},
eng_noun:protohuman{},
eng_noun:Paulian{},
eng_noun:realis{},
eng_noun:nonepileptic{},
eng_noun:cidery{},
eng_noun:nerdcore{},
eng_noun:nonfriable{},
eng_noun:ejectile{},
eng_noun:no - doc{},
eng_noun:Mariavite{},
eng_noun:acmeist{},
eng_noun:shell - like{},
eng_noun:Masurian{},
eng_noun:Lewesian{},
eng_noun:bysen{},
eng_noun:Pyrrhonian{},
eng_noun:Praguian{},
eng_noun:Ljubljanan{},
eng_noun:Tiranan{},
eng_noun:Brusselian{},
eng_noun:Copenhagener{},
eng_noun:Stockholmer{},
eng_noun:intensivist{},
eng_noun:Burnsian{},
eng_noun:Brabantian{},
eng_noun:precative{},
eng_noun:Crowleyan{},
eng_noun:Helvetian{},
eng_noun:Byronian{},
eng_noun:hyperreal{},
eng_noun:Campbellite{},
eng_noun:nonparanoid{},
eng_noun:alexipharmic{},
eng_noun:nonwar{},
eng_noun:precancer{},
eng_noun:Adjarian{},
eng_noun:anticar{},
eng_noun:nonminor{},
eng_noun:nonbisexual{},
eng_noun:chemoprophylactic{},
eng_noun:counterfeminist{},
eng_noun:non - dance{},
eng_noun:nonproperty{},
eng_noun:nonegalitarian{},
eng_noun:Lockean{},
eng_noun:Pompeian{},
eng_noun:Australopith{},
eng_noun:nonindigent{},
eng_noun:vetitive{},
eng_noun:wholewheat{},
eng_noun:nonvariant{},
eng_noun:Gagauz{},
eng_noun:nonmonetarist{},
eng_noun:stupefacient{},
eng_noun:preop{},
eng_noun:mousseux{},
eng_noun:monofractal{},
eng_noun:unfavorite{},
eng_noun:nonhorse{},
eng_noun:nondrama{},
eng_noun:Cyprian{},
eng_noun:multiquark{},
eng_noun:capitulationist{},
eng_noun:pteropine{},
eng_noun:Pichileminian{},
eng_noun:Afro - indian{},
eng_noun:Sassanid{},
eng_noun:Abkhasian{},
eng_noun:Cameronite{},
eng_noun:Antiochian{},
eng_noun:heartcut{},
eng_noun:Aramaean{},
eng_noun:Aramean{},
eng_noun:Medician{},
eng_noun:gorgonian{},
eng_noun:ichthyoid{},
eng_noun:pro - abort{},
eng_noun:balductum{},
eng_noun:reactionist{},
eng_noun:predicant{},
eng_noun:settleable{},
eng_noun:asbuilt{},
eng_noun:Chattanoogan{},
eng_noun:Sevillan{},
eng_noun:anti - rust{},
eng_noun:Tripolitanian{},
eng_noun:push - through{},
eng_noun:drudgy{},
eng_noun:Ossete{},
eng_noun:scatheless{},
eng_noun:exhortative{},
eng_noun:Gallo - roman{},
eng_noun:hokie{},
eng_noun:bellywark{},
eng_noun:megadollar{},
eng_noun:multialgorithm{},
eng_noun:cooperant{},
eng_noun:twissell{},
eng_noun:italophone{},
eng_noun:antipluralist{},
eng_noun:antinaturalist{},
eng_noun:mithridatic{},
eng_noun:Seljuqian{},
eng_noun:meshugenah{},
eng_noun:sixgill{},
eng_noun:rustick{},
eng_noun:braveheart{},
eng_noun:advaunce{},
eng_noun:Hebrean{},
eng_noun:interiour{},
eng_noun:Columbian{},
eng_noun:Pamplonan{},
eng_noun:vorticist{},
eng_noun:antiliberal{},
eng_noun:antilibertarian{},
eng_noun:antidesiccant{},
eng_noun:nonsubject{},
eng_noun:antimask{},
eng_noun:antiquitarian{},
eng_noun:majour{},
eng_noun:nonprotest{},
eng_noun:characteristick{},
eng_noun:tonick{},
eng_noun:ethnick{},
eng_noun:paralytick{},
eng_noun:novenary{},
eng_noun:opercular{},
eng_noun:rory{},
eng_noun:Haytian{},
eng_noun:bumfuck{},
eng_noun:Afric{},
eng_noun:nasoturbinal{},
eng_noun:miscreaunt{},
eng_noun:tauromachian{},
eng_noun:hypohyal{},
eng_noun:refrigerative{},
eng_noun:antipodagric{},
eng_noun:Tripolitan{},
eng_noun:crossopterygian{},
eng_noun:Achaemenian{},
eng_noun:antihypnotic{},
eng_noun:Utahan{},
eng_noun:implacental{},
eng_noun:counter - revolutionary{},
eng_noun:interparietal{},
eng_noun:clinodiagonal{},
eng_noun:world{},
eng_noun:work{},
eng_noun:pale{},
eng_noun:close{},
eng_noun:evil{},
eng_noun:old{},
eng_noun:summer{},
eng_noun:spare{},
eng_noun:anglophile{},
eng_noun:attractant{},
eng_noun:biscuit{},
eng_noun:carrion{},
eng_noun:caesarean{},
eng_noun:cree{},
eng_noun:darn{},
eng_noun:decrescendo{},
eng_noun:disinfectant{},
eng_noun:dusk{},
eng_noun:factoid{},
eng_noun:fake{},
eng_noun:glam{},
eng_noun:ganoid{},
eng_noun:frank{},
eng_noun:hydrozoan{},
eng_noun:infidel{},
eng_noun:isoseismal{},
eng_noun:journalist{},
eng_noun:julienne{},
eng_noun:lowland{},
eng_noun:monocular{},
eng_noun:neuralgia{},
eng_noun:overenthusiasm{},
eng_noun:naught{},
eng_noun:placoid{},
eng_noun:pianissimo{},
eng_noun:polymorphism{},
eng_noun:partisan{},
eng_noun:recusant{},
eng_noun:purgative{},
eng_noun:predestinarian{},
eng_noun:sib{},
eng_noun:territorial{},
eng_noun:superscript{},
eng_noun:teen{},
eng_noun:stationary{},
eng_noun:tonic{},
eng_noun:trusty{},
eng_noun:volute{},
eng_noun:vegetable{},
eng_noun:republicrat{},
eng_noun:mope{},
eng_noun:hump{},
eng_noun:secant{},
eng_noun:parti{},
eng_noun:hind{},
eng_noun:rigorist{},
eng_noun:courtier{},
eng_noun:romanesque{},
eng_noun:shy{},
eng_noun:boon{},
eng_noun:umber{},
eng_noun:forte{},
eng_noun:swell{},
eng_noun:techno{},
eng_noun:outback{},
eng_noun:electro{},
eng_noun:haulage{},
eng_noun:shipboard{},
eng_noun:pastorate{},
eng_noun:monocoque{},
eng_noun:allegretto{},
eng_noun:sabbatarian{},
eng_noun:fit{},
eng_noun:aloetic{},
eng_noun:flat{},
eng_noun:bivalve{},
eng_noun:extrovert{},
eng_noun:video{},
eng_noun:hairline{},
eng_noun:softcore{},
eng_noun:ultraviolet{},
eng_noun:paralegal{},
eng_noun:problematic{},
eng_noun:friendly{},
eng_noun:factorial{},
eng_noun:airplay{},
eng_noun:necessarian{},
eng_noun:autofocus{},
eng_noun:hale{},
eng_noun:paraboloid{},
eng_noun:lophobranch{},
eng_noun:viridian{},
eng_noun:lagging{},
eng_noun:speaking{},
eng_noun:beginning{},
eng_noun:happening{},
eng_noun:killing{},
eng_noun:pressing{},
eng_noun:spinning{},
eng_noun:tickling{},
eng_noun:sporting{},
eng_noun:sterling{},
eng_noun:unreflecting{},
eng_noun:unsuspecting{},
eng_noun:childbearing{},
eng_noun:shareholding{},
eng_noun:trending{},
eng_noun:inbound{},
eng_noun:inbred{},
eng_noun:abdicant{},
eng_noun:ablative{},
eng_noun:abnormal{},
eng_noun:abolitionist{},
eng_noun:absolvent{},
eng_noun:abstersive{},
eng_noun:abstinent{},
eng_noun:Abyssinian{},
eng_noun:pseudo{},
eng_noun:quotidian{},
eng_noun:uncountable{},
eng_noun:Netherlands{},
eng_noun:ace{},
eng_noun:silver{},
eng_noun:imperfect{},
eng_noun:irrational{},
eng_noun:infinitive{},
eng_noun:future{},
eng_noun:comparative{},
eng_noun:leather{},
eng_noun:east{},
eng_noun:crimson{},
eng_noun:azure{},
eng_noun:aquamarine{},
eng_noun:chocolate{},
eng_noun:orchid{},
eng_noun:salmon{},
eng_noun:turquoise{},
eng_noun:russet{},
eng_noun:scarlet{},
eng_noun:sepia{},
eng_noun:amethyst{},
eng_noun:pyramidal{},
eng_noun:Canberran{},
eng_noun:Hobartian{},
eng_noun:Perthian{},
eng_noun:chamois{},
eng_noun:Zulu{},
eng_noun:liberal{},
eng_noun:aforementioned{},
eng_noun:maiden{},
eng_noun:Moslem{},
eng_noun:criminal{},
eng_noun:exterior{},
eng_noun:Cornish{},
eng_noun:by{},
eng_noun:chicken{},
eng_noun:liquid{},
eng_noun:federation{},
eng_noun:freshwater{},
eng_noun:Armenian{},
eng_noun:quiet{},
eng_noun:penultimate{},
eng_noun:cardinal{},
eng_noun:hypocoristic{},
eng_noun:Sardinian{},
eng_noun:Floridian{},
eng_noun:Neapolitan{},
eng_noun:Venetian{},
eng_noun:supernatural{},
eng_noun:acephalan{},
eng_noun:epicurean{},
eng_noun:coefficient{},
eng_noun:economy{},
eng_noun:Bahamian{},
eng_noun:Barbadian{},
eng_noun:Swiss{},
eng_noun:Pakistani{},
eng_noun:Egyptian{},
eng_noun:Lebanese{},
eng_noun:Tunisian{},
eng_noun:Ivorian{},
eng_noun:Togolese{},
eng_noun:Saudi{},
eng_noun:foible{},
eng_noun:hybrid{},
eng_noun:dynamic{},
eng_noun:apricot{},
eng_noun:Punjabi{},
eng_noun:Eskimo{},
eng_noun:exotic{},
eng_noun:aery{},
eng_noun:rouge{},
eng_noun:chief{},
eng_noun:up{},
eng_noun:affluent{},
eng_noun:superficial{},
eng_noun:valuable{},
eng_noun:kam{},
eng_noun:intent{},
eng_noun:variable{},
eng_noun:Manx{},
eng_noun:Tahitian{},
eng_noun:inside{},
eng_noun:constructivist{},
eng_noun:equal{},
eng_noun:descriptive{},
eng_noun:median{},
eng_noun:possible{},
eng_noun:passive{},
eng_noun:triliteral{},
eng_noun:defective{},
eng_noun:nonalcoholic{},
eng_noun:staccato{},
eng_noun:fortis{},
eng_noun:adverbial{},
eng_noun:Trinitarian{},
eng_noun:universist{},
eng_noun:lab{},
eng_noun:faux{},
eng_noun:brand{},
eng_noun:globular{},
eng_noun:horsy{},
eng_noun:capillary{},
eng_noun:normal{},
eng_noun:citron{},
eng_noun:pagan{},
eng_noun:mulberry{},
eng_noun:apposite{},
eng_noun:hermaphrodite{},
eng_noun:centigrade{},
eng_noun:fetid{},
eng_noun:LEGO{},
eng_noun:recalcitrant{},
eng_noun:salient{},
eng_noun:prior{},
eng_noun:triple{},
eng_noun:religious{},
eng_noun:spiritual{},
eng_noun:unrestrained{},
eng_noun:captive{},
eng_noun:emo{},
eng_noun:compulsive{},
eng_noun:sandy{},
eng_noun:basal{},
eng_noun:dickey{},
eng_noun:hymnal{},
eng_noun:patina{},
eng_noun:withy{},
eng_noun:antinomian{},
eng_noun:dandelion{},
eng_noun:immune{},
eng_noun:indubitable{},
eng_noun:ripe{},
eng_noun:splay{},
eng_noun:recluse{},
eng_noun:thumby{},
eng_noun:sunny{},
eng_noun:explosive{},
eng_noun:paranoid{},
eng_noun:Bacchanalian{},
eng_noun:gyratory{},
eng_noun:savvy{},
eng_noun:crunk{},
eng_noun:mid - december{},
eng_noun:state - of - the - art{},
eng_noun:candid{},
eng_noun:avant - garde{},
eng_noun:fungible{},
eng_noun:Dickensian{},
eng_noun:manuscript{},
eng_noun:Iberian{},
eng_noun:aromatic{},
eng_noun:prescriptivist{},
eng_noun:sickle{},
eng_noun:batshit{},
eng_noun:blackleg{},
eng_noun:conic{},
eng_noun:associate{},
eng_noun:telltale{},
eng_noun:lily{},
eng_noun:Remulakian{},
eng_noun:starvation{},
eng_noun:profound{},
eng_noun:megapixel{},
eng_noun:fringe{},
eng_noun:antepenultimate{},
eng_noun:paprika{},
eng_noun:pluperfect{},
eng_noun:routine{},
eng_noun:undercover{},
eng_noun:metropolitan{},
eng_noun:polemic{},
eng_noun:xenobiotic{},
eng_noun:hypnotic{},
eng_noun:hypochondriac{},
eng_noun:frolic{},
eng_noun:badass{},
eng_noun:epicene{},
eng_noun:crematory{},
eng_noun:emergency{},
eng_noun:pisiform{},
eng_noun:fashionable{},
eng_noun:heterodont{},
eng_noun:comedolytic{},
eng_noun:stretto{},
eng_noun:meliorist{},
eng_noun:covert{},
eng_noun:pompous{},
eng_noun:metallic{},
eng_noun:broadband{},
eng_noun:girly{},
eng_noun:tough{},
eng_noun:outsize{},
eng_noun:dop{},
eng_noun:picaresque{},
eng_noun:infrared{},
eng_noun:conjunctive{},
eng_noun:coprophiliac{},
eng_noun:schoolboy{},
eng_noun:chubby{},
eng_noun:tutelary{},
eng_noun:astringent{},
eng_noun:inedible{},
eng_noun:undergraduate{},
eng_noun:undesirable{},
eng_noun:pedigree{},
eng_noun:rascal{},
eng_noun:malcontent{},
eng_noun:legendary{},
eng_noun:Lusophone{},
eng_noun:transformist{},
eng_noun:Cockney{},
eng_noun:elitist{},
eng_noun:transnational{},
eng_noun:transactinide{},
eng_noun:Ediacaran{},
eng_noun:Mississippian{},
eng_noun:antioxidant{},
eng_noun:dumbshit{},
eng_noun:downtown{},
eng_noun:cloverleaf{},
eng_noun:gamboge{},
eng_noun:reseda{},
eng_noun:Aristotelian{},
eng_noun:burlywood{},
eng_noun:lovat{},
eng_noun:florentine{},
eng_noun:dissentient{},
eng_noun:scaphoid{},
eng_noun:poltroon{},
eng_noun:co - ed{},
eng_noun:sphenoid{},
eng_noun:grass - green{},
eng_noun:monorchid{},
eng_noun:lacy{},
eng_noun:dioptric{},
eng_noun:fey{},
eng_noun:retrospective{},
eng_noun:takeaway{},
eng_noun:Disney{},
eng_noun:literate{},
eng_noun:repellant{},
eng_noun:alluvial{},
eng_noun:hylic{},
eng_noun:reptilian{},
eng_noun:terpsichorean{},
eng_noun:ignostic{},
eng_noun:heathen{},
eng_noun:murk{},
eng_noun:Albertan{},
eng_noun:sublime{},
eng_noun:hearty{},
eng_noun:motley{},
eng_noun:proximate{},
eng_noun:corrival{},
eng_noun:lonesome{},
eng_noun:indispensable{},
eng_noun:organometallic{},
eng_noun:brunet{},
eng_noun:parastatal{},
eng_noun:psychotropic{},
eng_noun:flambe{},
eng_noun:technosexual{},
eng_noun:zygodactyl{},
eng_noun:exhibitionist{},
eng_noun:invasive{},
eng_noun:Pentecostal{},
eng_noun:stunod{},
eng_noun:textbook{},
eng_noun:thematic{},
eng_noun:terracotta{},
eng_noun:bloodshot{},
eng_noun:Israelite{},
eng_noun:postgrad{},
eng_noun:exemplary{},
eng_noun:adessive{},
eng_noun:esculent{},
eng_noun:succulent{},
eng_noun:supplemental{},
eng_noun:satin{},
eng_noun:backwoods{},
eng_noun:separatist{},
eng_noun:payable{},
eng_noun:eastward{},
eng_noun:madcap{},
eng_noun:pococurante{},
eng_noun:psychoanalytic{},
eng_noun:Caesarian{},
eng_noun:caitiff{},
eng_noun:ferly{},
eng_noun:diuretic{},
eng_noun:Tlingit{},
eng_noun:Torontonian{},
eng_noun:traducian{},
eng_noun:analgesic{},
eng_noun:Riojan{},
eng_noun:reformist{},
eng_noun:hydro{},
eng_noun:rotary{},
eng_noun:Arian{},
eng_noun:immunological{},
eng_noun:namby - pamby{},
eng_noun:rah{},
eng_noun:crinoid{},
eng_noun:irredentist{},
eng_noun:xiphioid{},
eng_noun:preschool{},
eng_noun:intermetallic{},
eng_noun:untimely{},
eng_noun:parietal{},
eng_noun:folkie{},
eng_noun:bulimic{},
eng_noun:rattletrap{},
eng_noun:prerequisite{},
eng_noun:rodomontade{},
eng_noun:Stakhanovite{},
eng_noun:polyphenolic{},
eng_noun:champaign{},
eng_noun:enceinte{},
eng_noun:jussive{},
eng_noun:ooid{},
eng_noun:grizzly{},
eng_noun:confectionary{},
eng_noun:ascendant{},
eng_noun:carefree{},
eng_noun:squiggly{},
eng_noun:sesquiterpenoid{},
eng_noun:clatty{},
eng_noun:Grecian{},
eng_noun:legionary{},
eng_noun:Zanzibari{},
eng_noun:causative{},
eng_noun:imponderable{},
eng_noun:paquebot{},
eng_noun:Pastafarian{},
eng_noun:agoraphobic{},
eng_noun:attaint{},
eng_noun:docetist{},
eng_noun:rhinestone{},
eng_noun:standover{},
eng_noun:girlie{},
eng_noun:Beltway{},
eng_noun:unrestricted{},
eng_noun:sulpha{},
eng_noun:fae{},
eng_noun:nonessential{},
eng_noun:parasympathomimetic{},
eng_noun:liveaboard{},
eng_noun:eyeful{},
eng_noun:walk - up{},
eng_noun:castiron{},
eng_noun:escapist{},
eng_noun:waterside{},
eng_noun:polytene{},
eng_noun:arthritic{},
eng_noun:trisyllabic{},
eng_noun:biodegradable{},
eng_noun:Moldavian{},
eng_noun:Byelorussian{},
eng_noun:frictionless{},
eng_noun:salutatory{},
eng_noun:Acheulean{},
eng_noun:pluvial{},
eng_noun:poopy{},
eng_noun:poopie{},
eng_noun:semblable{},
eng_noun:climacteric{},
eng_noun:spalt{},
eng_noun:negotiable{},
eng_noun:sciurine{},
eng_noun:sooky{},
eng_noun:glassful{},
eng_noun:long - haul{},
eng_noun:work - to - rule{},
eng_noun:centrist{},
eng_noun:Canaanite{},
eng_noun:careerist{},
eng_noun:concubinary{},
eng_noun:microelectronic{},
eng_noun:split - level{},
eng_noun:domiciliary{},
eng_noun:slip - on{},
eng_noun:semiprofessional{},
eng_noun:ding - dong{},
eng_noun:preventative{},
eng_noun:ovibovine{},
eng_noun:billable{},
eng_noun:Pascha{},
eng_noun:antimycotic{},
eng_noun:antifungal{},
eng_noun:polyacrylic{},
eng_noun:polyunsaturate{},
eng_noun:approbative{},
eng_noun:essentialist{},
eng_noun:boffo{},
eng_noun:Maxonian{},
eng_noun:octonary{},
eng_noun:eruptive{},
eng_noun:ternary{},
eng_noun:mandibulate{},
eng_noun:Mannerist{},
eng_noun:decretal{},
eng_noun:Jerusalemite{},
eng_noun:Ottawan{},
eng_noun:Peronist{},
eng_noun:freezable{},
eng_noun:Aquarian{},
eng_noun:depilatory{},
eng_noun:mure{},
eng_noun:dinkum{},
eng_noun:Finnic{},
eng_noun:vallecular{},
eng_noun:Aluredian{},
eng_noun:microsurgery{},
eng_noun:hearthside{},
eng_noun:hookup{},
eng_noun:indeterminable{},
eng_noun:bamboo{},
eng_noun:heptapeptide{},
eng_noun:nonpartisan{},
eng_noun:vespid{},
eng_noun:diglot{},
eng_noun:organobromine{},
eng_noun:proforma{},
eng_noun:sawtooth{},
eng_noun:Tenochcan{},
eng_noun:remiped{},
eng_noun:paediatric{},
eng_noun:nihilarian{},
eng_noun:quadrate{},
eng_noun:Nebraskan{},
eng_noun:Nabatean{},
eng_noun:pansexual{},
eng_noun:parotid{},
eng_noun:Dorian{},
eng_noun:Zarathustrian{},
eng_noun:nonparticipant{},
eng_noun:nonrecognition{},
eng_noun:nonsexist{},
eng_noun:nonspecialist{},
eng_noun:Emirati{},
eng_noun:serpentry{},
eng_noun:geru{},
eng_noun:bichord{},
eng_noun:roundhead{},
eng_noun:Jamerican{},
eng_noun:epical{},
eng_noun:antiprotozoal{},
eng_noun:cotemporary{},
eng_noun:alkenyl{},
eng_noun:preseed{},
eng_noun:aminopropyl{},
eng_noun:Rusyn{},
eng_noun:brookside{},
eng_noun:screwtop{},
eng_noun:Indo - germanic{},
eng_noun:biaryl{},
eng_noun:quartan{},
eng_noun:nanophase{},
eng_noun:nonwoven{},
eng_noun:Ukie{},
eng_noun:choleretic{},
eng_noun:structuralist{},
eng_noun:obviative{},
eng_noun:A - line{},
eng_noun:Bostonite{},
eng_noun:antitumor{},
eng_noun:fattist{},
eng_noun:cathartical{},
eng_noun:scoptophiliac{},
eng_noun:Bashkortostani{},
eng_noun:anacreontic{},
eng_noun:neofascist{},
eng_noun:germinant{},
eng_noun:occurrent{},
eng_noun:imponent{},
eng_noun:sphingid{},
eng_noun:turbellarian{},
eng_noun:vesicomyid{},
eng_noun:kutcha{},
eng_noun:elapid{},
eng_noun:hypothecary{},
eng_noun:Manchurian{},
eng_noun:speccy{},
eng_noun:delphinine{},
eng_noun:callable{},
eng_noun:ultramontane{},
eng_noun:Tadzhik{},
eng_noun:Tennessean{},
eng_noun:antifibrinolytic{},
eng_noun:nonemergency{},
eng_noun:anticonsumerist{},
eng_noun:prehypertensive{},
eng_noun:ultranationalist{},
eng_noun:Cromwellian{},
eng_noun:reliabilist{},
eng_noun:fictionalist{},
eng_noun:coherentist{},
eng_noun:semi - vegetarian{},
eng_noun:apiarian{},
eng_noun:nonbusiness{},
eng_noun:ultraportable{},
eng_noun:nonsolvent{},
eng_noun:make - out{},
eng_noun:nonrecombinant{},
eng_noun:paranuchal{},
eng_noun:midconcert{},
eng_noun:nonruminant{},
eng_noun:nondaily{},
eng_noun:lacertilian{},
eng_noun:Mangaian{},
eng_noun:Oblomovist{},
eng_noun:Mantinean{},
eng_noun:Mantuan{},
eng_noun:nonscalar{},
eng_noun:medusoid{},
eng_noun:Shanghainese{},
eng_noun:Benthamite{},
eng_noun:nonmineral{},
eng_noun:Sarajevan{},
eng_noun:Skopjan{},
eng_noun:Rigan{},
eng_noun:Hanoian{},
eng_noun:nonlife{},
eng_noun:bayard{},
eng_noun:malaprop{},
eng_noun:anarcho - capitalist{},
eng_noun:nonfeline{},
eng_noun:Adjaran{},
eng_noun:antiart{},
eng_noun:nonaromatic{},
eng_noun:multilateralist{},
eng_noun:tetanuran{},
eng_noun:obv.{},
eng_noun:winne{},
eng_noun:nonlibertarian{},
eng_noun:nonneurotic{},
eng_noun:afrotherian{},
eng_noun:pappyshow{},
eng_noun:postop{},
eng_noun:inspiral{},
eng_noun:subgrid{},
eng_noun:multipath{},
eng_noun:intermonsoon{},
eng_noun:screw - off{},
eng_noun:Timonist{},
eng_noun:multiport{},
eng_noun:nonevidence{},
eng_noun:schooly{},
eng_noun:antidiarrhoeal{},
eng_noun:aperitive{},
eng_noun:acrodont{},
eng_noun:Narnian{},
eng_noun:Lacedaemonian{},
eng_noun:firster{},
eng_noun:Warsovian{},
eng_noun:Batavian{},
eng_noun:nonsubordinate{},
eng_noun:Sasanian{},
eng_noun:Teucrian{},
eng_noun:neuroprotectant{},
eng_noun:procoagulant{},
eng_noun:antidiarrheic{},
eng_noun:Wesleyan{},
eng_noun:nondiscipline{},
eng_noun:intercommunity{},
eng_noun:Roumanian{},
eng_noun:varioloid{},
eng_noun:vomitory{},
eng_noun:lacunar{},
eng_noun:catarrhine{},
eng_noun:noninterview{},
eng_noun:multivalve{},
eng_noun:scabious{},
eng_noun:extrinsical{},
eng_noun:bicolour{},
eng_noun:antiherpetic{},
eng_noun:Wordsworthian{},
eng_noun:sweetmeal{},
eng_noun:Canadarian{},
eng_noun:Salvatorian{},
eng_noun:Baghdadian{},
eng_noun:lameo{},
eng_noun:Eskimoan{},
eng_noun:witherward{},
eng_noun:Zaragozan{},
eng_noun:miscellanist{},
eng_noun:pretrigger{},
eng_noun:nonsurvival{},
eng_noun:Spenserian{},
eng_noun:Trifluvian{},
eng_noun:dearn{},
eng_noun:Oxfordian{},
eng_noun:verbile{},
eng_noun:lame - o{},
eng_noun:Lamarckian{},
eng_noun:Ostrobothnian{},
eng_noun:read - through{},
eng_noun:Cushitic{},
eng_noun:Neopythagorean{},
eng_noun:pictorialist{},
eng_noun:foldover{},
eng_noun:ridgeside{},
eng_noun:primatal{},
eng_noun:antigonorrhoeic{},
eng_noun:superciliary{},
eng_noun:inferiour{},
eng_noun:Nepaulese{}
}
| The pharmaceutical industry
| eng_noun:pharmaceutical{}, | 7,304,819 | [
1,
1986,
1844,
4610,
623,
322,
1706,
1547,
407,
698,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
24691,
67,
82,
465,
30,
844,
4610,
623,
322,
1706,
2916,
16,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract Presale is AccessControl {
using SafeERC20 for IERC20;
struct SaleInfo {
uint256 stableTokenAmount; //Total allocation bought in stablecoins
uint256 loopTokenAmount; //Total bought LOOP tokens after IDO
uint256 claimedLoopTokenAmount; //Total claimed by user so far
uint8 nextVestingIndex; //Pointer to next claimable tranche
}
mapping(address => bool) public whitelists;
mapping(address => SaleInfo) public presaleList;
mapping(address => bool) public acceptTokens;
struct BuyHistory {
address buyerAddress;
address stablecoinAddress;
uint256 stableTokenAmount;
uint256 buyTime;
}
BuyHistory[] private buyHistory; // Buying history
bool private isPause;
uint8 public constant maxDecimals = 18;
address public immutable loopAddress;
struct SaleRules {
uint256 round2Multiplier;
uint256 fcfsMultiplier;
uint256 round2Minutes;
uint256 fcfsMinutes;
bool round2RequireWhitelist;
bool fcfsRequireWhitelist;
}
struct VestingTranche {
uint16 Percentage; //Percentage Vested in Basis points 10,000 = 100%
uint256 Date; //UNIX Timestamp of Vesting
}
SaleRules public saleRules;
VestingTranche[] public vestingSchedule;
uint256 public saleStartTime;
uint256 public saleEndTime;
uint256 public immutable tokenPrice;
uint256 public immutable allowedTokenAmount;
uint256 public soldToken;
uint256 public immutable presaleTokenAmount;
event TokenPurchased(address userAddress, uint256 purchasedAmount);
event TokenClaimed(address userAddress, uint256 purchasedAmount);
constructor(
address _loopAddress,
uint256 _saleStartTime,
uint256 _saleEndTime,
uint256 _tokenPrice,
uint256 _allowedTokenAmount,
SaleRules memory _saleRules,
VestingTranche[] memory _vestingSchedule,
address[] memory _acceptTokens,
uint256 _presaleTokenAmount
) {
require(_saleEndTime >= _saleStartTime);
require(_saleRules.round2Minutes >= 0);
require(_saleRules.fcfsMinutes >= 0);
require(_tokenPrice > 0);
require(_allowedTokenAmount >= 0);
require(_presaleTokenAmount >= 0);
require(_saleRules.round2Multiplier >= 1);
require(_saleRules.fcfsMultiplier >= 1);
require(_vestingSchedule.length > 0);
saleStartTime = _saleStartTime;
saleEndTime = _saleEndTime;
saleRules.round2Minutes = _saleRules.round2Minutes;
saleRules.fcfsMinutes = _saleRules.fcfsMinutes;
saleRules.round2Multiplier = _saleRules.round2Multiplier;
saleRules.fcfsMultiplier = _saleRules.fcfsMultiplier;
saleRules.fcfsRequireWhitelist =_saleRules.fcfsRequireWhitelist;
saleRules.fcfsRequireWhitelist =_saleRules.fcfsRequireWhitelist;
//Assign vesting vesting schedule
for(uint i = 0; i < _vestingSchedule.length; i++) {
vestingSchedule.push(_vestingSchedule[i]);
}
require(checkVestingPercentage(_vestingSchedule), "Vesting percentages don't add up to 100%. Please make sure that values are in basis points");
require(checkVestingScheduleOrdered(_vestingSchedule), "Vesting schedule is not ordered from older to newest");
tokenPrice = _tokenPrice;
allowedTokenAmount = _allowedTokenAmount;
loopAddress = _loopAddress;
for (uint i = 0; i < _acceptTokens.length; i ++) {
acceptTokens[_acceptTokens[i]] = true;
}
presaleTokenAmount = _presaleTokenAmount;
soldToken = 0;
isPause = false;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
modifier executable() {
require(!isPause, "Contract is paused");
_;
}
modifier checkEventTime() {
require(block.timestamp >= saleStartTime && block.timestamp <= saleEndTime, "Out of presale period");
_;
}
modifier checkAfterTime() {
require(block.timestamp > saleEndTime, "Presale not finished");
_;
}
function setStartTime(uint256 _saleStartTime) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleStartTime = _saleStartTime;
}
function setEndTime(uint256 _saleEndTime) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleEndTime = _saleEndTime;
}
function setSaleRules(SaleRules calldata _saleRules) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules = _saleRules;
}
function setRound2Multiplier(uint256 _round2Multiplier) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.round2Multiplier = _round2Multiplier;
}
function setFCFSMultiplier(uint256 _fcfsMultiplier) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.fcfsMultiplier = _fcfsMultiplier;
}
function setRound2Minutes(uint256 _round2Minutes) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.round2Minutes = _round2Minutes;
}
function setFCFSMinutes(uint256 _fcfsMinutes) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.fcfsMinutes = _fcfsMinutes;
}
function setRound2RequireWhitelist(bool _flag) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.round2RequireWhitelist = _flag;
}
function setFCFSRequireWhitelist(bool _flag) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
saleRules.fcfsRequireWhitelist = _flag;
}
function getSoldToken() public view returns(uint) {
return soldToken;
}
function stopContract(bool _pause) external onlyRole(DEFAULT_ADMIN_ROLE) {
isPause = _pause;
}
function getPauseStatus() external view returns(bool) {
return isPause;
}
function addWhitelist(address _whiteAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
whitelists[_whiteAddress] = true;
}
function removeWhitelist(address _whiteAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
whitelists[_whiteAddress] = false;
}
function addWhitelists(address[] calldata _whiteAddresses) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint i = 0; i < _whiteAddresses.length; i++) {
whitelists[_whiteAddresses[i]] = true;
}
}
function removeWhitelists(address[] calldata _whiteAddresses) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint i = 0; i < _whiteAddresses.length; i++) {
whitelists[_whiteAddresses[i]] = false;
}
}
function addAcceptTokens(address _acceptTokenAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
acceptTokens[_acceptTokenAddress] = true;
}
function removeAcceptTokens(address _acceptTokenAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) {
acceptTokens[_acceptTokenAddress] = false;
}
function buyToken(address _stableTokenAddress, uint256 _amount) external executable checkEventTime {
require(soldToken != presaleTokenAmount, "All Loop Tokens are sold out");
//Whitelist enforcement
if(block.timestamp < saleEndTime - saleRules.round2Minutes * 1 minutes) { //Round 1
require(whitelists[msg.sender] == true, "Not whitelist address"); //Enforce Whitelist
}
else if ((block.timestamp >= saleEndTime - saleRules.round2Minutes * 1 minutes) && (block.timestamp < saleEndTime - saleRules.fcfsMinutes * 1 minutes) && saleRules.round2RequireWhitelist) {
require(whitelists[msg.sender] == true, "Not whitelist address");
}
else if ((block.timestamp >= saleEndTime - saleRules.fcfsMinutes * 1 minutes) && saleRules.fcfsRequireWhitelist) {
require(whitelists[msg.sender] == true, "Not whitelist address");
}
//End Whitelist enforcement
require(acceptTokens[_stableTokenAddress] == true, "Not stableToken address");
SaleInfo storage saleInfo = presaleList[msg.sender];
uint8 tokenDecimal = ERC20(_stableTokenAddress).decimals();
uint256 tokenAmount = _amount;
if (tokenDecimal < maxDecimals) {
tokenAmount = tokenAmount * 10 ** (maxDecimals - tokenDecimal);
}
uint256 loopTokenAmount = tokenAmount / tokenPrice * 10 ** ERC20(loopAddress).decimals();
require(soldToken + loopTokenAmount <= presaleTokenAmount, "Cannot buy more LOOP tokens than amount up for presale");
if (block.timestamp < saleEndTime - saleRules.round2Minutes * 1 minutes) {
require(saleInfo.stableTokenAmount + tokenAmount <= allowedTokenAmount,
"Exceeding presale token limit during round1 period");
} else if ((block.timestamp >= saleEndTime - saleRules.round2Minutes * 1 minutes) && (block.timestamp < saleEndTime - saleRules.fcfsMinutes * 1 minutes)) {
require(saleInfo.stableTokenAmount + tokenAmount <= allowedTokenAmount * saleRules.round2Multiplier,
"Exceeding presale token limit during round2 period");
} else if (block.timestamp >= saleEndTime - saleRules.fcfsMinutes * 1 minutes) {
require(saleInfo.stableTokenAmount + tokenAmount <= allowedTokenAmount * saleRules.fcfsMultiplier,
"Exceeding presale token limit during FCFS period");
}
saleInfo.stableTokenAmount += tokenAmount;
saleInfo.loopTokenAmount += loopTokenAmount;
saleInfo.claimedLoopTokenAmount = 0;
saleInfo.nextVestingIndex = 0;
soldToken += loopTokenAmount;
IERC20(_stableTokenAddress).safeTransferFrom(msg.sender, address(this), _amount);
//Add Buy History
BuyHistory memory tempHistory;
tempHistory.buyerAddress = msg.sender;
tempHistory.stablecoinAddress = _stableTokenAddress;
tempHistory.stableTokenAmount = _amount;
tempHistory.buyTime = block.timestamp;
addBuyHistory(tempHistory);
emit TokenPurchased(msg.sender, loopTokenAmount);
}
/*
This function claims all vested tranches of Loop tokens
*/
function claimToken() external executable checkAfterTime {
SaleInfo storage saleInfo = presaleList[msg.sender];
require((saleInfo.loopTokenAmount - saleInfo.claimedLoopTokenAmount) > 0, "No claimToken amount");
require(block.timestamp >= vestingSchedule[saleInfo.nextVestingIndex].Date, "No tokens available for claim yet");
uint256 claimAmount = 0; //Amount claimable now
//Claim all eligible vesting tranches
while(block.timestamp >= vestingSchedule[saleInfo.nextVestingIndex].Date) {
claimAmount += (vestingSchedule[saleInfo.nextVestingIndex].Percentage * saleInfo.loopTokenAmount) / 10000;
saleInfo.nextVestingIndex++;
if(saleInfo.nextVestingIndex == vestingSchedule.length) {
break;
}
}
uint balance = IERC20(loopAddress).balanceOf(address(this));
require(balance > 0 && claimAmount <= balance, string(abi.encodePacked(Strings.toString(balance), abi.encodePacked("Insufficient balance for claim amount: ", Strings.toString(claimAmount)))));
saleInfo.claimedLoopTokenAmount += claimAmount;
IERC20(loopAddress).safeTransfer(msg.sender, claimAmount);
emit TokenClaimed(msg.sender, claimAmount);
}
function withdrawAllToken(address _withdrawAddress, address[] calldata _stableTokens) external executable onlyRole(DEFAULT_ADMIN_ROLE) checkAfterTime {
//Withdraw all unsold LOOP tokens
uint256 unsoldLoopTokenAmount = IERC20(loopAddress).balanceOf(address(this)) - soldToken;
if(unsoldLoopTokenAmount > 0) {
IERC20(loopAddress).safeTransfer(_withdrawAddress, unsoldLoopTokenAmount);
}
//Withdraw all stablecoins
for (uint i = 0; i < _stableTokens.length; i ++) {
uint stableTokenAmount = IERC20(_stableTokens[i]).balanceOf(address(this));
IERC20(_stableTokens[i]).safeTransfer(_withdrawAddress, stableTokenAmount);
}
}
function giveBackToken(address _withdrawAddress, address _tokenAddress) external executable onlyRole(DEFAULT_ADMIN_ROLE) checkAfterTime {
require(acceptTokens[_tokenAddress] == false, "Cannot withdraw pre-sale swap stablecoin tokens from presale using this function.");
require(loopAddress != _tokenAddress, "Cannot withdraw Loop tokens from presale using this function.");
uint tokenAmount = IERC20(_tokenAddress).balanceOf(address(this));
IERC20(_tokenAddress).safeTransfer(_withdrawAddress, tokenAmount);
}
function checkVestingPercentage(VestingTranche[] memory _vestingSchedule) pure private returns (bool vestingPercentageCorrect) {
vestingPercentageCorrect = false;
uint16 totalPercentage = 0;
for (uint i = 0; i < _vestingSchedule.length; i++)
{
totalPercentage += _vestingSchedule[i].Percentage;
}
if (totalPercentage == 10000) {
vestingPercentageCorrect = true;
}
}
function checkVestingScheduleOrdered(VestingTranche[] memory _vestingSchedule) pure private returns (bool vestingScheduleOrdered) {
vestingScheduleOrdered = true;
for (uint i = 0; i < _vestingSchedule.length - 1; i++)
{
if(_vestingSchedule[i].Date > _vestingSchedule[i+1].Date) {
vestingScheduleOrdered = false;
break;
}
}
return vestingScheduleOrdered;
}
/*
Allow Admin to modify vesting schedule. Checks to be made that there are no clashes
*/
function modifyVestingSchedule(VestingTranche[] memory _newVestingSchedule) onlyRole(DEFAULT_ADMIN_ROLE) external {
//Basic pre-checks on new vesting schedule
require(checkVestingPercentage(_newVestingSchedule), "Vesting percentages don't add up to 100%. Please make sure that values are in basis points");
require(checkVestingScheduleOrdered(_newVestingSchedule), "Vesting schedule is not ordered from older to newest");
//Check length of new vesting schedule vs old vesting schedule
VestingTranche[] memory oldVestingSchedule;
VestingTranche memory tranche;
oldVestingSchedule = vestingSchedule; //Copy
delete vestingSchedule; //Clear the vesting schedule
//Set new vesting parameters
for (uint i = 0; i < _newVestingSchedule.length; i++) {
if(i < oldVestingSchedule.length) { //Prevent addressing of invalid entries
if(oldVestingSchedule[i].Date < block.timestamp) {
//Copy old vesting values if tranches are in the past
tranche.Date = oldVestingSchedule[i].Date;
tranche.Percentage = oldVestingSchedule[i].Percentage;
}
else {
//Copy for anything where claims have not started
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
}
}
else { //Anything longer than old vesting schedule, we just copy
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
}
vestingSchedule.push(tranche);
}
//Basic checks on validity of vesting parameters
require(checkVestingPercentage(vestingSchedule), "User tried to modify earlier tranches of vesting schedule that created inconsistencies");
require(checkVestingScheduleOrdered(vestingSchedule), "User tried to modify earlier tranches of vesting schedule that created inconsistencies");
}
function addBuyHistory(BuyHistory memory _buyHistory) private {
buyHistory.push(_buyHistory);
}
function getBuyHistory() view external onlyRole(DEFAULT_ADMIN_ROLE) returns (BuyHistory[] memory bHistory) {
return buyHistory;
}
} | /Basic pre-checks on new vesting scheduleCheck length of new vesting schedule vs old vesting scheduleSet new vesting parameters | function modifyVestingSchedule(VestingTranche[] memory _newVestingSchedule) onlyRole(DEFAULT_ADMIN_ROLE) external {
require(checkVestingPercentage(_newVestingSchedule), "Vesting percentages don't add up to 100%. Please make sure that values are in basis points");
require(checkVestingScheduleOrdered(_newVestingSchedule), "Vesting schedule is not ordered from older to newest");
VestingTranche[] memory oldVestingSchedule;
VestingTranche memory tranche;
Allow Admin to modify vesting schedule. Checks to be made that there are no clashes
for (uint i = 0; i < _newVestingSchedule.length; i++) {
if(oldVestingSchedule[i].Date < block.timestamp) {
tranche.Date = oldVestingSchedule[i].Date;
tranche.Percentage = oldVestingSchedule[i].Percentage;
}
else {
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
}
}
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
for (uint i = 0; i < _newVestingSchedule.length; i++) {
if(oldVestingSchedule[i].Date < block.timestamp) {
tranche.Date = oldVestingSchedule[i].Date;
tranche.Percentage = oldVestingSchedule[i].Percentage;
}
else {
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
}
}
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
for (uint i = 0; i < _newVestingSchedule.length; i++) {
if(oldVestingSchedule[i].Date < block.timestamp) {
tranche.Date = oldVestingSchedule[i].Date;
tranche.Percentage = oldVestingSchedule[i].Percentage;
}
else {
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
}
}
tranche.Date = _newVestingSchedule[i].Date;
tranche.Percentage = _newVestingSchedule[i].Percentage;
}
| 12,805,564 | [
1,
19,
8252,
675,
17,
12366,
603,
394,
331,
10100,
4788,
1564,
769,
434,
394,
331,
10100,
4788,
6195,
1592,
331,
10100,
4788,
694,
394,
331,
10100,
1472,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5612,
58,
10100,
6061,
12,
58,
10100,
17730,
18706,
8526,
3778,
389,
2704,
58,
10100,
6061,
13,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
3903,
288,
203,
3639,
2583,
12,
1893,
58,
10100,
16397,
24899,
2704,
58,
10100,
6061,
3631,
315,
58,
10100,
5551,
1023,
2727,
1404,
527,
731,
358,
2130,
9,
18,
7801,
1221,
3071,
716,
924,
854,
316,
10853,
3143,
8863,
203,
3639,
2583,
12,
1893,
58,
10100,
6061,
16756,
24899,
2704,
58,
10100,
6061,
3631,
315,
58,
10100,
4788,
353,
486,
5901,
628,
12156,
358,
19824,
8863,
203,
540,
203,
540,
203,
3639,
776,
10100,
17730,
18706,
8526,
3778,
1592,
58,
10100,
6061,
31,
203,
3639,
776,
10100,
17730,
18706,
3778,
13637,
18706,
31,
203,
540,
203,
203,
203,
203,
203,
565,
7852,
7807,
358,
5612,
331,
10100,
4788,
18,
13074,
358,
506,
7165,
716,
1915,
854,
1158,
927,
7690,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
2704,
58,
10100,
6061,
18,
2469,
31,
277,
27245,
288,
203,
203,
7734,
309,
12,
1673,
58,
10100,
6061,
63,
77,
8009,
1626,
411,
1203,
18,
5508,
13,
288,
203,
10792,
13637,
18706,
18,
1626,
273,
1592,
58,
10100,
6061,
63,
77,
8009,
1626,
31,
203,
10792,
13637,
18706,
18,
16397,
273,
1592,
58,
10100,
6061,
63,
77,
8009,
16397,
31,
27699,
7734,
289,
203,
7734,
469,
288,
203,
10792,
13637,
18706,
18,
1626,
273,
389,
2704,
58,
10100,
6061,
63,
77,
8009,
1626,
31,
203,
10792,
13637,
18706,
18,
16397,
273,
389,
2704,
58,
2
] |
/******************************************************************************\
file: Math.sol
ver: 0.5.0
updated:25-10-2017
author: Darryl Morris (o0ragman0o)
email: o0ragman0o AT gmail.com
unit256 and uint64 Safe maths libraries.
---
pragma solidity ^0.4.13;
import "Math.sol"
contract K{
using MathU for uint;
uint num;
function foo(uint x) {
...
num = num.add(x);
...
}
}
---
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
Release Notes
-------------
* set all functions to `pure`
* Added safe uint casting for common uint sub types
* removed Math64 library
\******************************************************************************/
pragma solidity ^0.4.13;
library Math
{
int8 constant LT = -1;
int8 constant EQ = 0;
int8 constant GT = 1;
// a add to b
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
assert(c >= a);
}
// a subtract b
function sub(uint a, uint b) internal pure returns (uint c) {
c = a - b;
assert(c <= a);
}
// a multiplied by b
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
assert(a == 0 || c / a == b);
}
// a divided by b
function div(uint a, uint b) internal pure returns (uint c) {
require (b != 0);
c = a / b;
}
// Increment
function inc(uint a) internal pure returns (uint c) {
c = a + 1;
assert(c > a);
}
// Decrement
function dec(uint a) internal pure returns (uint c) {
c = a - 1;
assert(c < a);
}
// Raise a to power of b
function pow(uint a, uint8 b) internal pure returns (uint c) {
c = a**b;
// Not a sufficient test as overflowed result may still be larger
assert(c > a);
}
// Equal to
function eq(uint a, uint b) internal pure returns (bool) {
return a == b;
}
// Less than
function lt(uint a, uint b) internal pure returns (bool) {
return a < b;
}
// Greater than
function gt(uint a, uint b) internal pure returns (bool) {
return a > b;
}
// Less than or equal to.
function lteq(uint a, uint b) internal pure returns (bool) {
return a <= b;
}
// Greater than or equal to.
function gteq(uint a, uint b) internal pure returns (bool) {
return a >= b;
}
// Zero value test
function isZero(uint a) internal pure returns (bool) {
return a == 0;
}
// Parametric comparitor for > or <
// !_sym returns a < b
// _sym returns a > b
function cmp(uint a, uint b, bool sym) internal pure returns (bool)
{
return (a!=b) && ((a < b) != sym);
}
// Parametric comparitor for >= or <=
// !_sym returns a <= b
// _sym returns a >= b
function cmpEq(uint a, uint b, bool sym) internal pure returns (bool)
{
return (a==b) || ((a < b) != sym);
}
// Trinary comparitor returning int -1, 0, 1 for LT, EQ, GT
function cmpTri(uint a, uint b) internal pure returns (int8) {
return a < b ? LT : a > b ? GT : EQ;
}
// Safe cast from uint to uint8
function to8(uint a) internal pure returns (uint8 b) {
b = uint8(a);
assert(uint(b) == a);
}
// Safecast from uint to uint16
function to16(uint a) internal pure returns (uint16 b) {
b = uint16(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint32
function to32(uint a) internal pure returns (uint32 b) {
b = uint32(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint40
function to40(uint a) internal pure returns (uint40 b) {
b = uint40(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint48
function to48(uint a) internal pure returns (uint48 b) {
b = uint48(a);
assert(uint(b) == a);
}
// Safecast from uint to uint56
function to56(uint a) internal pure returns (uint56 b) {
b = uint56(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint64
function to64(uint a) internal pure returns (uint64 b) {
b = uint64(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint72
function to72(uint a) internal pure returns (uint72 b) {
b = uint72(a);
assert(uint(b) == a);
}
// Safecast from uint to uint80
function to80(uint a) internal pure returns (uint80 b) {
b = uint80(a);
assert(uint(b) == a);
}
// Safe cast from uint to uint96
function to96(uint a) internal pure returns (uint96 b) {
b = uint96(a);
assert(uint(b) == a);
}
// Safecast from uint to uint128
function to128(uint a) internal pure returns (uint128 b) {
b = uint128(a);
assert(uint(b) == a);
}
// Safecast from uint to uint192
function to192(uint a) internal pure returns (uint192 b) {
b = uint192(a);
assert(uint(b) == a);
}
} | Safe cast from uint to uint32 | function to32(uint a) internal pure returns (uint32 b) {
b = uint32(a);
assert(uint(b) == a);
}
| 12,755,852 | [
1,
9890,
4812,
628,
2254,
358,
2254,
1578,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
358,
1578,
12,
11890,
279,
13,
2713,
16618,
1135,
261,
11890,
1578,
324,
13,
288,
203,
3639,
324,
273,
2254,
1578,
12,
69,
1769,
203,
3639,
1815,
12,
11890,
12,
70,
13,
422,
279,
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
] |
pragma solidity ^0.5.10;
/**
* @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.
*/
contract ReentrancyGuard {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: contracts/commons/Ownable.sol
pragma solidity ^0.5.10;
contract Ownable {
address public owner;
event TransferOwnership(address _from, address _to);
constructor() public {
owner = msg.sender;
emit TransferOwnership(address(0), msg.sender);
}
modifier onlyOwner() {
require(msg.sender == owner, "only owner");
_;
}
function setOwner(address _owner) external onlyOwner {
emit TransferOwnership(owner, _owner);
owner = _owner;
}
}
// File: contracts/commons/StorageUnit.sol
pragma solidity ^0.5.10;
contract StorageUnit {
address private owner;
mapping(bytes32 => bytes32) private store;
constructor() public {
owner = msg.sender;
}
function write(bytes32 _key, bytes32 _value) external {
/* solium-disable-next-line */
require(msg.sender == owner);
store[_key] = _value;
}
function read(bytes32 _key) external view returns (bytes32) {
return store[_key];
}
}
// File: contracts/utils/IsContract.sol
pragma solidity ^0.5.10;
library IsContract {
function isContract(address _addr) internal view returns (bool) {
bytes32 codehash;
/* solium-disable-next-line */
assembly { codehash := extcodehash(_addr) }
return codehash != bytes32(0) && codehash != bytes32(0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
}
// File: contracts/utils/DistributedStorage.sol
pragma solidity ^0.5.10;
library DistributedStorage {
function contractSlot(bytes32 _struct) private view returns (address) {
return address(
uint256(
keccak256(
abi.encodePacked(
byte(0xff),
address(this),
_struct,
keccak256(type(StorageUnit).creationCode)
)
)
)
);
}
function deploy(bytes32 _struct) private {
bytes memory slotcode = type(StorageUnit).creationCode;
/* solium-disable-next-line */
assembly{ pop(create2(0, add(slotcode, 0x20), mload(slotcode), _struct)) }
}
function write(
bytes32 _struct,
bytes32 _key,
bytes32 _value
) internal {
StorageUnit store = StorageUnit(contractSlot(_struct));
if (!IsContract.isContract(address(store))) {
deploy(_struct);
}
/* solium-disable-next-line */
(bool success, ) = address(store).call(
abi.encodeWithSelector(
store.write.selector,
_key,
_value
)
);
require(success, "error writing storage");
}
function read(
bytes32 _struct,
bytes32 _key
) internal view returns (bytes32) {
StorageUnit store = StorageUnit(contractSlot(_struct));
if (!IsContract.isContract(address(store))) {
return bytes32(0);
}
/* solium-disable-next-line */
(bool success, bytes memory data) = address(store).staticcall(
abi.encodeWithSelector(
store.read.selector,
_key
)
);
require(success, "error reading storage");
return abi.decode(data, (bytes32));
}
}
// File: contracts/utils/SafeMath.sol
pragma solidity ^0.5.10;
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x + y;
require(z >= x, "Add overflow");
return z;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256) {
require(x >= y, "Sub underflow");
return x - y;
}
function mult(uint256 x, uint256 y) internal pure returns (uint256) {
if (x == 0) {
return 0;
}
uint256 z = x * y;
require(z / x == y, "Mult overflow");
return z;
}
function div(uint256 x, uint256 y) internal pure returns (uint256) {
require(y != 0, "Div by zero");
return x / y;
}
function divRound(uint256 x, uint256 y) internal pure returns (uint256) {
require(y != 0, "Div by zero");
uint256 r = x / y;
if (x % y != 0) {
r = r + 1;
}
return r;
}
}
// File: contracts/utils/Math.sol
pragma solidity ^0.5.10;
library Math {
function orderOfMagnitude(uint256 input) internal pure returns (uint256){
uint256 counter = uint(-1);
uint256 temp = input;
do {
temp /= 10;
counter++;
} while (temp != 0);
return counter;
}
function min(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a < _b) {
return _a;
} else {
return _b;
}
}
function max(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a > _b) {
return _a;
} else {
return _b;
}
}
}
// File: contracts/utils/GasPump.sol
pragma solidity ^0.5.10;
contract GasPump {
bytes32 private stub;
modifier requestGas(uint256 _factor) {
if (tx.gasprice == 0 || gasleft() > block.gaslimit) {
uint256 startgas = gasleft();
_;
uint256 delta = startgas - gasleft();
uint256 target = (delta * _factor) / 100;
startgas = gasleft();
while (startgas - gasleft() < target) {
// Burn gas
stub = keccak256(abi.encodePacked(stub));
}
} else {
_;
}
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity ^0.5.10;
interface IERC20 {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function approve(address _spender, uint256 _value) external returns (bool success);
function balanceOf(address _owner) external view returns (uint256 balance);
}
// File: contracts/commons/AddressMinHeap.sol
pragma solidity ^0.5.10;
/*
@author Agustin Aguilar <[email protected]>
*/
library AddressMinHeap {
using AddressMinHeap for AddressMinHeap.Heap;
struct Heap {
uint256[] entries;
mapping(address => uint256) index;
}
function initialize(Heap storage _heap) internal {
require(_heap.entries.length == 0, "already initialized");
_heap.entries.push(0);
}
function encode(address _addr, uint256 _value) internal pure returns (uint256 _entry) {
/* solium-disable-next-line */
assembly {
_entry := not(or(and(0xffffffffffffffffffffffffffffffffffffffff, _addr), shl(160, _value)))
}
}
function decode(uint256 _entry) internal pure returns (address _addr, uint256 _value) {
/* solium-disable-next-line */
assembly {
let entry := not(_entry)
_addr := and(entry, 0xffffffffffffffffffffffffffffffffffffffff)
_value := shr(160, entry)
}
}
function decodeAddress(uint256 _entry) internal pure returns (address _addr) {
/* solium-disable-next-line */
assembly {
_addr := and(not(_entry), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
function top(Heap storage _heap) internal view returns(address, uint256) {
if (_heap.entries.length < 2) {
return (address(0), 0);
}
return decode(_heap.entries[1]);
}
function has(Heap storage _heap, address _addr) internal view returns (bool) {
return _heap.index[_addr] != 0;
}
function size(Heap storage _heap) internal view returns (uint256) {
return _heap.entries.length - 1;
}
function entry(Heap storage _heap, uint256 _i) internal view returns (address, uint256) {
return decode(_heap.entries[_i + 1]);
}
// RemoveMax pops off the root element of the heap (the highest value here) and rebalances the heap
function popTop(Heap storage _heap) internal returns(address _addr, uint256 _value) {
// Ensure the heap exists
uint256 heapLength = _heap.entries.length;
require(heapLength > 1, "The heap does not exists");
// take the root value of the heap
(_addr, _value) = decode(_heap.entries[1]);
_heap.index[_addr] = 0;
if (heapLength == 2) {
_heap.entries.length = 1;
} else {
// Takes the last element of the array and put it at the root
uint256 val = _heap.entries[heapLength - 1];
_heap.entries[1] = val;
// Delete the last element from the array
_heap.entries.length = heapLength - 1;
// Start at the top
uint256 ind = 1;
// Bubble down
ind = _heap.bubbleDown(ind, val);
// Update index
_heap.index[decodeAddress(val)] = ind;
}
}
// Inserts adds in a value to our heap.
function insert(Heap storage _heap, address _addr, uint256 _value) internal {
require(_heap.index[_addr] == 0, "The entry already exists");
// Add the value to the end of our array
uint256 encoded = encode(_addr, _value);
_heap.entries.push(encoded);
// Start at the end of the array
uint256 currentIndex = _heap.entries.length - 1;
// Bubble Up
currentIndex = _heap.bubbleUp(currentIndex, encoded);
// Update index
_heap.index[_addr] = currentIndex;
}
function update(Heap storage _heap, address _addr, uint256 _value) internal {
uint256 ind = _heap.index[_addr];
require(ind != 0, "The entry does not exists");
uint256 can = encode(_addr, _value);
uint256 val = _heap.entries[ind];
uint256 newInd;
if (can < val) {
// Bubble down
newInd = _heap.bubbleDown(ind, can);
} else if (can > val) {
// Bubble up
newInd = _heap.bubbleUp(ind, can);
} else {
// no changes needed
return;
}
// Update entry
_heap.entries[newInd] = can;
// Update index
if (newInd != ind) {
_heap.index[_addr] = newInd;
}
}
function bubbleUp(Heap storage _heap, uint256 _ind, uint256 _val) internal returns (uint256 ind) {
// Bubble up
ind = _ind;
if (ind != 1) {
uint256 parent = _heap.entries[ind / 2];
while (parent < _val) {
// If the parent value is lower than our current value, we swap them
(_heap.entries[ind / 2], _heap.entries[ind]) = (_val, parent);
// Update moved Index
_heap.index[decodeAddress(parent)] = ind;
// change our current Index to go up to the parent
ind = ind / 2;
if (ind == 1) {
break;
}
// Update parent
parent = _heap.entries[ind / 2];
}
}
}
function bubbleDown(Heap storage _heap, uint256 _ind, uint256 _val) internal returns (uint256 ind) {
// Bubble down
ind = _ind;
uint256 lenght = _heap.entries.length;
uint256 target = lenght - 1;
while (ind * 2 < lenght) {
// get the current index of the children
uint256 j = ind * 2;
// left child value
uint256 leftChild = _heap.entries[j];
// Store the value of the child
uint256 childValue;
if (target > j) {
// The parent has two childs 👨👧👦
// Load right child value
uint256 rightChild = _heap.entries[j + 1];
// Compare the left and right child.
// if the rightChild is greater, then point j to it's index
// and save the value
if (leftChild < rightChild) {
childValue = rightChild;
j = j + 1;
} else {
// The left child is greater
childValue = leftChild;
}
} else {
// The parent has a single child 👨👦
childValue = leftChild;
}
// Check if the child has a lower value
if (_val > childValue) {
break;
}
// else swap the value
(_heap.entries[ind], _heap.entries[j]) = (childValue, _val);
// Update moved Index
_heap.index[decodeAddress(childValue)] = ind;
// and let's keep going down the heap
ind = j;
}
}
}
// File: contracts/Heap.sol
pragma solidity ^0.5.10;
contract Heap is Ownable {
using AddressMinHeap for AddressMinHeap.Heap;
// heap
AddressMinHeap.Heap private heap;
// Heap events
event JoinHeap(address indexed _address, uint256 _balance, uint256 _prevSize);
event LeaveHeap(address indexed _address, uint256 _balance, uint256 _prevSize);
uint256 public constant TOP_SIZE = 512;
constructor() public {
heap.initialize();
}
function topSize() external pure returns (uint256) {
return TOP_SIZE;
}
function addressAt(uint256 _i) external view returns (address addr) {
(addr, ) = heap.entry(_i);
}
function indexOf(address _addr) external view returns (uint256) {
return heap.index[_addr];
}
function entry(uint256 _i) external view returns (address, uint256) {
return heap.entry(_i);
}
function top() external view returns (address, uint256) {
return heap.top();
}
function size() external view returns (uint256) {
return heap.size();
}
function update(address _addr, uint256 _new) external onlyOwner {
uint256 _size = heap.size();
// If the heap is empty
// join the _addr
if (_size == 0) {
emit JoinHeap(_addr, _new, 0);
heap.insert(_addr, _new);
return;
}
// Load top value of the heap
(, uint256 lastBal) = heap.top();
// If our target address already is in the heap
if (heap.has(_addr)) {
// Update the target address value
heap.update(_addr, _new);
// If the new value is 0
// always pop the heap
// we updated the heap, so our address should be on top
if (_new == 0) {
heap.popTop();
emit LeaveHeap(_addr, 0, _size);
}
} else {
// IF heap is full or new balance is higher than pop heap
if (_new != 0 && (_size < TOP_SIZE || lastBal < _new)) {
// If heap is full pop heap
if (_size >= TOP_SIZE) {
(address _poped, uint256 _balance) = heap.popTop();
emit LeaveHeap(_poped, _balance, _size);
}
// Insert new value
heap.insert(_addr, _new);
emit JoinHeap(_addr, _new, _size);
}
}
}
}
// File: contracts/ShuffleToken.sol
pragma solidity ^0.5.10;
contract ShuffleToken is Ownable, GasPump, IERC20 {
using DistributedStorage for bytes32;
using SafeMath for uint256;
// Shuffle events
event Winner(address indexed _addr, uint256 _value);
// Managment events
event SetName(string _prev, string _new);
event SetExtraGas(uint256 _prev, uint256 _new);
event SetHeap(address _prev, address _new);
event WhitelistFrom(address _addr, bool _whitelisted);
event WhitelistTo(address _addr, bool _whitelisted);
uint256 public totalSupply;
bytes32 private constant BALANCE_KEY = keccak256("balance");
// game
uint256 public constant FEE = 100;
// metadata
string public name = "Shuffle.Monster V3";
string public constant symbol = "SHUF";
uint8 public constant decimals = 18;
// fee whitelist
mapping(address => bool) public whitelistFrom;
mapping(address => bool) public whitelistTo;
// heap
Heap public heap;
// internal
uint256 public extraGas;
bool inited;
function init(
address _to,
uint256 _amount
) external {
// Only init once
assert(!inited);
inited = true;
// Sanity checks
assert(totalSupply == 0);
assert(address(heap) == address(0));
// Create Heap
heap = new Heap();
emit SetHeap(address(0), address(heap));
// Init contract variables and mint
// entire token balance
extraGas = 15;
emit SetExtraGas(0, extraGas);
emit Transfer(address(0), _to, _amount);
_setBalance(_to, _amount);
totalSupply = _amount;
}
///
// Storage access functions
///
// Getters
function _toKey(address a) internal pure returns (bytes32) {
return bytes32(uint256(a));
}
function _balanceOf(address _addr) internal view returns (uint256) {
return uint256(_toKey(_addr).read(BALANCE_KEY));
}
function _allowance(address _addr, address _spender) internal view returns (uint256) {
return uint256(_toKey(_addr).read(keccak256(abi.encodePacked("allowance", _spender))));
}
function _nonce(address _addr, uint256 _cat) internal view returns (uint256) {
return uint256(_toKey(_addr).read(keccak256(abi.encodePacked("nonce", _cat))));
}
// Setters
function _setAllowance(address _addr, address _spender, uint256 _value) internal {
_toKey(_addr).write(keccak256(abi.encodePacked("allowance", _spender)), bytes32(_value));
}
function _setNonce(address _addr, uint256 _cat, uint256 _value) internal {
_toKey(_addr).write(keccak256(abi.encodePacked("nonce", _cat)), bytes32(_value));
}
function _setBalance(address _addr, uint256 _balance) internal {
_toKey(_addr).write(BALANCE_KEY, bytes32(_balance));
heap.update(_addr, _balance);
}
///
// Internal methods
///
function _isWhitelisted(address _from, address _to) internal view returns (bool) {
return whitelistFrom[_from]||whitelistTo[_to];
}
function _random(address _s1, uint256 _s2, uint256 _s3, uint256 _max) internal pure returns (uint256) {
uint256 rand = uint256(keccak256(abi.encodePacked(_s1, _s2, _s3)));
return rand % (_max + 1);
}
function _pickWinner(address _from, uint256 _value) internal returns (address winner) {
// Get order of magnitude of the tx
uint256 magnitude = Math.orderOfMagnitude(_value);
// Pull nonce for a given order of magnitude
uint256 nonce = _nonce(_from, magnitude);
_setNonce(_from, magnitude, nonce + 1);
// pick entry from heap
winner = heap.addressAt(_random(_from, nonce, magnitude, heap.size() - 1));
}
function _transferFrom(address _operator, address _from, address _to, uint256 _value, bool _payFee) internal {
// If transfer amount is zero
// emit event and stop execution
if (_value == 0) {
emit Transfer(_from, _to, 0);
return;
}
// Load sender balance
uint256 balanceFrom = _balanceOf(_from);
require(balanceFrom >= _value, "balance not enough");
// Check if operator is sender
if (_from != _operator) {
// If not, validate allowance
uint256 allowanceFrom = _allowance(_from, _operator);
// If allowance is not 2 ** 256 - 1, consume allowance
if (allowanceFrom != uint(-1)) {
// Check allowance and save new one
require(allowanceFrom >= _value, "allowance not enough");
_setAllowance(_from, _operator, allowanceFrom.sub(_value));
}
}
// Calculate receiver balance
// initial receive is full value
uint256 receive = _value;
uint256 burn = 0;
uint256 shuf = 0;
// Change sender balance
_setBalance(_from, balanceFrom.sub(_value));
// If the transaction is not whitelisted
// or if sender requested to pay the fee
// calculate fees
if (_payFee || !_isWhitelisted(_from, _to)) {
// Fee is the same for BURN and SHUF
// If we are sending value one
// give priority to BURN
burn = _value.divRound(FEE);
shuf = _value == 1 ? 0 : burn;
// Subtract fees from receiver amount
receive = receive.sub(burn.add(shuf));
// Burn tokens
totalSupply = totalSupply.sub(burn);
emit Transfer(_from, address(0), burn);
// Shuffle tokens
// Pick winner pseudo-randomly
address winner = _pickWinner(_from, _value);
// Transfer balance to winner
_setBalance(winner, _balanceOf(winner).add(shuf));
emit Winner(winner, shuf);
emit Transfer(_from, winner, shuf);
}
// Sanity checks
// no tokens where created
assert(burn.add(shuf).add(receive) == _value);
// Add tokens to receiver
_setBalance(_to, _balanceOf(_to).add(receive));
emit Transfer(_from, _to, receive);
}
///
// Managment
///
function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistTo(_addr, _whitelisted);
whitelistTo[_addr] = _whitelisted;
}
function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistFrom(_addr, _whitelisted);
whitelistFrom[_addr] = _whitelisted;
}
function setName(string calldata _name) external onlyOwner {
emit SetName(name, _name);
name = _name;
}
function setExtraGas(uint256 _gas) external onlyOwner {
emit SetExtraGas(extraGas, _gas);
extraGas = _gas;
}
function setHeap(Heap _heap) external onlyOwner {
emit SetHeap(address(heap), address(_heap));
heap = _heap;
}
/////
// Heap methods
/////
function topSize() external view returns (uint256) {
return heap.topSize();
}
function heapSize() external view returns (uint256) {
return heap.size();
}
function heapEntry(uint256 _i) external view returns (address, uint256) {
return heap.entry(_i);
}
function heapTop() external view returns (address, uint256) {
return heap.top();
}
function heapIndex(address _addr) external view returns (uint256) {
return heap.indexOf(_addr);
}
function getNonce(address _addr, uint256 _cat) external view returns (uint256) {
return _nonce(_addr, _cat);
}
/////
// ERC20
/////
function balanceOf(address _addr) external view returns (uint256) {
return _balanceOf(_addr);
}
function allowance(address _addr, address _spender) external view returns (uint256) {
return _allowance(_addr, _spender);
}
function approve(address _spender, uint256 _value) external returns (bool) {
emit Approval(msg.sender, _spender, _value);
_setAllowance(msg.sender, _spender, _value);
return true;
}
function transfer(address _to, uint256 _value) external requestGas(extraGas) returns (bool) {
_transferFrom(msg.sender, msg.sender, _to, _value, false);
return true;
}
function transferWithFee(address _to, uint256 _value) external requestGas(extraGas) returns (bool) {
_transferFrom(msg.sender, msg.sender, _to, _value, true);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) external requestGas(extraGas) returns (bool) {
_transferFrom(msg.sender, _from, _to, _value, false);
return true;
}
function transferFromWithFee(address _from, address _to, uint256 _value) external requestGas(extraGas) returns (bool) {
_transferFrom(msg.sender, _from, _to, _value, true);
return true;
}
}
// File: contracts/utils/SigUtils.sol
pragma solidity ^0.5.10;
library SigUtils {
/**
@dev Recovers address who signed the message
@param _hash operation ethereum signed message hash
@param _signature message `hash` signature
*/
function ecrecover2(
bytes32 _hash,
bytes memory _signature
) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
/* solium-disable-next-line */
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(add(_signature, 65)), 255)
}
if (v < 27) {
v += 27;
}
return ecrecover(
_hash,
v,
r,
s
);
}
}
// File: contracts/utils/SafeCast.sol
pragma solidity ^0.5.10;
library SafeCast {
function toUint96(uint256 _a) internal pure returns (uint96) {
require(_a <= 2 ** 96 - 1, "cast uint96 overflow");
return uint96(_a);
}
}
// File: contracts/Airdrop.sol
pragma solidity ^0.5.10;
contract Airdrop is Ownable, ReentrancyGuard {
using IsContract for address payable;
using SafeCast for uint256;
using SafeMath for uint256;
ShuffleToken public shuffleToken;
// Managment
uint64 public maxClaimedBy = 0;
uint256 public refsCut;
mapping(address => uint256) public customMaxClaimedBy;
bool public paused;
event SetMaxClaimedBy(uint256 _max);
event SetCustomMaxClaimedBy(address _address, uint256 _max);
event SetSigner(address _signer, bool _active);
event SetMigrator(address _migrator, bool _active);
event SetFuse(address _fuse, bool _active);
event SetPaused(bool _paused);
event SetRefsCut(uint256 _prev, uint256 _new);
event Claimed(address _by, address _to, address _signer, uint256 _value, uint256 _claimed);
event RefClaim(address _ref, uint256 _val);
event ClaimedOwner(address _owner, uint256 _tokens);
uint256 public constant MINT_AMOUNT = 1000000 * 10 ** 18;
uint256 public constant SHUFLE_BY_ETH = 150;
uint256 public constant MAX_CLAIM_ETH = 10 ether;
mapping(address => bool) public isSigner;
mapping(address => bool) public isMigrator;
mapping(address => bool) public isFuse;
mapping(address => uint256) public claimed;
mapping(address => uint256) public numberClaimedBy;
constructor(ShuffleToken _token) public {
shuffleToken = _token;
shuffleToken.init(address(this), MINT_AMOUNT);
emit SetMaxClaimedBy(maxClaimedBy);
}
// ///
// Managment
// ///
modifier notPaused() {
require(!paused, "contract is paused");
_;
}
function setMaxClaimedBy(uint64 _max) external onlyOwner {
maxClaimedBy = _max;
emit SetMaxClaimedBy(_max);
}
function setSigner(address _signer, bool _active) external onlyOwner {
isSigner[_signer] = _active;
emit SetSigner(_signer, _active);
}
function setMigrator(address _migrator, bool _active) external onlyOwner {
isMigrator[_migrator] = _active;
emit SetMigrator(_migrator, _active);
}
function setFuse(address _fuse, bool _active) external onlyOwner {
isFuse[_fuse] = _active;
emit SetFuse(_fuse, _active);
}
function setSigners(address[] calldata _signers, bool _active) external onlyOwner {
for (uint256 i = 0; i < _signers.length; i++) {
address signer = _signers[i];
isSigner[signer] = _active;
emit SetSigner(signer, _active);
}
}
function setCustomMaxClaimedBy(address _address, uint256 _max) external onlyOwner {
customMaxClaimedBy[_address] = _max;
emit SetCustomMaxClaimedBy(_address, _max);
}
function setRefsCut(uint256 _val) external onlyOwner {
emit SetRefsCut(refsCut, _val);
refsCut = _val;
}
function pause() external {
require(
isFuse[msg.sender] ||
msg.sender == owner ||
isMigrator[msg.sender] ||
isSigner[msg.sender],
"not authorized"
);
paused = true;
emit SetPaused(true);
}
function start() external onlyOwner {
emit SetPaused(false);
paused = false;
}
// ///
// Airdrop
// ///
function _selfBalance() internal view returns (uint256) {
return shuffleToken.balanceOf(address(this));
}
function checkFallback(address _to) private returns (bool success) {
/* solium-disable-next-line */
(success, ) = _to.call.value(1)("");
}
function claim(
address _to,
address _ref,
uint256 _val,
bytes calldata _sig
) external notPaused nonReentrant {
// Load values
uint96 val = _val.toUint96();
// Validate signature
bytes32 _hash = keccak256(abi.encodePacked(_to, val));
address signer = SigUtils.ecrecover2(_hash, _sig);
require(isSigner[signer], "signature not valid");
// Prepare claim amount
uint256 balance = _selfBalance();
uint256 claimVal = Math.min(
balance,
Math.min(
val,
MAX_CLAIM_ETH
).mult(SHUFLE_BY_ETH)
);
// Sanity checks
assert(claimVal <= SHUFLE_BY_ETH.mult(val));
assert(claimVal <= MAX_CLAIM_ETH.mult(SHUFLE_BY_ETH));
assert(claimVal.div(SHUFLE_BY_ETH) <= MAX_CLAIM_ETH);
assert(
claimVal.div(SHUFLE_BY_ETH) == _val ||
claimVal.div(SHUFLE_BY_ETH) == MAX_CLAIM_ETH ||
claimVal == balance
);
// Claim, only once
require(claimed[_to] == 0, "already claimed");
claimed[_to] = claimVal;
// External claim checks
if (msg.sender != _to) {
// Validate max external claims
uint256 _numberClaimedBy = numberClaimedBy[msg.sender].add(1);
require(_numberClaimedBy <= Math.max(maxClaimedBy, customMaxClaimedBy[msg.sender]), "max claim reached");
numberClaimedBy[msg.sender] = _numberClaimedBy;
// Check if _to address can receive ETH
require(checkFallback(_to), "_to address can't receive tokens");
}
// Transfer Shuffle token, paying fee
shuffleToken.transferWithFee(_to, claimVal);
// Emit events
emit Claimed(msg.sender, _to, signer, val, claimVal);
// Ref links
if (refsCut != 0) {
// Only valid for self-claims
if (msg.sender == _to && _ref != address(0)) {
// Calc transfer extra
uint256 extra = claimVal.mult(refsCut).div(10000);
// Ignore ref fee if Airdrop balance is not enought
if (_selfBalance() >= extra) {
shuffleToken.transferWithFee(_ref, extra);
emit RefClaim(_ref, extra);
// Sanity checks
assert(extra <= MAX_CLAIM_ETH.mult(SHUFLE_BY_ETH));
assert(extra <= claimVal);
assert(extra == (claimVal * refsCut) / 10000);
}
}
}
// If contract is empty, perform self destruct
if (balance == claimVal && _selfBalance() == 0) {
selfdestruct(address(uint256(owner)));
}
}
// Migration methods
event Migrated(address _addr, uint256 _balance);
mapping(address => uint256) public migrated;
function migrate(address _addr, uint256 _balance, uint256 _require) external notPaused {
// Check if migrator is a migrator
require(isMigrator[msg.sender], "only migrator can migrate");
// Check if expected migrated matches current migrated
require(migrated[_addr] == _require, "_require prev migrate failed");
// Save migrated amount
migrated[_addr] = migrated[_addr].add(_balance);
// Transfer tokens and emit event
shuffleToken.transfer(_addr, _balance);
emit Migrated(_addr, _balance);
}
function fund() external payable { }
} | RemoveMax pops off the root element of the heap (the highest value here) and rebalances the heap Ensure the heap exists take the root value of the heap Takes the last element of the array and put it at the root Delete the last element from the array Start at the top Bubble down Update index | function popTop(Heap storage _heap) internal returns(address _addr, uint256 _value) {
uint256 heapLength = _heap.entries.length;
require(heapLength > 1, "The heap does not exists");
(_addr, _value) = decode(_heap.entries[1]);
_heap.index[_addr] = 0;
if (heapLength == 2) {
_heap.entries.length = 1;
uint256 val = _heap.entries[heapLength - 1];
_heap.entries[1] = val;
_heap.entries.length = heapLength - 1;
uint256 ind = 1;
ind = _heap.bubbleDown(ind, val);
_heap.index[decodeAddress(val)] = ind;
}
}
| 881,554 | [
1,
3288,
2747,
28518,
3397,
326,
1365,
930,
434,
326,
10500,
261,
5787,
9742,
460,
2674,
13,
471,
283,
70,
26488,
326,
10500,
7693,
326,
10500,
1704,
4862,
326,
1365,
460,
434,
326,
10500,
23004,
326,
1142,
930,
434,
326,
526,
471,
1378,
518,
622,
326,
1365,
2504,
326,
1142,
930,
628,
326,
526,
3603,
622,
326,
1760,
605,
14787,
2588,
2315,
770,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1843,
3401,
12,
15648,
2502,
389,
25506,
13,
2713,
1135,
12,
2867,
389,
4793,
16,
2254,
5034,
389,
1132,
13,
288,
203,
3639,
2254,
5034,
10500,
1782,
273,
389,
25506,
18,
8219,
18,
2469,
31,
203,
3639,
2583,
12,
25506,
1782,
405,
404,
16,
315,
1986,
10500,
1552,
486,
1704,
8863,
203,
203,
3639,
261,
67,
4793,
16,
389,
1132,
13,
273,
2495,
24899,
25506,
18,
8219,
63,
21,
19226,
203,
3639,
389,
25506,
18,
1615,
63,
67,
4793,
65,
273,
374,
31,
203,
203,
3639,
309,
261,
25506,
1782,
422,
576,
13,
288,
203,
5411,
389,
25506,
18,
8219,
18,
2469,
273,
404,
31,
203,
5411,
2254,
5034,
1244,
273,
389,
25506,
18,
8219,
63,
25506,
1782,
300,
404,
15533,
203,
5411,
389,
25506,
18,
8219,
63,
21,
65,
273,
1244,
31,
203,
203,
5411,
389,
25506,
18,
8219,
18,
2469,
273,
10500,
1782,
300,
404,
31,
203,
203,
5411,
2254,
5034,
1547,
273,
404,
31,
203,
203,
5411,
1547,
273,
389,
25506,
18,
70,
14787,
4164,
12,
728,
16,
1244,
1769,
203,
203,
5411,
389,
25506,
18,
1615,
63,
3922,
1887,
12,
1125,
25887,
273,
1547,
31,
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
] |
./full_match/80001/0xBf465673a080f26ce0AA913479659a40ea2fD5Dd/sources/contracts/NotionChatToken.sol | Override function to return default token URI for every token | function tokenURI(uint256 tokenId) public view override returns (string memory) {
return defaultTokenURI;
}
| 9,485,880 | [
1,
6618,
445,
358,
327,
805,
1147,
3699,
364,
3614,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
282,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
4202,
327,
805,
1345,
3098,
31,
203,
282,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x10fbB7cfaD75E76f85074F3e2b35D6da6e6f8b49/sources/https_/github.com/chelbukhov/ERC1155/blob/main/contracts/tokens/ERC1155/ERC1155Metadata.sol | * @notice Will update the base URL of token's URI @param _newBaseMetadataURI New base URL of token's URI/ | function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal {
baseMetadataURI = _newBaseMetadataURI;
}
| 782,913 | [
1,
13670,
1089,
326,
1026,
1976,
434,
1147,
1807,
3699,
225,
389,
2704,
2171,
2277,
3098,
1166,
1026,
1976,
434,
1147,
1807,
3699,
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
] | [
1,
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,
225,
445,
389,
542,
2171,
2277,
3098,
12,
1080,
3778,
389,
2704,
2171,
2277,
3098,
13,
2713,
288,
203,
565,
1026,
2277,
3098,
273,
389,
2704,
2171,
2277,
3098,
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
] |
./full_match/1/0x4074ca0e06726A4b8eDDAb069d94419aD68046c9/sources/browser/ZAIAdvancer.sol | CHANGE START TIME HERE
| return ((_targetEpoch * 1800) + 1608422400); | 8,402,754 | [
1,
14473,
10485,
8721,
670,
29340,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
327,
14015,
67,
3299,
14638,
380,
6549,
713,
13,
397,
25430,
5193,
23622,
713,
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
] |
./partial_match/1/0xF0d8681671B987eE3e3E2F5285dc1b39BD1BFaa5/sources/PaymentToken.sol | SPDX-License-Identifier: MIT | import { EnumerableSet } from "./EnumerableSet.sol";
| 4,220,511 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5666,
288,
6057,
25121,
694,
289,
628,
25165,
3572,
25121,
694,
18,
18281,
14432,
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
] |
// Sources flattened with hardhat v2.6.4 https://hardhat.org
// File openzeppelin-solidity/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File openzeppelin-solidity/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File openzeppelin-solidity/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File openzeppelin-solidity/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File openzeppelin-solidity/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File openzeppelin-solidity/contracts/utils/[email protected]
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-solidity/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File openzeppelin-solidity/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File openzeppelin-solidity/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File openzeppelin-solidity/contracts/utils/cryptography/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File contracts/ArpeggiGenesisFinal.sol
pragma solidity >=0.8.0 <0.9.0;
// Arpeggi Studio Genesis is the first on-chain music creation platform. All data and instructions to recreate your Arpeggi song reside on the Ethereum blockchain.
//
// To recreate your song, you will need to retrieve two compressed files from the chain: "samples" and "scripts".
//
// STEPS TO RETRIEVE "samples":
// - The mp3 samples to play your song have been packaged together as a single compressed file, split into pieces, and stored in transaction data on-chain.
// - Make a new file on your local, 'samples.hex,' to piece together the samples hex data gathered from the contract.
// - Query the contract for the sampleCount - this is the number of pieces of the samples file. You will need all of them.
// - Pass in the sampleCount starting with 0 into the _samples read method of the ArpeggiStudioGenesis contract, this is will return a transaction hash.
// - Use the transaction hash to find the sample transaction on Etherscan.
// - Copy the "Input Data" field of this the transaction to the end of your local 'samples.hex' file, removing the leading 0x at the beggining of the input data.
// - Repeat the last three steps, incrementing the sampleConut in the _samples read method and appending to the end of your local file data until you have copied all the sample data.
// - Convert the local file from hex to binary using a command line tool. Example command: xxd -r -p samples.hex > samples.zip
// - Follow the instructions to retrieve the scripts below.
//
// STEPS TO RETRIEVE "scripts":
// - The song player script is written in JavaScript, split into pieces, and stored on chain.
// - Make a new file on your local, 'scripts.hex' to piece together the script hex data gathered from the contract
// - Query the contract for the scriptCount - this is the number of pieces of the player script. It's likely to be one transaction.
// - Pass in the scriptCount starting with 0 into the _scripts read method of the ArpeggiStudioGenesis contract, this is will return a transaction hash.
// - Use the transaction hash to find the script transaction on Etherscan
// - Copy the "Input Data" field of this the transaction to your local 'scripts.hex' file, removing the leading 0x at the beggining of the input data.
// - Repeat these last three steps, incrementing the scriptCount in the _scripts method and appending to the end of your local file data until you have copied all the script data.
// - Convert the local file from hex to binary using a command line tool. Example command: xxd -r -p scripts.hex > scripts.zip
//
// PLAYING YOUR SONG:
// - Extract the scripts and the samples files. This is all of the data required to play your song.
// - Follow the instructions in the scripts/README file to play your song!
contract ArpeggiStudioGenesis is
ERC721,
Ownable
{
////////////////// STRUCT //////////////////
/**
* @dev Struct for Pass and Song
*/
struct Pass {
string title;
string artist;
bytes composition;
uint mintTime;
address artistAddress;
}
////////////////// CONSTANTS //////////////////
uint256 public constant MAX_PASSES = 600;
uint256 public constant PRESALE_MINT_PRICE = 0.25 ether;
uint256 public constant GENERAL_MINT_PRICE = 0.3 ether;
/**
* @dev Max number of Passes that the contract owner can mint.
*/
uint256 public constant CREATORS_NUM_PASSES = 64;
/**
* @dev Max number of Passes that the contract owner can mint.
*/
uint256 public constant DEVELOPERS_NUM_PASSES = 24;
////////////////// STORAGE //////////////////
uint256 public _numMinted = 0;
/**
* @dev Custom pause functionality for Creator/Developer Reserve Mint
*/
bool private _paused = true;
bool public _onlyEarlyAccess = true;
address public immutable CREATORS_RESERVE;
address public immutable DEVELOPERS_RESERVE;
/**
* @dev Base URL for external_url metadata field.
*/
string private _basePassExternalUrl = "http://www.arpeggi.io/metadata/pass/";
/**
* @dev Base URL for external_url metadata field.
*/
string private _baseSongExternalUrl = "http://www.arpeggi.io/metadata/song/";
/**
* @dev All existing Passes.
*/
mapping(uint256 => Pass) public _passes;
/**
* @dev Addresses with early minting access.
*/
mapping(address => bool) private _earlyAccess;
/**
* @dev For setting scripts. When locked it is irreversible.
*/
bool private _locked = false;
/**
* @dev The scripts used to render a composition from a token
*/
mapping (uint256 => string) public _scripts;
uint256 public scriptCount = 0;
/**
* @dev The samples used to play a song
*/
mapping (uint256 => string) public _samples;
uint256 public sampleCount = 0;
////////////////// CONSTRUCTOR //////////////////
constructor(
address creatorsReserve,
address developersReserve
)
ERC721(
"Arpeggi Genesis Studio Pass",
"ARPEGGI"
)
{
CREATORS_RESERVE = creatorsReserve;
DEVELOPERS_RESERVE = developersReserve;
}
////////////////// MODIFIERS //////////////////
/**
* @dev Modifier to make a function callable only when the contract is not paused.
* Contract must not be paused
*/
modifier whenNotPaused() {
require(!isPaused(), "Paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
* Contract must be paused.
*/
modifier whenPaused() {
require(isPaused(), "Paused");
_;
}
/**
* @dev Lock functionality to lock scripts/samples after uploading
*/
modifier onlyUnlocked() {
require(!_locked, "Contract is locked");
_;
}
////////////////// EXTERNAL ONLY-OWNER FUNCTIONS //////////////////
/**
* @dev Returns to unpaused state. The contract must be paused.
*/
function unpause()
external
onlyOwner
whenPaused
{
_paused = false;
}
/**
* @dev Function to lock on-chain scripts and samples
*/
function setLocked()
external
onlyOwner
onlyUnlocked
{
_locked = true;
}
/**
* @dev Add a new section of the script
* @param script String value of script or pointer
*/
function addScript(
string memory script
)
external
onlyOwner
onlyUnlocked
{
_scripts[scriptCount] = script;
scriptCount++;
}
/**
* @dev Overwrite a script section at a particular index
* @param script String value of script or pointer
* @param index Index of the script to replace
*/
function updateScript(
string memory script,
uint256 index
)
external
onlyOwner
onlyUnlocked
{
require(index < scriptCount, "Index out of bounds");
_scripts[index] = script;
}
/**
* @dev Reset script index to zero, caller must be owner and the contract unlocked
*/
function resetScriptCount()
external
onlyOwner
onlyUnlocked
{
scriptCount = 0;
}
/**
* @dev Add a new section of the sample
* @param sample String value of sample or pointer
*/
function addSample(
string memory sample
)
external
onlyOwner
onlyUnlocked
{
_samples[sampleCount] = sample;
sampleCount++;
}
/**
* @dev Reset sample index to zero, caller must be owner and the contract unlocked
*/
function resetSampleCount()
external
onlyOwner
onlyUnlocked
{
sampleCount = 0;
}
/**
* @dev Set the _onlyEarlyAccess flag.
*/
function setOnlyEarlyAccess(
bool to
)
external
onlyOwner
{
_onlyEarlyAccess = to;
}
/**
* @dev Set early-access granting or revocation for the addresses. eg. ["0x12345"]
*/
function setEarlyAccessGrants(
address[] calldata addresses,
bool hasAccess
)
external
onlyOwner
{
for (uint i = 0; i < addresses.length; i++) {
_earlyAccess[addresses[i]] = hasAccess;
}
}
/**
* @dev Allocate passes to Arpeggi Creators Reserve wallet
*/
function mintCreatorsReserve()
external
onlyOwner
whenPaused
{
for (uint i=0; i < CREATORS_NUM_PASSES; i++) {
_mintToken(CREATORS_RESERVE);
}
}
/**
* @dev Allocate passes to Arpeggi Creators Reserve wallet
*/
function mintDevelopersReserve()
external
onlyOwner
whenPaused
{
for (uint i=0; i < DEVELOPERS_NUM_PASSES; i++) {
_mintToken(DEVELOPERS_RESERVE);
}
}
/**
* @dev Withdraw funds from contract to owner
*/
function withdraw() public onlyOwner {
payable(owner()).transfer(address(this).balance);
}
////////////////// EXTERNAL FUNCTIONS //////////////////
/**
* @dev Mint a lab pass
*/
function mint()
external
payable
whenNotPaused
{
require(_numMinted < MAX_PASSES, "No More Passes Left");
require(
(_onlyEarlyAccess && PRESALE_MINT_PRICE == msg.value) || (!_onlyEarlyAccess && GENERAL_MINT_PRICE == msg.value),
"Incorrect Ether value.");
require(!_isContract(msg.sender), "Can't mint from a contract smh");
require(
!_onlyEarlyAccess || _earlyAccess[msg.sender],
"You are not approved for presale"
);
_mintToken(msg.sender);
if (_onlyEarlyAccess) {
_earlyAccess[msg.sender] = false;
}
}
function pressSong(
uint256 _tokenId,
bytes calldata _composition,
string calldata _title,
string calldata _artist
)
external
whenNotPaused
{
require(_isApprovedOrOwner(_msgSender(), _tokenId));
require(_passes[_tokenId].mintTime == 0, "Your Studio Pass has already been used");
_pressSongToken(msg.sender, _tokenId, _title, _artist, _composition);
}
////////////////// PUBLIC ONLY-OWNER FUNCTIONS //////////////////
/**
* @dev Set the base URL for external_url metadata field.
*/
function setBasePassExternalUrl(
string memory url
)
public
onlyOwner
{
_basePassExternalUrl = url;
}
/**
* @dev Set the base URL for external_url metadata field.
*/
function setBaseSongExternalUrl(
string memory url
)
public
onlyOwner
{
_baseSongExternalUrl = url;
}
////////////////// PUBLIC FUNCTIONS //////////////////
/**
* @dev Returns data URI of token metadata.
*/
function tokenURI(
uint256 _tokenId
)
public
override
view
returns (string memory)
{
if (_passes[_tokenId].mintTime == 0) {
return string(abi.encodePacked(_basePassExternalUrl, Strings.toString(_tokenId)));
}
else {
return string(abi.encodePacked(_baseSongExternalUrl, Strings.toString(_tokenId)));
}
}
/**
* @dev Checks an address to see if it has early access
*/
function hasEarlyAccess(address _address) public view returns (bool) {
return _earlyAccess[_address] == true;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function isPaused()
public
view
returns (bool)
{
return _paused;
}
////////////////// INTERNAL FUNCTIONS //////////////////
function _mintToken(
address _to
)
internal
{
_numMinted++;
_safeMint(_to, _numMinted);
}
function _pressSongToken(
address _artistAddress,
uint256 _tokenId,
string calldata _title,
string calldata _artist,
bytes calldata _composition
)
internal
returns(uint256 _songToken)
{
_passes[_tokenId].title = _title;
_passes[_tokenId].artist = _artist;
_passes[_tokenId].composition = _composition;
_passes[_tokenId].mintTime = block.timestamp;
_passes[_tokenId].artistAddress = _artistAddress;
return _tokenId;
}
/**
* @dev Function to check if an address is a contract for minting
*/
function _isContract(
address _addr
)
internal
view
returns (bool)
{
uint32 _size;
assembly {
_size:= extcodesize(_addr)
}
return (_size > 0);
}
} | * @dev Returns to unpaused state. The contract must be paused./ | function unpause()
external
onlyOwner
whenPaused
{
_paused = false;
}
| 14,709,590 | [
1,
1356,
358,
640,
8774,
3668,
919,
18,
1021,
6835,
1297,
506,
17781,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
640,
19476,
1435,
203,
3639,
3903,
203,
3639,
1338,
5541,
203,
3639,
1347,
28590,
203,
565,
288,
203,
3639,
389,
8774,
3668,
273,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8d25b3843e3918D0F8d1687f0D3C733065D8d32f/sources/oToken.sol | * @notice Called by anyone holding the oTokens and underlying during the exercise window i.e. from `expiry - windowSize` time to `expiry` time. The caller transfers in their oTokens and corresponding amount of underlying and gets `strikePrice oTokens` amount of collateral out. The collateral paid out is taken from the each vault owner starting with the first and iterating until the oTokens to exercise are found. NOTE: This uses a for loop and hence could run out of gas if the array passed in is too big! @param oTokensToExercise the number of oTokens being exercised. @param vaultsToExerciseFrom the array of vaults to exercise from./ | function exercise(
uint256 oTokensToExercise,
address payable[] memory vaultsToExerciseFrom
) public payable {
for (uint256 i = 0; i < vaultsToExerciseFrom.length; i++) {
address payable vaultOwner = vaultsToExerciseFrom[i];
require(
hasVault(vaultOwner),
"Cannot exercise from a vault that doesn't exist"
);
Vault storage vault = vaults[vaultOwner];
if (oTokensToExercise == 0) {
return;
_exercise(oTokensToExercise, vaultOwner);
return;
oTokensToExercise = oTokensToExercise.sub(vault.oTokensIssued);
_exercise(vault.oTokensIssued, vaultOwner);
}
}
require(
oTokensToExercise == 0,
"Specified vaults have insufficient collateral"
);
}
| 16,155,336 | [
1,
8185,
635,
1281,
476,
19918,
326,
320,
5157,
471,
6808,
4982,
326,
24165,
2742,
277,
18,
73,
18,
628,
1375,
22409,
300,
27064,
68,
813,
358,
1375,
22409,
68,
813,
18,
1021,
4894,
29375,
316,
3675,
320,
5157,
471,
4656,
3844,
434,
6808,
471,
5571,
1375,
701,
2547,
5147,
225,
320,
5157,
68,
3844,
434,
4508,
2045,
287,
596,
18,
1021,
4508,
2045,
287,
30591,
596,
353,
9830,
628,
326,
1517,
9229,
3410,
5023,
598,
326,
1122,
471,
13099,
3180,
326,
320,
5157,
358,
24165,
854,
1392,
18,
5219,
30,
1220,
4692,
279,
364,
2798,
471,
20356,
3377,
1086,
596,
434,
16189,
309,
326,
526,
2275,
316,
353,
4885,
5446,
5,
225,
320,
5157,
774,
424,
20603,
326,
1300,
434,
320,
5157,
3832,
431,
12610,
5918,
18,
225,
9229,
11634,
424,
20603,
1265,
326,
526,
434,
9229,
87,
358,
24165,
628,
18,
19,
2,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [
1,
565,
445,
24165,
12,
203,
3639,
2254,
5034,
320,
5157,
774,
424,
20603,
16,
203,
3639,
1758,
8843,
429,
8526,
3778,
9229,
11634,
424,
20603,
1265,
203,
565,
262,
1071,
8843,
429,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
9229,
11634,
424,
20603,
1265,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1758,
8843,
429,
9229,
5541,
273,
9229,
11634,
424,
20603,
1265,
63,
77,
15533,
203,
5411,
2583,
12,
203,
7734,
711,
12003,
12,
26983,
5541,
3631,
203,
7734,
315,
4515,
24165,
628,
279,
9229,
716,
3302,
1404,
1005,
6,
203,
5411,
11272,
203,
5411,
17329,
2502,
9229,
273,
9229,
87,
63,
26983,
5541,
15533,
203,
5411,
309,
261,
83,
5157,
774,
424,
20603,
422,
374,
13,
288,
203,
7734,
327,
31,
203,
7734,
389,
8913,
30708,
12,
83,
5157,
774,
424,
20603,
16,
9229,
5541,
1769,
203,
7734,
327,
31,
203,
7734,
320,
5157,
774,
424,
20603,
273,
320,
5157,
774,
424,
20603,
18,
1717,
12,
26983,
18,
83,
5157,
7568,
5957,
1769,
203,
7734,
389,
8913,
30708,
12,
26983,
18,
83,
5157,
7568,
5957,
16,
9229,
5541,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
2583,
12,
203,
5411,
320,
5157,
774,
424,
20603,
422,
374,
16,
203,
5411,
315,
17068,
9229,
87,
1240,
2763,
11339,
4508,
2045,
287,
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
] |
./full_match/80001/0x5d12a2b9937B0F7EA99e5a13Ad89AaB05Ef7288b/sources/contracts/Settings.sol | * Toggle Custom URL for Future Mints*/ | function toggleAggregator() public virtual onlyOwner {
getSettings().useAggregator = !getSettings().useAggregator;
}
| 853,511 | [
1,
17986,
6082,
1976,
364,
9108,
490,
28142,
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,
10486,
17711,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
18283,
7675,
1202,
17711,
273,
401,
588,
2628,
7675,
1202,
17711,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPLv3
pragma solidity 0.8.4;
interface IToken {
function mint(address _receiver, uint256 _amount) external;
function burn(address _receiver, uint256 _amount) external;
}
/// @notice Contract that defines GRO DAOs' tokenomics - Contracts set below
/// are allowed to mint tokens based on predefined quotas. This contract is
/// intrinsically tied to the GRO Dao token, and is the only contract that is
/// allowed to mint and burn tokens.
contract GRODistributer {
// Limits for token minting
uint256 public constant DEFAULT_FACTOR = 1E18;
// Amount dedicated to the dao (13M - 5M)
uint256 public constant DAO_QUOTA = 8_000_000 * DEFAULT_FACTOR;
// Amount dedicated to the investor group
uint256 public constant INVESTOR_QUOTA = 19_490_577 * DEFAULT_FACTOR;
// Amount dedicated to the team
uint256 public constant TEAM_QUOTA = 22_509_423 * DEFAULT_FACTOR;
// Amount dedicated to the community
uint256 public constant COMMUNITY_QUOTA = 45_000_000 * DEFAULT_FACTOR;
IToken public immutable govToken;
// contracts that are allowed to mint
address public immutable DAO_VESTER;
address public immutable INVESTOR_VESTER;
address public immutable TEAM_VESTER;
address public immutable COMMUNITY_VESTER;
// contract that is allowed to burn
address public immutable BURNER;
// pool with minting limits for above contracts
mapping(address => uint256) public mintingPools;
constructor(address token, address[4] memory vesters, address burner) {
// set token
govToken = IToken(token);
// set vesters
DAO_VESTER = vesters[0];
INVESTOR_VESTER = vesters[1];
TEAM_VESTER = vesters[2];
COMMUNITY_VESTER = vesters[3];
BURNER = burner;
// set quotas for each vester
mintingPools[vesters[0]] = DAO_QUOTA;
mintingPools[vesters[1]] = INVESTOR_QUOTA;
mintingPools[vesters[2]] = TEAM_QUOTA;
mintingPools[vesters[3]] = COMMUNITY_QUOTA;
}
/// @notice mint tokens - Reduces total allowance for minting pool
/// @param account account to mint for
/// @param amount amount to mint
function mint(address account, uint256 amount) external {
require(
msg.sender == INVESTOR_VESTER ||
msg.sender == TEAM_VESTER ||
msg.sender == COMMUNITY_VESTER,
'mint: msg.sender != vester'
);
uint256 available = mintingPools[msg.sender];
mintingPools[msg.sender] = available - amount;
govToken.mint(account, amount);
}
/// @notice mintDao seperate minting function for dao vester - can mint from both
/// community and dao quota
/// @param account account to mint for
/// @param amount amount to mint
/// @param community If the vest comes from the community or dao quota
function mintDao(
address account,
uint256 amount,
bool community
) external {
require(msg.sender == DAO_VESTER, "mintDao: msg.sender != DAO_VESTER");
address poolId = msg.sender;
if (community) {
poolId = COMMUNITY_VESTER;
}
uint256 available = mintingPools[poolId];
mintingPools[poolId] = available - amount;
govToken.mint(account, amount);
}
/// @notice burn tokens - adds allowance to community pool
/// @param amount amount to burn
/// @dev Burned tokens should get add to users vesting position and
/// add to the community quota.
function burn(uint256 amount) external {
require(msg.sender == BURNER, "burn: msg.sender != BURNER");
govToken.burn(msg.sender, amount);
mintingPools[COMMUNITY_VESTER] = mintingPools[COMMUNITY_VESTER] + amount;
}
} | @notice Contract that defines GRO DAOs' tokenomics - Contracts set below are allowed to mint tokens based on predefined quotas. This contract is intrinsically tied to the GRO Dao token, and is the only contract that is allowed to mint and burn tokens. Limits for token minting Amount dedicated to the dao (13M - 5M) Amount dedicated to the investor group Amount dedicated to the team Amount dedicated to the community contracts that are allowed to mint contract that is allowed to burn pool with minting limits for above contracts | contract GRODistributer {
uint256 public constant DEFAULT_FACTOR = 1E18;
uint256 public constant DAO_QUOTA = 8_000_000 * DEFAULT_FACTOR;
uint256 public constant INVESTOR_QUOTA = 19_490_577 * DEFAULT_FACTOR;
uint256 public constant TEAM_QUOTA = 22_509_423 * DEFAULT_FACTOR;
uint256 public constant COMMUNITY_QUOTA = 45_000_000 * DEFAULT_FACTOR;
IToken public immutable govToken;
address public immutable DAO_VESTER;
address public immutable INVESTOR_VESTER;
address public immutable TEAM_VESTER;
address public immutable COMMUNITY_VESTER;
address public immutable BURNER;
mapping(address => uint256) public mintingPools;
constructor(address token, address[4] memory vesters, address burner) {
govToken = IToken(token);
DAO_VESTER = vesters[0];
INVESTOR_VESTER = vesters[1];
TEAM_VESTER = vesters[2];
COMMUNITY_VESTER = vesters[3];
BURNER = burner;
mintingPools[vesters[0]] = DAO_QUOTA;
mintingPools[vesters[1]] = INVESTOR_QUOTA;
mintingPools[vesters[2]] = TEAM_QUOTA;
mintingPools[vesters[3]] = COMMUNITY_QUOTA;
}
function mint(address account, uint256 amount) external {
require(
msg.sender == INVESTOR_VESTER ||
msg.sender == TEAM_VESTER ||
msg.sender == COMMUNITY_VESTER,
'mint: msg.sender != vester'
);
uint256 available = mintingPools[msg.sender];
mintingPools[msg.sender] = available - amount;
govToken.mint(account, amount);
}
function mintDao(
address account,
uint256 amount,
bool community
) external {
require(msg.sender == DAO_VESTER, "mintDao: msg.sender != DAO_VESTER");
address poolId = msg.sender;
if (community) {
poolId = COMMUNITY_VESTER;
}
uint256 available = mintingPools[poolId];
mintingPools[poolId] = available - amount;
govToken.mint(account, amount);
}
function mintDao(
address account,
uint256 amount,
bool community
) external {
require(msg.sender == DAO_VESTER, "mintDao: msg.sender != DAO_VESTER");
address poolId = msg.sender;
if (community) {
poolId = COMMUNITY_VESTER;
}
uint256 available = mintingPools[poolId];
mintingPools[poolId] = available - amount;
govToken.mint(account, amount);
}
function burn(uint256 amount) external {
require(msg.sender == BURNER, "burn: msg.sender != BURNER");
govToken.burn(msg.sender, amount);
mintingPools[COMMUNITY_VESTER] = mintingPools[COMMUNITY_VESTER] + amount;
}
} | 357,884 | [
1,
8924,
716,
11164,
611,
1457,
463,
37,
15112,
11,
1147,
362,
2102,
300,
30131,
444,
5712,
377,
854,
2935,
358,
312,
474,
2430,
2511,
603,
19555,
4914,
345,
18,
1220,
6835,
353,
377,
316,
17993,
6478,
268,
2092,
358,
326,
611,
1457,
463,
6033,
1147,
16,
471,
353,
326,
1338,
6835,
716,
353,
377,
2935,
358,
312,
474,
471,
18305,
2430,
18,
27240,
364,
1147,
312,
474,
310,
16811,
24328,
358,
326,
15229,
261,
3437,
49,
300,
1381,
49,
13,
16811,
24328,
358,
326,
2198,
395,
280,
1041,
16811,
24328,
358,
326,
5927,
16811,
24328,
358,
326,
19833,
20092,
716,
854,
2935,
358,
312,
474,
6835,
716,
353,
2935,
358,
18305,
2845,
598,
312,
474,
310,
8181,
364,
5721,
20092,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1,
0,
0,
0,
0,
0,
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,
15228,
1212,
291,
665,
26812,
288,
203,
565,
2254,
5034,
1071,
5381,
3331,
67,
26835,
273,
404,
41,
2643,
31,
203,
565,
2254,
5034,
1071,
5381,
463,
20463,
67,
3500,
23476,
273,
1725,
67,
3784,
67,
3784,
380,
3331,
67,
26835,
31,
203,
565,
2254,
5034,
1071,
5381,
2120,
3412,
882,
916,
67,
3500,
23476,
273,
5342,
67,
7616,
20,
67,
25,
4700,
380,
3331,
67,
26835,
31,
203,
565,
2254,
5034,
1071,
5381,
25156,
2192,
67,
3500,
23476,
273,
11201,
67,
5995,
67,
24,
4366,
380,
3331,
67,
26835,
31,
203,
565,
2254,
5034,
1071,
5381,
5423,
49,
2124,
4107,
67,
3500,
23476,
273,
12292,
67,
3784,
67,
3784,
380,
3331,
67,
26835,
31,
203,
203,
565,
467,
1345,
1071,
11732,
31841,
1345,
31,
203,
565,
1758,
1071,
11732,
463,
20463,
67,
3412,
22857,
31,
203,
565,
1758,
1071,
11732,
2120,
3412,
882,
916,
67,
3412,
22857,
31,
203,
565,
1758,
1071,
11732,
25156,
2192,
67,
3412,
22857,
31,
203,
565,
1758,
1071,
11732,
5423,
49,
2124,
4107,
67,
3412,
22857,
31,
203,
565,
1758,
1071,
11732,
605,
8521,
654,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
312,
474,
310,
16639,
31,
203,
203,
565,
3885,
12,
2867,
1147,
16,
1758,
63,
24,
65,
3778,
331,
281,
5432,
16,
1758,
18305,
264,
13,
288,
203,
3639,
31841,
1345,
273,
467,
1345,
12,
2316,
1769,
203,
540,
203,
3639,
463,
20463,
67,
3412,
22857,
273,
331,
281,
5432,
63,
20,
15533,
203,
3639,
2120,
3412,
882,
916,
67,
2
] |
./full_match/1/0xDae97EAFB92F988F268626e4b5120C3E6959bfc7/sources/contracts/MekaDriver/interface/IMultiMint.sol | * @dev Emitted when `tokenId` token is lock./ | event EventMintChange(string _name, Mint sale);
| 8,383,724 | [
1,
1514,
11541,
1347,
1375,
2316,
548,
68,
1147,
353,
2176,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
2587,
49,
474,
3043,
12,
1080,
389,
529,
16,
490,
474,
272,
5349,
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
] |
pragma solidity ^ 0.4 .6;
/*
*
* This file is part of Pass DAO.
*
* The Token Manager smart contract is used for the management of tokens
* by a client smart contract (the Dao). Defines the functions to set new funding rules,
* create or reward tokens, check token balances, send tokens and send
* tokens on behalf of a 3rd party and the corresponding approval process.
*
*/
/// @title Token Manager smart contract of the Pass Decentralized Autonomous Organisation
contract PassTokenManagerInterface {
struct fundingData {
// True if public funding without a main partner
bool publicCreation;
// The address which sets partners and manages the funding in case of private funding
address mainPartner;
// The maximum amount (in wei) of the funding
uint maxAmountToFund;
// The actual funded amount (in wei)
uint fundedAmount;
// A unix timestamp, denoting the start time of the funding
uint startTime;
// A unix timestamp, denoting the closing time of the funding
uint closingTime;
// The price multiplier for a share or a token without considering the inflation rate
uint initialPriceMultiplier;
// Rate per year in percentage applied to the share or token price
uint inflationRate;
// Index of the client proposal
uint proposalID;
}
// Address of the creator of the smart contract
address public creator;
// Address of the Dao
address public client;
// Address of the recipient;
address public recipient;
// The token name for display purpose
string public name;
// The token symbol for display purpose
string public symbol;
// The quantity of decimals for display purpose
uint8 public decimals;
// End date of the setup procedure
uint public smartContractStartDate;
// Total amount of tokens
uint256 totalTokenSupply;
// Array with all balances
mapping(address => uint256) balances;
// Array with all allowances
mapping(address => mapping(address => uint256)) allowed;
// Map of the result (in wei) of fundings
mapping(uint => uint) fundedAmount;
// Array of token or share holders
address[] holders;
// Map with the indexes of the holders
mapping(address => uint) public holderID;
// If true, the shares or tokens can be transfered
bool public transferable;
// Map of blocked Dao share accounts. Points to the date when the share holder can transfer shares
mapping(address => uint) public blockedDeadLine;
// Rules for the actual funding and the contractor token price
fundingData[2] public FundingRules;
/// @return The total supply of shares or tokens
function totalSupply() constant external returns(uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant external returns(uint256 balance);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Quantity of remaining tokens of _owner that _spender is allowed to spend
function allowance(address _owner, address _spender) constant external returns(uint256 remaining);
/// @param _proposalID The index of the Dao proposal
/// @return The result (in wei) of the funding
function FundedAmount(uint _proposalID) constant external returns(uint);
/// @param _saleDate in case of presale, the date of the presale
/// @return the share or token price divisor condidering the sale date and the inflation rate
function priceDivisor(uint _saleDate) constant internal returns(uint);
/// @return the actual price divisor of a share or token
function actualPriceDivisor() constant external returns(uint);
/// @return The maximal amount a main partner can fund at this moment
/// @param _mainPartner The address of the main parner
function fundingMaxAmount(address _mainPartner) constant external returns(uint);
/// @return The number of share or token holders
function numberOfHolders() constant returns(uint);
/// @param _index The index of the holder
/// @return the address of the an holder
function HolderAddress(uint _index) constant returns(address);
// Modifier that allows only the client to manage this account manager
modifier onlyClient {
if (msg.sender != client) throw;
_;
}
// Modifier that allows only the main partner to manage the actual funding
modifier onlyMainPartner {
if (msg.sender != FundingRules[0].mainPartner) throw;
_;
}
// Modifier that allows only the contractor propose set the token price or withdraw
modifier onlyContractor {
if (recipient == 0 || (msg.sender != recipient && msg.sender != creator)) throw;
_;
}
// Modifier for Dao functions
modifier onlyDao {
if (recipient != 0) throw;
_;
}
/// @dev The constructor function
/// @param _creator The address of the creator of the smart contract
/// @param _client The address of the client or Dao
/// @param _recipient The recipient of this manager
/// @param _tokenName The token name for display purpose
/// @param _tokenSymbol The token symbol for display purpose
/// @param _tokenDecimals The quantity of decimals for display purpose
/// @param _transferable True if allows the transfer of tokens
//function PassTokenManager(
// address _creator,
// address _client,
// address _recipient,
// string _tokenName,
// string _tokenSymbol,
// uint8 _tokenDecimals,
// bool _transferable);
/// @notice Function to create initial tokens
/// @param _holder The beneficiary of the created tokens
/// @param _quantity The quantity of tokens to create
function createInitialTokens(address _holder, uint _quantity);
/// @notice Function to close the setup procedure of this contract
function closeSetup();
/// @notice Function that allow the contractor to propose a token price
/// @param _initialPriceMultiplier The initial price multiplier of contractor tokens
/// @param _inflationRate If 0, the contractor token price doesn't change during the funding
/// @param _closingTime The initial price and inflation rate can be changed after this date
function setTokenPriceProposal(
uint _initialPriceMultiplier,
uint _inflationRate,
uint _closingTime
);
/// @notice Function to set a funding. Can be private or public
/// @param _mainPartner The address of the smart contract to manage a private funding
/// @param _publicCreation True if public funding
/// @param _initialPriceMultiplier Price multiplier without considering any inflation rate
/// @param _maxAmountToFund The maximum amount (in wei) of the funding
/// @param _minutesFundingPeriod Period in minutes of the funding
/// @param _inflationRate If 0, the token price doesn't change during the funding
/// @param _proposalID Index of the client proposal (not mandatory)
function setFundingRules(
address _mainPartner,
bool _publicCreation,
uint _initialPriceMultiplier,
uint _maxAmountToFund,
uint _minutesFundingPeriod,
uint _inflationRate,
uint _proposalID
) external;
/// @dev Internal function to add a new token or share holder
/// @param _holder The address of the token or share holder
function addHolder(address _holder) internal;
/// @dev Internal function for the creation of shares or tokens
/// @param _recipient The recipient address of shares or tokens
/// @param _amount The funded amount (in wei)
/// @param _saleDate In case of presale, the date of the presale
/// @return Whether the creation was successful or not
function createToken(
address _recipient,
uint _amount,
uint _saleDate
) internal returns(bool success);
/// @notice Function used by the main partner to set the start time of the funding
/// @param _startTime The unix start date of the funding
function setFundingStartTime(uint _startTime) external;
/// @notice Function used by the main partner to reward shares or tokens
/// @param _recipient The address of the recipient of shares or tokens
/// @param _amount The amount (in Wei) to calculate the quantity of shares or tokens to create
/// @param _date The unix date to consider for the share or token price calculation
/// @return Whether the transfer was successful or not
function rewardToken(
address _recipient,
uint _amount,
uint _date
) external;
/// @dev Internal function to close the actual funding
function closeFunding() internal;
/// @notice Function used by the main partner to set the funding fueled
function setFundingFueled() external;
/// @notice Function to able the transfer of Dao shares or contractor tokens
function ableTransfer();
/// @notice Function to disable the transfer of Dao shares
function disableTransfer();
/// @notice Function used by the client to block the transfer of shares from and to a share holder
/// @param _shareHolder The address of the share holder
/// @param _deadLine When the account will be unblocked
function blockTransfer(address _shareHolder, uint _deadLine) external;
/// @dev Internal function to send `_value` token to `_to` from `_From`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
/// @return Whether the function was successful or not
function transferFromTo(
address _from,
address _to,
uint256 _value
) internal returns(bool success);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
/// @return Whether the function was successful or not
function transfer(address _to, uint256 _value) returns(bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The quantity of shares or tokens to be transferred
function transferFrom(
address _from,
address _to,
uint256 _value
) returns(bool success);
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns(bool success);
event TokenPriceProposalSet(uint InitialPriceMultiplier, uint InflationRate, uint ClosingTime);
event holderAdded(uint Index, address Holder);
event TokensCreated(address indexed Sender, address indexed TokenHolder, uint Quantity);
event FundingRulesSet(address indexed MainPartner, uint indexed FundingProposalId, uint indexed StartTime, uint ClosingTime);
event FundingFueled(uint indexed FundingProposalID, uint FundedAmount);
event TransferAble();
event TransferDisable();
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract PassTokenManager is PassTokenManagerInterface {
function totalSupply() constant external returns(uint256) {
return totalTokenSupply;
}
function balanceOf(address _owner) constant external returns(uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant external returns(uint256 remaining) {
return allowed[_owner][_spender];
}
function FundedAmount(uint _proposalID) constant external returns(uint) {
return fundedAmount[_proposalID];
}
function priceDivisor(uint _saleDate) constant internal returns(uint) {
uint _date = _saleDate;
if (_saleDate > FundingRules[0].closingTime) _date = FundingRules[0].closingTime;
if (_saleDate < FundingRules[0].startTime) _date = FundingRules[0].startTime;
return 100 + 100 * FundingRules[0].inflationRate * (_date - FundingRules[0].startTime) / (100 * 365 days);
}
function actualPriceDivisor() constant external returns(uint) {
return priceDivisor(now);
}
function fundingMaxAmount(address _mainPartner) constant external returns(uint) {
if (now > FundingRules[0].closingTime || now < FundingRules[0].startTime || _mainPartner != FundingRules[0].mainPartner) {
return 0;
} else {
return FundingRules[0].maxAmountToFund;
}
}
function numberOfHolders() constant returns(uint) {
return holders.length - 1;
}
function HolderAddress(uint _index) constant returns(address) {
return holders[_index];
}
function PassTokenManager(
address _creator,
address _client,
address _recipient,
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals,
bool _transferable) {
if (_creator == 0 || _client == 0 || _client == _recipient || _client == address(this) || _recipient == address(this)) throw;
creator = _creator;
client = _client;
recipient = _recipient;
holders.length = 1;
name = _tokenName;
symbol = _tokenSymbol;
decimals = _tokenDecimals;
if (_transferable) {
transferable = true;
TransferAble();
} else {
transferable = false;
TransferDisable();
}
}
function createInitialTokens(
address _holder,
uint _quantity
) {
if (smartContractStartDate != 0) throw;
if (_quantity > 0 && balances[_holder] == 0) {
addHolder(_holder);
balances[_holder] = _quantity;
totalTokenSupply += _quantity;
TokensCreated(msg.sender, _holder, _quantity);
}
}
function closeSetup() {
smartContractStartDate = now;
}
function setTokenPriceProposal(
uint _initialPriceMultiplier,
uint _inflationRate,
uint _closingTime
) onlyContractor {
if (_closingTime < now || now < FundingRules[1].closingTime) throw;
FundingRules[1].initialPriceMultiplier = _initialPriceMultiplier;
FundingRules[1].inflationRate = _inflationRate;
FundingRules[1].startTime = now;
FundingRules[1].closingTime = _closingTime;
TokenPriceProposalSet(_initialPriceMultiplier, _inflationRate, _closingTime);
}
function setFundingRules(
address _mainPartner,
bool _publicCreation,
uint _initialPriceMultiplier,
uint _maxAmountToFund,
uint _minutesFundingPeriod,
uint _inflationRate,
uint _proposalID
) external onlyClient {
if (now < FundingRules[0].closingTime || _mainPartner == address(this) || _mainPartner == client || (!_publicCreation && _mainPartner == 0) || (_publicCreation && _mainPartner != 0) || (recipient == 0 && _initialPriceMultiplier == 0) || (recipient != 0 && (FundingRules[1].initialPriceMultiplier == 0 || _inflationRate < FundingRules[1].inflationRate || now < FundingRules[1].startTime || FundingRules[1].closingTime < now + (_minutesFundingPeriod * 1 minutes))) || _maxAmountToFund == 0 || _minutesFundingPeriod == 0) throw;
FundingRules[0].startTime = now;
FundingRules[0].closingTime = now + _minutesFundingPeriod * 1 minutes;
FundingRules[0].mainPartner = _mainPartner;
FundingRules[0].publicCreation = _publicCreation;
if (recipient == 0) FundingRules[0].initialPriceMultiplier = _initialPriceMultiplier;
else FundingRules[0].initialPriceMultiplier = FundingRules[1].initialPriceMultiplier;
if (recipient == 0) FundingRules[0].inflationRate = _inflationRate;
else FundingRules[0].inflationRate = FundingRules[1].inflationRate;
FundingRules[0].fundedAmount = 0;
FundingRules[0].maxAmountToFund = _maxAmountToFund;
FundingRules[0].proposalID = _proposalID;
FundingRulesSet(_mainPartner, _proposalID, FundingRules[0].startTime, FundingRules[0].closingTime);
}
function addHolder(address _holder) internal {
if (holderID[_holder] == 0) {
uint _holderID = holders.length++;
holders[_holderID] = _holder;
holderID[_holder] = _holderID;
holderAdded(_holderID, _holder);
}
}
function createToken(
address _recipient,
uint _amount,
uint _saleDate
) internal returns(bool success) {
if (now > FundingRules[0].closingTime || now < FundingRules[0].startTime || _saleDate > FundingRules[0].closingTime || _saleDate < FundingRules[0].startTime || FundingRules[0].fundedAmount + _amount > FundingRules[0].maxAmountToFund) return;
uint _a = _amount * FundingRules[0].initialPriceMultiplier;
uint _multiplier = 100 * _a;
uint _quantity = _multiplier / priceDivisor(_saleDate);
if (_a / _amount != FundingRules[0].initialPriceMultiplier || _multiplier / 100 != _a || totalTokenSupply + _quantity <= totalTokenSupply || totalTokenSupply + _quantity <= _quantity) return;
addHolder(_recipient);
balances[_recipient] += _quantity;
totalTokenSupply += _quantity;
FundingRules[0].fundedAmount += _amount;
TokensCreated(msg.sender, _recipient, _quantity);
if (FundingRules[0].fundedAmount == FundingRules[0].maxAmountToFund) closeFunding();
return true;
}
function setFundingStartTime(uint _startTime) external onlyMainPartner {
if (now > FundingRules[0].closingTime) throw;
FundingRules[0].startTime = _startTime;
}
function rewardToken(
address _recipient,
uint _amount,
uint _date
) external onlyMainPartner {
uint _saleDate;
if (_date == 0) _saleDate = now;
else _saleDate = _date;
if (!createToken(_recipient, _amount, _saleDate)) throw;
}
function closeFunding() internal {
if (recipient == 0) fundedAmount[FundingRules[0].proposalID] = FundingRules[0].fundedAmount;
FundingRules[0].closingTime = now;
}
function setFundingFueled() external onlyMainPartner {
if (now > FundingRules[0].closingTime) throw;
closeFunding();
if (recipient == 0) FundingFueled(FundingRules[0].proposalID, FundingRules[0].fundedAmount);
}
function ableTransfer() onlyClient {
if (!transferable) {
transferable = true;
TransferAble();
}
}
function disableTransfer() onlyClient {
if (transferable) {
transferable = false;
TransferDisable();
}
}
function blockTransfer(address _shareHolder, uint _deadLine) external onlyClient onlyDao {
if (_deadLine > blockedDeadLine[_shareHolder]) {
blockedDeadLine[_shareHolder] = _deadLine;
}
}
function transferFromTo(
address _from,
address _to,
uint256 _value
) internal returns(bool success) {
if (transferable && now > blockedDeadLine[_from] && now > blockedDeadLine[_to] && _to != address(this) && balances[_from] >= _value && balances[_to] + _value > balances[_to] && balances[_to] + _value >= _value) {
balances[_from] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
addHolder(_to);
return true;
} else {
return false;
}
}
function transfer(address _to, uint256 _value) returns(bool success) {
if (!transferFromTo(msg.sender, _to, _value)) throw;
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) returns(bool success) {
if (allowed[_from][msg.sender] < _value || !transferFromTo(_from, _to, _value)) throw;
allowed[_from][msg.sender] -= _value;
return true;
}
function approve(address _spender, uint256 _value) returns(bool success) {
allowed[msg.sender][_spender] = _value;
return true;
}
}
pragma solidity ^ 0.4 .6;
/*
*
* This file is part of Pass DAO.
*
* The Manager smart contract is used for the management of accounts and tokens.
* Allows to receive or withdraw ethers and to buy Dao shares.
* The contract derives to the Token Manager smart contract for the management of tokens.
*
* Recipient is 0 for the Dao account manager and the address of
* contractor's recipient for the contractors's mahagers.
*
*/
/// @title Manager smart contract of the Pass Decentralized Autonomous Organisation
contract PassManagerInterface is PassTokenManagerInterface {
struct proposal {
// Amount (in wei) of the proposal
uint amount;
// A description of the proposal
string description;
// The hash of the proposal's document
bytes32 hashOfTheDocument;
// A unix timestamp, denoting the date when the proposal was created
uint dateOfProposal;
// The index of the last approved client proposal
uint lastClientProposalID;
// The sum amount (in wei) ordered for this proposal
uint orderAmount;
// A unix timestamp, denoting the date of the last order for the approved proposal
uint dateOfOrder;
}
// Proposals to work for the client
proposal[] public proposals;
// The address of the last Manager before cloning
address public clonedFrom;
/// @dev The constructor function
/// @param _client The address of the Dao
/// @param _recipient The address of the recipient. 0 for the Dao
/// @param _clonedFrom The address of the last Manager before cloning
/// @param _tokenName The token name for display purpose
/// @param _tokenSymbol The token symbol for display purpose
/// @param _tokenDecimals The quantity of decimals for display purpose
/// @param _transferable True if allows the transfer of tokens
//function PassManager(
// address _client,
// address _recipient,
// address _clonedFrom,
// string _tokenName,
// string _tokenSymbol,
// uint8 _tokenDecimals,
// bool _transferable
//) PassTokenManager(
// msg.sender,
// _client,
// _recipient,
// _tokenName,
// _tokenSymbol,
// _tokenDecimals,
// _transferable);
/// @notice Function to allow sending fees in wei to the Dao
function receiveFees() payable;
/// @notice Function to allow the contractor making a deposit in wei
function receiveDeposit() payable;
/// @notice Function to clone a proposal from another manager contract
/// @param _amount Amount (in wei) of the proposal
/// @param _description A description of the proposal
/// @param _hashOfTheDocument The hash of the proposal's document
/// @param _dateOfProposal A unix timestamp, denoting the date when the proposal was created
/// @param _lastClientProposalID The index of the last approved client proposal
/// @param _orderAmount The sum amount (in wei) ordered for this proposal
/// @param _dateOfOrder A unix timestamp, denoting the date of the last order for the approved proposal
function cloneProposal(
uint _amount,
string _description,
bytes32 _hashOfTheDocument,
uint _dateOfProposal,
uint _lastClientProposalID,
uint _orderAmount,
uint _dateOfOrder);
/// @notice Function to clone tokens from a manager
/// @param _from The index of the first holder
/// @param _to The index of the last holder
function cloneTokens(
uint _from,
uint _to);
/// @notice Function to update the client address
function updateClient(address _newClient);
/// @notice Function to update the recipent address
/// @param _newRecipient The adress of the recipient
function updateRecipient(address _newRecipient);
/// @notice Function to buy Dao shares according to the funding rules
/// with `msg.sender` as the beneficiary
function buyShares() payable;
/// @notice Function to buy Dao shares according to the funding rules
/// @param _recipient The beneficiary of the created shares
function buySharesFor(address _recipient) payable;
/// @notice Function to make a proposal to work for the client
/// @param _amount The amount (in wei) of the proposal
/// @param _description String describing the proposal
/// @param _hashOfTheDocument The hash of the proposal document
/// @return The index of the contractor proposal
function newProposal(
uint _amount,
string _description,
bytes32 _hashOfTheDocument
) returns(uint);
/// @notice Function used by the client to order according to the contractor proposal
/// @param _clientProposalID The index of the last approved client proposal
/// @param _proposalID The index of the contractor proposal
/// @param _amount The amount (in wei) of the order
/// @return Whether the order was made or not
function order(
uint _clientProposalID,
uint _proposalID,
uint _amount
) external returns(bool);
/// @notice Function used by the client to send ethers from the Dao manager
/// @param _recipient The address to send to
/// @param _amount The amount (in wei) to send
/// @return Whether the transfer was successful or not
function sendTo(
address _recipient,
uint _amount
) external returns(bool);
/// @notice Function to allow contractors to withdraw ethers
/// @param _amount The amount (in wei) to withdraw
function withdraw(uint _amount);
/// @return The number of Dao rules proposals
function numberOfProposals() constant returns(uint);
event FeesReceived(address indexed From, uint Amount);
event DepositReceived(address indexed From, uint Amount);
event ProposalCloned(uint indexed LastClientProposalID, uint indexed ProposalID, uint Amount, string Description, bytes32 HashOfTheDocument);
event ClientUpdated(address LastClient, address NewClient);
event RecipientUpdated(address LastRecipient, address NewRecipient);
event ProposalAdded(uint indexed ProposalID, uint Amount, string Description, bytes32 HashOfTheDocument);
event Order(uint indexed clientProposalID, uint indexed ProposalID, uint Amount);
event Withdawal(address indexed Recipient, uint Amount);
}
contract PassManager is PassManagerInterface, PassTokenManager {
function PassManager(
address _client,
address _recipient,
address _clonedFrom,
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals,
bool _transferable
) PassTokenManager(
msg.sender,
_client,
_recipient,
_tokenName,
_tokenSymbol,
_tokenDecimals,
_transferable
) {
clonedFrom = _clonedFrom;
proposals.length = 1;
}
function receiveFees() payable onlyDao {
FeesReceived(msg.sender, msg.value);
}
function receiveDeposit() payable onlyContractor {
DepositReceived(msg.sender, msg.value);
}
function cloneProposal(
uint _amount,
string _description,
bytes32 _hashOfTheDocument,
uint _dateOfProposal,
uint _lastClientProposalID,
uint _orderAmount,
uint _dateOfOrder
) {
if (smartContractStartDate != 0 || recipient == 0) throw;
uint _proposalID = proposals.length++;
proposal c = proposals[_proposalID];
c.amount = _amount;
c.description = _description;
c.hashOfTheDocument = _hashOfTheDocument;
c.dateOfProposal = _dateOfProposal;
c.lastClientProposalID = _lastClientProposalID;
c.orderAmount = _orderAmount;
c.dateOfOrder = _dateOfOrder;
ProposalCloned(_lastClientProposalID, _proposalID, c.amount, c.description, c.hashOfTheDocument);
}
function cloneTokens(
uint _from,
uint _to) {
if (smartContractStartDate != 0) throw;
PassManager _clonedFrom = PassManager(_clonedFrom);
if (_from < 1 || _to > _clonedFrom.numberOfHolders()) throw;
address _holder;
for (uint i = _from; i <= _to; i++) {
_holder = _clonedFrom.HolderAddress(i);
if (balances[_holder] == 0) {
createInitialTokens(_holder, _clonedFrom.balanceOf(_holder));
}
}
}
function updateClient(address _newClient) onlyClient {
if (_newClient == 0 || _newClient == recipient) throw;
ClientUpdated(client, _newClient);
client = _newClient;
}
function updateRecipient(address _newRecipient) onlyContractor {
if (_newRecipient == 0 || _newRecipient == client) throw;
RecipientUpdated(recipient, _newRecipient);
recipient = _newRecipient;
}
function buyShares() payable {
buySharesFor(msg.sender);
}
function buySharesFor(address _recipient) payable onlyDao {
if (!FundingRules[0].publicCreation || !createToken(_recipient, msg.value, now)) throw;
}
function newProposal(
uint _amount,
string _description,
bytes32 _hashOfTheDocument
) onlyContractor returns(uint) {
uint _proposalID = proposals.length++;
proposal c = proposals[_proposalID];
c.amount = _amount;
c.description = _description;
c.hashOfTheDocument = _hashOfTheDocument;
c.dateOfProposal = now;
ProposalAdded(_proposalID, c.amount, c.description, c.hashOfTheDocument);
return _proposalID;
}
function order(
uint _clientProposalID,
uint _proposalID,
uint _orderAmount
) external onlyClient returns(bool) {
proposal c = proposals[_proposalID];
uint _sum = c.orderAmount + _orderAmount;
if (_sum > c.amount || _sum < c.orderAmount || _sum < _orderAmount) return;
c.lastClientProposalID = _clientProposalID;
c.orderAmount = _sum;
c.dateOfOrder = now;
Order(_clientProposalID, _proposalID, _orderAmount);
return true;
}
function sendTo(
address _recipient,
uint _amount
) external onlyClient onlyDao returns(bool) {
if (_recipient.send(_amount)) return true;
else return false;
}
function withdraw(uint _amount) onlyContractor {
if (!recipient.send(_amount)) throw;
Withdawal(recipient, _amount);
}
function numberOfProposals() constant returns(uint) {
return proposals.length - 1;
}
}
pragma solidity ^ 0.4 .6;
/*
This file is part of Pass DAO.
Pass DAO is free software: you can redistribute it and/or modify
it under the terms of the GNU lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Pass DAO is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU lesser General Public License for more details.
You should have received a copy of the GNU lesser General Public License
along with Pass DAO. If not, see <http://www.gnu.org/licenses></http:>.
*/
/*
Smart contract for a Decentralized Autonomous Organization (DAO)
to automate organizational governance and decision-making.
*/
/// @title Pass Decentralized Autonomous Organisation
contract PassDaoInterface {
struct BoardMeeting {
// Address of the creator of the board meeting for a proposal
address creator;
// Index to identify the proposal to pay a contractor or fund the Dao
uint proposalID;
// Index to identify the proposal to update the Dao rules
uint daoRulesProposalID;
// unix timestamp, denoting the end of the set period of a proposal before the board meeting
uint setDeadline;
// Fees (in wei) paid by the creator of the board meeting
uint fees;
// Total of fees (in wei) rewarded to the voters or to the Dao account manager for the balance
uint totalRewardedAmount;
// A unix timestamp, denoting the end of the voting period
uint votingDeadline;
// True if the proposal's votes have yet to be counted, otherwise False
bool open;
// A unix timestamp, denoting the date of the execution of the approved proposal
uint dateOfExecution;
// Number of shares in favor of the proposal
uint yea;
// Number of shares opposed to the proposal
uint nay;
// mapping to indicate if a shareholder has voted
mapping(address => bool) hasVoted;
}
struct Contractor {
// The address of the contractor manager smart contract
address contractorManager;
// The date of the first order for the contractor
uint creationDate;
}
struct Proposal {
// Index to identify the board meeting of the proposal
uint boardMeetingID;
// The contractor manager smart contract
PassManager contractorManager;
// The index of the contractor proposal
uint contractorProposalID;
// The amount (in wei) of the proposal
uint amount;
// True if the proposal foresees a contractor token creation
bool tokenCreation;
// True if public funding without a main partner
bool publicShareCreation;
// The address which sets partners and manages the funding in case of private funding
address mainPartner;
// The initial price multiplier of Dao shares at the beginning of the funding
uint initialSharePriceMultiplier;
// The inflation rate to calculate the actual contractor share price
uint inflationRate;
// A unix timestamp, denoting the start time of the funding
uint minutesFundingPeriod;
// True if the proposal is closed
bool open;
}
struct Rules {
// Index to identify the board meeting that decides to apply or not the Dao rules
uint boardMeetingID;
// The quorum needed for each proposal is calculated by totalSupply / minQuorumDivisor
uint minQuorumDivisor;
// Minimum fees (in wei) to create a proposal
uint minBoardMeetingFees;
// Period in minutes to consider or set a proposal before the voting procedure
uint minutesSetProposalPeriod;
// The minimum debate period in minutes that a generic proposal can have
uint minMinutesDebatePeriod;
// The inflation rate to calculate the reward of fees to voters during a board meeting
uint feesRewardInflationRate;
// True if the dao rules allow the transfer of shares
bool transferable;
// Address of the effective Dao smart contract (can be different of this Dao in case of upgrade)
address dao;
}
// The creator of the Dao
address public creator;
// The name of the project
string public projectName;
// The address of the last Dao before upgrade (not mandatory)
address public lastDao;
// End date of the setup procedure
uint public smartContractStartDate;
// The Dao manager smart contract
PassManager public daoManager;
// The minimum periods in minutes
uint public minMinutesPeriods;
// The maximum period in minutes for proposals (set+debate)
uint public maxMinutesProposalPeriod;
// The maximum funding period in minutes for funding proposals
uint public maxMinutesFundingPeriod;
// The maximum inflation rate for share price or rewards to voters
uint public maxInflationRate;
// Map to allow the share holders to withdraw board meeting fees
mapping(address => uint) pendingFees;
// Board meetings to vote for or against a proposal
BoardMeeting[] public BoardMeetings;
// Contractors of the Dao
Contractor[] public Contractors;
// Map with the indexes of the contractors
mapping(address => uint) contractorID;
// Proposals to pay a contractor or fund the Dao
Proposal[] public Proposals;
// Proposals to update the Dao rules
Rules[] public DaoRulesProposals;
// The current Dao rules
Rules public DaoRules;
/// @dev The constructor function
/// @param _projectName The name of the Dao
/// @param _lastDao The address of the last Dao before upgrade (not mandatory)
//function PassDao(
// string _projectName,
// address _lastDao);
/// @dev Internal function to add a new contractor
/// @param _contractorManager The address of the contractor manager
/// @param _creationDate The date of the first order
function addContractor(address _contractorManager, uint _creationDate) internal;
/// @dev Function to clone a contractor from the last Dao in case of upgrade
/// @param _contractorManager The address of the contractor manager
/// @param _creationDate The date of the first order
function cloneContractor(address _contractorManager, uint _creationDate);
/// @notice Function to update the client of the contractor managers in case of upgrade
/// @param _from The index of the first contractor manager to update
/// @param _to The index of the last contractor manager to update
function updateClientOfContractorManagers(
uint _from,
uint _to);
/// @dev Function to initialize the Dao
/// @param _daoManager Address of the Dao manager smart contract
/// @param _maxInflationRate The maximum inflation rate for contractor and funding proposals
/// @param _minMinutesPeriods The minimum periods in minutes
/// @param _maxMinutesFundingPeriod The maximum funding period in minutes for funding proposals
/// @param _maxMinutesProposalPeriod The maximum period in minutes for proposals (set+debate)
/// @param _minQuorumDivisor The initial minimum quorum divisor for the proposals
/// @param _minBoardMeetingFees The amount (in wei) to make a proposal and ask for a board meeting
/// @param _minutesSetProposalPeriod The minimum period in minutes before a board meeting
/// @param _minMinutesDebatePeriod The minimum period in minutes of the board meetings
/// @param _feesRewardInflationRate The inflation rate to calculate the reward of fees to voters during a board meeting
function initDao(
address _daoManager,
uint _maxInflationRate,
uint _minMinutesPeriods,
uint _maxMinutesFundingPeriod,
uint _maxMinutesProposalPeriod,
uint _minQuorumDivisor,
uint _minBoardMeetingFees,
uint _minutesSetProposalPeriod,
uint _minMinutesDebatePeriod,
uint _feesRewardInflationRate
);
/// @dev Internal function to create a board meeting
/// @param _proposalID The index of the proposal if for a contractor or for a funding
/// @param _daoRulesProposalID The index of the proposal if Dao rules
/// @param _minutesDebatingPeriod The duration in minutes of the meeting
/// @return the index of the board meeting
function newBoardMeeting(
uint _proposalID,
uint _daoRulesProposalID,
uint _minutesDebatingPeriod
) internal returns(uint);
/// @notice Function to make a proposal to pay a contractor or fund the Dao
/// @param _contractorManager Address of the contractor manager smart contract
/// @param _contractorProposalID Index of the contractor proposal of the contractor manager
/// @param _amount The amount (in wei) of the proposal
/// @param _tokenCreation True if the proposal foresees a contractor token creation
/// @param _publicShareCreation True if public funding without a main partner
/// @param _mainPartner The address which sets partners and manage the funding
/// in case of private funding (not mandatory)
/// @param _initialSharePriceMultiplier The initial price multiplier of shares
/// @param _inflationRate If 0, the share price doesn't change during the funding (not mandatory)
/// @param _minutesFundingPeriod Period in minutes of the funding
/// @param _minutesDebatingPeriod Period in minutes of the board meeting to vote on the proposal
/// @return The index of the proposal
function newProposal(
address _contractorManager,
uint _contractorProposalID,
uint _amount,
bool _publicShareCreation,
bool _tokenCreation,
address _mainPartner,
uint _initialSharePriceMultiplier,
uint _inflationRate,
uint _minutesFundingPeriod,
uint _minutesDebatingPeriod
) payable returns(uint);
/// @notice Function to make a proposal to change the Dao rules
/// @param _minQuorumDivisor If 5, the minimum quorum is 20%
/// @param _minBoardMeetingFees The amount (in wei) to make a proposal and ask for a board meeting
/// @param _minutesSetProposalPeriod Minimum period in minutes before a board meeting
/// @param _minMinutesDebatePeriod The minimum period in minutes of the board meetings
/// @param _feesRewardInflationRate The inflation rate to calculate the reward of fees to voters during a board meeting
/// @param _transferable True if the proposal foresees to allow the transfer of Dao shares
/// @param _dao Address of a new Dao smart contract in case of upgrade (not mandatory)
/// @param _minutesDebatingPeriod Period in minutes of the board meeting to vote on the proposal
function newDaoRulesProposal(
uint _minQuorumDivisor,
uint _minBoardMeetingFees,
uint _minutesSetProposalPeriod,
uint _minMinutesDebatePeriod,
uint _feesRewardInflationRate,
bool _transferable,
address _dao,
uint _minutesDebatingPeriod
) payable returns(uint);
/// @notice Function to vote during a board meeting
/// @param _boardMeetingID The index of the board meeting
/// @param _supportsProposal True if the proposal is supported
function vote(
uint _boardMeetingID,
bool _supportsProposal
);
/// @notice Function to execute a board meeting decision and close the board meeting
/// @param _boardMeetingID The index of the board meeting
/// @return Whether the proposal was executed or not
function executeDecision(uint _boardMeetingID) returns(bool);
/// @notice Function to order a contractor proposal
/// @param _proposalID The index of the proposal
/// @return Whether the proposal was ordered and the proposal amount sent or not
function orderContractorProposal(uint _proposalID) returns(bool);
/// @notice Function to withdraw the rewarded board meeting fees
/// @return Whether the withdraw was successful or not
function withdrawBoardMeetingFees() returns(bool);
/// @param _shareHolder Address of the shareholder
/// @return The amount in wei the shareholder can withdraw
function PendingFees(address _shareHolder) constant returns(uint);
/// @return The minimum quorum for proposals to pass
function minQuorum() constant returns(uint);
/// @return The number of contractors
function numberOfContractors() constant returns(uint);
/// @return The number of board meetings (or proposals)
function numberOfBoardMeetings() constant returns(uint);
event ContractorProposalAdded(uint indexed ProposalID, uint boardMeetingID, address indexed ContractorManager,
uint indexed ContractorProposalID, uint amount);
event FundingProposalAdded(uint indexed ProposalID, uint boardMeetingID, bool indexed LinkedToContractorProposal,
uint amount, address MainPartner, uint InitialSharePriceMultiplier, uint InflationRate, uint MinutesFundingPeriod);
event DaoRulesProposalAdded(uint indexed DaoRulesProposalID, uint boardMeetingID, uint MinQuorumDivisor,
uint MinBoardMeetingFees, uint MinutesSetProposalPeriod, uint MinMinutesDebatePeriod, uint FeesRewardInflationRate,
bool Transferable, address NewDao);
event Voted(uint indexed boardMeetingID, uint ProposalID, uint DaoRulesProposalID, bool position, address indexed voter);
event ProposalClosed(uint indexed ProposalID, uint indexed DaoRulesProposalID, uint boardMeetingID,
uint FeesGivenBack, bool ProposalExecuted, uint BalanceSentToDaoManager);
event SentToContractor(uint indexed ProposalID, uint indexed ContractorProposalID, address indexed ContractorManagerAddress, uint AmountSent);
event Withdrawal(address indexed Recipient, uint Amount);
event DaoUpgraded(address NewDao);
}
contract PassDao is PassDaoInterface {
function PassDao(
string _projectName,
address _lastDao) {
lastDao = _lastDao;
creator = msg.sender;
projectName = _projectName;
Contractors.length = 1;
BoardMeetings.length = 1;
Proposals.length = 1;
DaoRulesProposals.length = 1;
}
function addContractor(address _contractorManager, uint _creationDate) internal {
if (contractorID[_contractorManager] == 0) {
uint _contractorID = Contractors.length++;
Contractor c = Contractors[_contractorID];
contractorID[_contractorManager] = _contractorID;
c.contractorManager = _contractorManager;
c.creationDate = _creationDate;
}
}
function cloneContractor(address _contractorManager, uint _creationDate) {
if (DaoRules.minQuorumDivisor != 0) throw;
addContractor(_contractorManager, _creationDate);
}
function initDao(
address _daoManager,
uint _maxInflationRate,
uint _minMinutesPeriods,
uint _maxMinutesFundingPeriod,
uint _maxMinutesProposalPeriod,
uint _minQuorumDivisor,
uint _minBoardMeetingFees,
uint _minutesSetProposalPeriod,
uint _minMinutesDebatePeriod,
uint _feesRewardInflationRate
) {
if (smartContractStartDate != 0) throw;
maxInflationRate = _maxInflationRate;
minMinutesPeriods = _minMinutesPeriods;
maxMinutesFundingPeriod = _maxMinutesFundingPeriod;
maxMinutesProposalPeriod = _maxMinutesProposalPeriod;
DaoRules.minQuorumDivisor = _minQuorumDivisor;
DaoRules.minBoardMeetingFees = _minBoardMeetingFees;
DaoRules.minutesSetProposalPeriod = _minutesSetProposalPeriod;
DaoRules.minMinutesDebatePeriod = _minMinutesDebatePeriod;
DaoRules.feesRewardInflationRate = _feesRewardInflationRate;
daoManager = PassManager(_daoManager);
smartContractStartDate = now;
}
function updateClientOfContractorManagers(
uint _from,
uint _to) {
if (_from < 1 || _to > Contractors.length - 1) throw;
for (uint i = _from; i <= _to; i++) {
PassManager(Contractors[i].contractorManager).updateClient(DaoRules.dao);
}
}
function newBoardMeeting(
uint _proposalID,
uint _daoRulesProposalID,
uint _minutesDebatingPeriod
) internal returns(uint) {
if (msg.value < DaoRules.minBoardMeetingFees || DaoRules.minutesSetProposalPeriod + _minutesDebatingPeriod > maxMinutesProposalPeriod || now + ((DaoRules.minutesSetProposalPeriod + _minutesDebatingPeriod) * 1 minutes) < now || _minutesDebatingPeriod < DaoRules.minMinutesDebatePeriod || msg.sender == address(this)) throw;
uint _boardMeetingID = BoardMeetings.length++;
BoardMeeting b = BoardMeetings[_boardMeetingID];
b.creator = msg.sender;
b.proposalID = _proposalID;
b.daoRulesProposalID = _daoRulesProposalID;
b.fees = msg.value;
b.setDeadline = now + (DaoRules.minutesSetProposalPeriod * 1 minutes);
b.votingDeadline = b.setDeadline + (_minutesDebatingPeriod * 1 minutes);
b.open = true;
return _boardMeetingID;
}
function newProposal(
address _contractorManager,
uint _contractorProposalID,
uint _amount,
bool _tokenCreation,
bool _publicShareCreation,
address _mainPartner,
uint _initialSharePriceMultiplier,
uint _inflationRate,
uint _minutesFundingPeriod,
uint _minutesDebatingPeriod
) payable returns(uint) {
if ((_contractorManager != 0 && _contractorProposalID == 0) || (_contractorManager == 0 && (_initialSharePriceMultiplier == 0 || _contractorProposalID != 0) || (_tokenCreation && _publicShareCreation) || (_initialSharePriceMultiplier != 0 && (_minutesFundingPeriod < minMinutesPeriods || _inflationRate > maxInflationRate || _minutesFundingPeriod > maxMinutesFundingPeriod)))) throw;
uint _proposalID = Proposals.length++;
Proposal p = Proposals[_proposalID];
p.contractorManager = PassManager(_contractorManager);
p.contractorProposalID = _contractorProposalID;
p.amount = _amount;
p.tokenCreation = _tokenCreation;
p.publicShareCreation = _publicShareCreation;
p.mainPartner = _mainPartner;
p.initialSharePriceMultiplier = _initialSharePriceMultiplier;
p.inflationRate = _inflationRate;
p.minutesFundingPeriod = _minutesFundingPeriod;
p.boardMeetingID = newBoardMeeting(_proposalID, 0, _minutesDebatingPeriod);
p.open = true;
if (_contractorProposalID != 0) {
ContractorProposalAdded(_proposalID, p.boardMeetingID, p.contractorManager, p.contractorProposalID, p.amount);
if (_initialSharePriceMultiplier != 0) {
FundingProposalAdded(_proposalID, p.boardMeetingID, true, p.amount, p.mainPartner,
p.initialSharePriceMultiplier, _inflationRate, _minutesFundingPeriod);
}
} else if (_initialSharePriceMultiplier != 0) {
FundingProposalAdded(_proposalID, p.boardMeetingID, false, p.amount, p.mainPartner,
p.initialSharePriceMultiplier, _inflationRate, _minutesFundingPeriod);
}
return _proposalID;
}
function newDaoRulesProposal(
uint _minQuorumDivisor,
uint _minBoardMeetingFees,
uint _minutesSetProposalPeriod,
uint _minMinutesDebatePeriod,
uint _feesRewardInflationRate,
bool _transferable,
address _newDao,
uint _minutesDebatingPeriod
) payable returns(uint) {
if (_minQuorumDivisor <= 1 || _minQuorumDivisor > 10 || _minutesSetProposalPeriod < minMinutesPeriods || _minMinutesDebatePeriod < minMinutesPeriods || _minutesSetProposalPeriod + _minMinutesDebatePeriod > maxMinutesProposalPeriod || _feesRewardInflationRate > maxInflationRate) throw;
uint _DaoRulesProposalID = DaoRulesProposals.length++;
Rules r = DaoRulesProposals[_DaoRulesProposalID];
r.minQuorumDivisor = _minQuorumDivisor;
r.minBoardMeetingFees = _minBoardMeetingFees;
r.minutesSetProposalPeriod = _minutesSetProposalPeriod;
r.minMinutesDebatePeriod = _minMinutesDebatePeriod;
r.feesRewardInflationRate = _feesRewardInflationRate;
r.transferable = _transferable;
r.dao = _newDao;
r.boardMeetingID = newBoardMeeting(0, _DaoRulesProposalID, _minutesDebatingPeriod);
DaoRulesProposalAdded(_DaoRulesProposalID, r.boardMeetingID, _minQuorumDivisor, _minBoardMeetingFees,
_minutesSetProposalPeriod, _minMinutesDebatePeriod, _feesRewardInflationRate, _transferable, _newDao);
return _DaoRulesProposalID;
}
function vote(
uint _boardMeetingID,
bool _supportsProposal
) {
BoardMeeting b = BoardMeetings[_boardMeetingID];
if (b.hasVoted[msg.sender] || now < b.setDeadline || now > b.votingDeadline) throw;
uint _balance = uint(daoManager.balanceOf(msg.sender));
if (_balance == 0) throw;
b.hasVoted[msg.sender] = true;
if (_supportsProposal) b.yea += _balance;
else b.nay += _balance;
if (b.fees > 0 && b.proposalID != 0 && Proposals[b.proposalID].contractorProposalID != 0) {
uint _a = 100 * b.fees;
if ((_a / 100 != b.fees) || ((_a * _balance) / _a != _balance)) throw;
uint _multiplier = (_a * _balance) / uint(daoManager.totalSupply());
uint _divisor = 100 + 100 * DaoRules.feesRewardInflationRate * (now - b.setDeadline) / (100 * 365 days);
uint _rewardedamount = _multiplier / _divisor;
if (b.totalRewardedAmount + _rewardedamount > b.fees) _rewardedamount = b.fees - b.totalRewardedAmount;
b.totalRewardedAmount += _rewardedamount;
pendingFees[msg.sender] += _rewardedamount;
}
Voted(_boardMeetingID, b.proposalID, b.daoRulesProposalID, _supportsProposal, msg.sender);
daoManager.blockTransfer(msg.sender, b.votingDeadline);
}
function executeDecision(uint _boardMeetingID) returns(bool) {
BoardMeeting b = BoardMeetings[_boardMeetingID];
Proposal p = Proposals[b.proposalID];
if (now < b.votingDeadline || !b.open) throw;
b.open = false;
if (p.contractorProposalID == 0) p.open = false;
uint _fees;
uint _minQuorum = minQuorum();
if (b.fees > 0 && (b.proposalID == 0 || p.contractorProposalID == 0) && b.yea + b.nay >= _minQuorum) {
_fees = b.fees;
b.fees = 0;
pendingFees[b.creator] += _fees;
}
uint _balance = b.fees - b.totalRewardedAmount;
if (_balance > 0) {
if (!daoManager.send(_balance)) throw;
}
if (b.yea + b.nay < _minQuorum || b.yea <= b.nay) {
p.open = false;
ProposalClosed(b.proposalID, b.daoRulesProposalID, _boardMeetingID, _fees, false, _balance);
return;
}
b.dateOfExecution = now;
if (b.proposalID != 0) {
if (p.initialSharePriceMultiplier != 0) {
daoManager.setFundingRules(p.mainPartner, p.publicShareCreation, p.initialSharePriceMultiplier,
p.amount, p.minutesFundingPeriod, p.inflationRate, b.proposalID);
if (p.contractorProposalID != 0 && p.tokenCreation) {
p.contractorManager.setFundingRules(p.mainPartner, p.publicShareCreation, 0,
p.amount, p.minutesFundingPeriod, maxInflationRate, b.proposalID);
}
}
} else {
Rules r = DaoRulesProposals[b.daoRulesProposalID];
DaoRules.boardMeetingID = r.boardMeetingID;
DaoRules.minQuorumDivisor = r.minQuorumDivisor;
DaoRules.minMinutesDebatePeriod = r.minMinutesDebatePeriod;
DaoRules.minBoardMeetingFees = r.minBoardMeetingFees;
DaoRules.minutesSetProposalPeriod = r.minutesSetProposalPeriod;
DaoRules.feesRewardInflationRate = r.feesRewardInflationRate;
DaoRules.transferable = r.transferable;
if (r.transferable) daoManager.ableTransfer();
else daoManager.disableTransfer();
if ((r.dao != 0) && (r.dao != address(this))) {
DaoRules.dao = r.dao;
daoManager.updateClient(r.dao);
DaoUpgraded(r.dao);
}
}
ProposalClosed(b.proposalID, b.daoRulesProposalID, _boardMeetingID, _fees, true, _balance);
return true;
}
function orderContractorProposal(uint _proposalID) returns(bool) {
Proposal p = Proposals[_proposalID];
BoardMeeting b = BoardMeetings[p.boardMeetingID];
if (b.open || !p.open) throw;
uint _amount = p.amount;
if (p.initialSharePriceMultiplier != 0) {
_amount = daoManager.FundedAmount(_proposalID);
if (_amount == 0 && now < b.dateOfExecution + (p.minutesFundingPeriod * 1 minutes)) return;
}
p.open = false;
if (_amount == 0 || !p.contractorManager.order(_proposalID, p.contractorProposalID, _amount)) return;
if (!daoManager.sendTo(p.contractorManager, _amount)) throw;
SentToContractor(_proposalID, p.contractorProposalID, address(p.contractorManager), _amount);
addContractor(address(p.contractorManager), now);
return true;
}
function withdrawBoardMeetingFees() returns(bool) {
uint _amount = pendingFees[msg.sender];
pendingFees[msg.sender] = 0;
if (msg.sender.send(_amount)) {
Withdrawal(msg.sender, _amount);
return true;
} else {
pendingFees[msg.sender] = _amount;
return false;
}
}
function PendingFees(address _shareHolder) constant returns(uint) {
return (pendingFees[_shareHolder]);
}
function minQuorum() constant returns(uint) {
return (uint(daoManager.totalSupply()) / DaoRules.minQuorumDivisor);
}
function numberOfContractors() constant returns(uint) {
return Contractors.length - 1;
}
function numberOfBoardMeetings() constant returns(uint) {
return BoardMeetings.length - 1;
}
} | Map to allow the share holders to withdraw board meeting fees | mapping(address => uint) pendingFees;
| 12,620,229 | [
1,
863,
358,
1699,
326,
7433,
366,
4665,
358,
598,
9446,
11094,
18721,
310,
1656,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
2874,
12,
2867,
516,
2254,
13,
4634,
2954,
281,
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
] |
./full_match/97/0x3DE74ecA1d04C99616548331a1B1F2dF44A6041d/sources/project:/contracts/Referal.sol | Если предыдущую комсу не забрали, заберем ее. | function buyClientTarif(uint16 _tarifKey) public {
require(!usersTree.blockedUsers(msg.sender), "User blocked");
TarifsStoreBase clientTarifs = usersTarifsStore.clientTarifs();
uint256 tarif = clientTarifs.tarif(_tarifKey);
require(tarif != 0 && canBuy(msg.sender), "E117");
if (usersFinance.comsaExists(msg.sender)) processComsa(msg.sender);
usersFinance.freezeMoney(TarifDataLib.getPrice(tarif), msg.sender);
usersTarifsStore.newClientTarif(msg.sender, tarif);
processComsa(msg.sender);
}
| 5,023,812 | [
1,
145,
248,
146,
228,
145,
124,
145,
121,
225,
145,
128,
146,
227,
145,
118,
145,
117,
146,
238,
145,
117,
146,
230,
146,
236,
146,
230,
146,
241,
225,
145,
123,
145,
127,
145,
125,
146,
228,
146,
230,
225,
145,
126,
145,
118,
225,
145,
120,
145,
113,
145,
114,
146,
227,
145,
113,
145,
124,
145,
121,
16,
225,
145,
120,
145,
113,
145,
114,
145,
118,
146,
227,
145,
118,
145,
125,
225,
145,
118,
145,
118,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30143,
1227,
20464,
430,
12,
11890,
2313,
389,
11718,
430,
653,
13,
1071,
288,
203,
3639,
2583,
12,
5,
5577,
2471,
18,
23156,
6588,
12,
3576,
18,
15330,
3631,
315,
1299,
14547,
8863,
203,
203,
3639,
20334,
17249,
2257,
2171,
1004,
20464,
17249,
273,
3677,
20464,
17249,
2257,
18,
2625,
20464,
17249,
5621,
203,
3639,
2254,
5034,
8232,
430,
273,
1004,
20464,
17249,
18,
11718,
430,
24899,
11718,
430,
653,
1769,
203,
3639,
2583,
12,
11718,
430,
480,
374,
597,
848,
38,
9835,
12,
3576,
18,
15330,
3631,
315,
41,
23454,
8863,
203,
203,
3639,
309,
261,
5577,
6187,
1359,
18,
832,
13098,
4002,
12,
3576,
18,
15330,
3719,
1207,
799,
13098,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
3677,
6187,
1359,
18,
29631,
23091,
12,
20464,
430,
751,
5664,
18,
588,
5147,
12,
11718,
430,
3631,
1234,
18,
15330,
1769,
203,
3639,
3677,
20464,
17249,
2257,
18,
2704,
1227,
20464,
430,
12,
3576,
18,
15330,
16,
8232,
430,
1769,
540,
203,
3639,
1207,
799,
13098,
12,
3576,
18,
15330,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
}
interface ItokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external returns (bool);
}
interface IstakeContract {
function createStake(address _wallet, uint8 _timeFrame, uint256 _value) external returns (bool);
}
interface IERC20Token {
function totalSupply() external view returns (uint256 supply);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function balanceOf(address _owner) external view returns (uint256 balance);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
}
contract Ownable {
address private owner;
event OwnerSet(address indexed oldOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner, "Caller is not owner");
_;
}
constructor() {
owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
emit OwnerSet(address(0), owner);
}
function changeOwner(address newOwner) public onlyOwner {
emit OwnerSet(owner, newOwner);
owner = newOwner;
}
function getOwner() external view returns (address) {
return owner;
}
}
contract StandardToken is IERC20Token {
using SafeMath for uint256;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public _totalSupply;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function totalSupply() override public view returns (uint256 supply) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) override virtual public returns (bool success) {
require(_to != address(0x0), "Use burn function instead"); // Prevent transfer to 0x0 address. Use burn() instead
require(_value >= 0, "Invalid amount");
require(balances[msg.sender] >= _value, "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;
}
function transferFrom(address _from, address _to, uint256 _value) override virtual public returns (bool success) {
require(_to != address(0x0), "Use burn function instead"); // Prevent transfer to 0x0 address. Use burn() instead
require(_value >= 0, "Invalid amount");
require(balances[_from] >= _value, "Not enough balance");
require(allowed[_from][msg.sender] >= _value, "You need to increase allowance");
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) override public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) override public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) override public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract YUIToken is Ownable, StandardToken {
using SafeMath for uint256;
string public name;
uint8 public decimals;
string public symbol;
address public stakeContract;
address public crowdSaleContract;
uint256 public soldTokensUnlockTime;
mapping (address => uint256) frozenBalances;
mapping (address => uint256) timelock;
event Burn(address indexed from, uint256 value);
event StakeContractSet(address indexed contractAddress);
constructor() {
name = "YUI Token";
decimals = 18;
symbol = "YUI";
stakeContract = address(0x0);
crowdSaleContract = 0x5530AF4758A33bE9Fd62165ef543b5E2e6742953; // contract for ICO tokens
address teamWallet = 0x07B8DcbDF4d52B9C1f4251373A289D803Cc670f8; // wallet for team tokens
address privateSaleWallet = 0xC5f1f4fdbFAb7F73CfC814d72408B648059514A0; // wallet for private sale tokens
address marketingWallet = 0x5e0e67AA4f29aD2920Fa8BFe3ae38B52D4f2ceb1; // wallet for marketing
address exchangesLiquidity = 0x7e47b3C642A72520fF7DbFDc052535A0c804fC3C; // add liquidity to exchanges
address stakeWallet = 0x16B92c0473C0491D1509c447285B7c925355e3D3; // tokens for the stake contract
uint256 teamReleaseTime = 1620324000; // lock team tokens for 6 months
uint256 marketingReleaseTime = 1612548000; // lock marketing tokens - 1k tokens for 3 months
uint256 stakesReleaseTime = 1606586400; // lock stakeContract tokens - 7.5k tokens for 3 weeks
balances[teamWallet] = 3000 ether;
emit Transfer(address(0x0), teamWallet, (3000 ether));
frozenBalances[teamWallet] = 3000 ether;
timelock[teamWallet] = teamReleaseTime;
balances[stakeWallet] = 7500 ether;
emit Transfer(address(0x0), address(stakeWallet), (7500 ether));
frozenBalances[stakeWallet] = 7500 ether;
timelock[stakeWallet] = stakesReleaseTime;
balances[marketingWallet] = 2000 ether;
emit Transfer(address(0x0), address(marketingWallet), (2000 ether));
frozenBalances[marketingWallet] = 1000 ether;
timelock[marketingWallet] = marketingReleaseTime;
balances[privateSaleWallet] = 1500 ether;
emit Transfer(address(0x0), address(privateSaleWallet), (1500 ether));
balances[crowdSaleContract] = 5000 ether;
emit Transfer(address(0x0), address(crowdSaleContract), (5000 ether));
balances[exchangesLiquidity] = 9000 ether;
emit Transfer(address(0x0), address(exchangesLiquidity), (9000 ether));
_totalSupply = 28000 ether;
soldTokensUnlockTime = 1605636300;
}
function frozenBalanceOf(address _owner) public view returns (uint256 balance) {
return frozenBalances[_owner];
}
function unlockTimeOf(address _owner) public view returns (uint256 time) {
return timelock[_owner];
}
function transfer(address _to, uint256 _value) override public returns (bool success) {
require(txAllowed(msg.sender, _value), "Crowdsale tokens are still frozen");
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) override public returns (bool success) {
require(txAllowed(msg.sender, _value), "Crowdsale tokens are still frozen");
return super.transferFrom(_from, _to, _value);
}
function setStakeContract(address _contractAddress) onlyOwner public {
stakeContract = _contractAddress;
emit StakeContractSet(_contractAddress);
}
function setCrowdSaleContract(address _contractAddress) onlyOwner public {
crowdSaleContract = _contractAddress;
}
// Tokens sold by crowdsale contract will be frozen ultil crowdsale ends
function txAllowed(address sender, uint256 amount) private returns (bool isAllowed) {
if (timelock[sender] > block.timestamp) {
return isBalanceFree(sender, amount);
} else {
if (frozenBalances[sender] > 0) frozenBalances[sender] = 0;
return true;
}
}
function isBalanceFree(address sender, uint256 amount) private view returns (bool isfree) {
if (amount <= (balances[sender] - frozenBalances[sender])) {
return true;
} else {
return false;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value, "Not enough balance");
require(_value >= 0, "Invalid amount");
balances[msg.sender] = balances[msg.sender].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(msg.sender, _value);
return true;
}
function approveStake(uint8 _timeFrame, uint256 _value) public returns (bool success) {
require(stakeContract != address(0x0));
allowed[msg.sender][stakeContract] = _value;
emit Approval(msg.sender, stakeContract, _value);
IstakeContract recipient = IstakeContract(stakeContract);
require(recipient.createStake(msg.sender, _timeFrame, _value));
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
ItokenRecipient recipient = ItokenRecipient(_spender);
require(recipient.receiveApproval(msg.sender, _value, address(this), _extraData));
return true;
}
function tokensSold(address buyer, uint256 amount) public returns (bool success) {
require(msg.sender == crowdSaleContract);
frozenBalances[buyer] += amount;
if (timelock[buyer] == 0 ) timelock[buyer] = soldTokensUnlockTime;
return super.transfer(buyer, amount);
}
} | contract for ICO tokens
| crowdSaleContract = 0x5530AF4758A33bE9Fd62165ef543b5E2e6742953; | 10,884,872 | [
1,
16351,
364,
467,
3865,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
276,
492,
72,
30746,
8924,
273,
374,
92,
2539,
5082,
6799,
24,
5877,
28,
37,
3707,
70,
41,
29,
27263,
8898,
28275,
10241,
6564,
23,
70,
25,
41,
22,
73,
26,
5608,
5540,
8643,
31,
5375,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../interfaces/IStrategy.sol";
import "../interfaces/IVault.sol";
import "../interfaces/IPancakeRouter02.sol";
import "../interfaces/IWaultSwapRouter02.sol";
import "../interfaces/ISwap.sol";
import "../interfaces/IWaultPair.sol";
import "../interfaces/INervePair.sol";
import "../interfaces/IWexMaster.sol";
import "../interfaces/IMasterMind.sol";
import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol";
import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
contract Strategy is IStrategy, Ownable, Pausable {
using SafeBEP20 for IBEP20;
using SafeBEP20 for IWaultPair;
using SafeBEP20 for INervePair;
using SafeMath for uint256;
/* ============= CONSTANTS ============= */
IBEP20 private WBNB = IBEP20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c);
IBEP20 private ETH = IBEP20(0x2170Ed0880ac9A755fd29B2688956BD959F933F8); // Binance Pegged ETH
IBEP20 private BETH = IBEP20(0x250632378E573c6Be1AC2f97Fcdf00515d0Aa91B);
IBEP20 private constant ANYETH =
IBEP20(0x6F817a0cE8F7640Add3bC0c1C2298635043c2423);
IBEP20 private constant WEX =
IBEP20(0xa9c41A46a6B3531d28d5c32F6633dd2fF05dFB90);
IBEP20 private constant NRV =
IBEP20(0x42F6f551ae042cBe50C739158b4f0CAC0Edb9096);
IWaultPair private constant ETH_BETH_LP =
IWaultPair(0x11040f3c467993556B19813d4A18b684598Ba4BD); // WaultSwap WETH-BETH LP
INervePair private constant ETH_ANYETH_LP =
INervePair(0x0d283BF16A9bdE49cfC48d8dc050AF28b71bdD90); // Nerve WETH-anyETH LP
IPancakeRouter02 private constant PANCAKE_ROUTER =
IPancakeRouter02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); // PCS Router V2
IWaultSwapRouter02 private constant WAULT_ROUTER =
IWaultSwapRouter02(0xD48745E39BbED146eEC15b79cBF964884F9877c2); // WaultSwap Router
ISwap private constant NERVE_SWAP =
ISwap(0x146CD24dCc9f4EB224DFd010c5Bf2b0D25aFA9C0); // Nerve ETH-anyETH LP maker
IWexMaster private constant WAULT_FARM =
IWexMaster(0x22fB2663C7ca71Adc2cc99481C77Aaf21E152e2D); // Wault WETH-BETH Farm, pid = 42
IMasterMind private constant NERVE_FARM =
IMasterMind(0x2EBe8CDbCB5fB8564bC45999DAb8DA264E31f24E); // Nerve WETH-anyETH Farm, pid = 5
uint256 private constant WAULT_PID = 42;
uint256 private constant NERVE_PID = 5;
uint8 private constant ETH_NERVE_TOKEN_ID = 0;
uint8 private constant ANYETH_NERVE_TOKEN_ID = 1;
uint256 private constant DENOMINATOR = 10000;
uint256 private constant MAX_AMT = type(uint256).max;
uint256 private constant ONE = 1e18;
/* ========== STATE VARIABLES ========== */
// LP token price in ETH
uint256 public _price_ETH_BETH_LP; // Might not need
uint256 public _price_ETH_ANYETH_LP;
// Pool in ETH
uint256 public _pool_ETH_BETH_LP;
uint256 public _pool_ETH_ANYETH_LP;
address public admin;
address public communityWallet;
address public strategist;
IVault public vault;
// Farm Allocation Weights
uint256 public waultFarmPerc = 5000; // 50% allocation to Wault
uint256 public nerveFarmPerc = 5000; // 50% allocation to Nerve
// Fees
uint256 public yieldFeePerc = 1000; // 10% Yield fees
// Information
uint256 public totalWaultYield = 0;
uint256 public totalNerveYield = 0;
/* ============= MODIFIERS ============= */
modifier onlyAdmin {
require(msg.sender == address(admin), "Strategy:: Only Admin");
_;
}
modifier onlyVault {
require(msg.sender == address(vault), "Strategy:: Only Vault");
_;
}
/* ============== EVENTS ============== */
event Invested(uint256 ethInvested);
event LiquidityRemoved(
address lpToken,
uint256 liquidityRemoved,
uint256 amountA,
uint256 amountB,
address router
);
event LiquidityAdded(
address tokenA,
address tokenB,
uint256 amountA,
uint256 amountB,
uint256 liquidity,
address router
);
event SetVault(address vaultAddress);
event SetAdmin(address adminAddress);
event SetStrategist(address strategistAddress);
event Harvested(uint256 claimedWEX, uint256 claimedNRV);
event Withdrawn(uint256 amount, uint256 withdrawalFee);
/* ============ CONSTRUCTOR ============ */
constructor(
address _communityWallet,
address _strategist,
address _admin
) public {
require(
_communityWallet != address(0),
"Strategy::constructor: communityWallet does not exist"
);
communityWallet = _communityWallet;
strategist = _strategist;
admin = _admin;
ETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT);
ETH.safeApprove(address(WAULT_ROUTER), MAX_AMT);
ETH.safeApprove(address(NERVE_SWAP), MAX_AMT);
BETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT);
BETH.safeApprove(address(WAULT_ROUTER), MAX_AMT);
ANYETH.safeApprove(address(PANCAKE_ROUTER), MAX_AMT);
ANYETH.safeApprove(address(NERVE_SWAP), MAX_AMT);
ETH_BETH_LP.safeApprove(address(WAULT_FARM), MAX_AMT);
ETH_BETH_LP.safeApprove(address(WAULT_ROUTER), MAX_AMT);
ETH_ANYETH_LP.safeApprove(address(NERVE_FARM), MAX_AMT);
ETH_ANYETH_LP.safeApprove(address(NERVE_SWAP), MAX_AMT);
WEX.safeApprove(address(PANCAKE_ROUTER), MAX_AMT);
NRV.safeApprove(address(PANCAKE_ROUTER), MAX_AMT);
}
receive() external payable {
// ...
}
fallback() external {
// ...
}
/* =========== VIEW FUNCTIONS =========== */
/// @notice Get TVL of Strategy in ETH
function getStrategyPool()
public
view
override
returns (uint256 _valueInEth)
{
uint256 _valueInEth_ETH_BETH_LP = _pool_ETH_BETH_LP
.mul(_calcPriceETH_BETH_LP())
.div(1e18);
uint256 _valueInEth_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP
.mul(_calcPriceETH_ANYETH_LP())
.div(1e18);
_valueInEth = _valueInEth_ETH_BETH_LP.add(_valueInEth_ETH_ANYETH_LP);
}
/* ========= MUTATIVE FUNCTIONS ========= */
/// @notice Invest tokens into Wault and Nerve Farms
/// @param _amount Amount of ETH to invest
function invest(uint256 _amount) public override onlyVault whenNotPaused {
require(_amount > 0, "Strategy::invest: Invest Amount <= 0");
ETH.safeTransferFrom(address(vault), address(this), _amount);
// Divide by 2 to maintain the 1:1 ETH:BETH for LP
uint256 _amountToBETH = _amount.mul(waultFarmPerc).div(2).div(
DENOMINATOR
);
uint256 _amountToANYETH = _amount.mul(nerveFarmPerc).div(2).div(
DENOMINATOR
);
uint256 _amountRemaining = _amount.sub(_amountToBETH).sub(
_amountToANYETH
);
uint256 _amountBETH = _swapETHforBETH(_amountToBETH);
uint256 _amountANYETH = _swapETHforANYETH(_amountToANYETH);
uint256 _amount_ETH_BETH_LP = _addLiquidityWault(
_amountRemaining.div(2),
_amountBETH
);
_amountRemaining = _amountRemaining.sub(_amountRemaining.div(2));
uint256 _amount_ETH_ANYETH_LP = _addLiquidityNerve(
_amountRemaining,
_amountANYETH
);
_investWault(_amount_ETH_BETH_LP);
_investNerve(_amount_ETH_ANYETH_LP);
// Update Pool
uint256 _pool_ETH_BETH_LP_before = _pool_ETH_BETH_LP;
(uint256 _pool_ETH_BETH_LP_after, , ) = WAULT_FARM.userInfo(
WAULT_PID,
address(this)
);
uint256 _pool_ETH_ANYETH_LP_before = _pool_ETH_ANYETH_LP;
(uint256 _pool_ETH_ANYETH_LP_after, ) = NERVE_FARM.userInfo(
NERVE_PID,
address(this)
);
_pool_ETH_BETH_LP = _pool_ETH_BETH_LP.add(
_pool_ETH_BETH_LP_after.sub(_pool_ETH_BETH_LP_before)
);
_pool_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP.add(
_pool_ETH_ANYETH_LP_after.sub(_pool_ETH_ANYETH_LP_before)
);
emit Invested(_amount);
}
/// @notice Withdraw tokens from farms and swap into ETH
/// @dev Liquidate enough LP tokens to meet the amount, 50% from Wault and 50% from Nerve
function withdraw(uint256 _amount) public override onlyVault whenNotPaused {
require(_amount > 0, "Strategy::withdraw: Withdraw Amount <= 0)");
uint256 _strategyPool = getStrategyPool();
uint256 _amount_ETH_BETH_LP = _amount.mul(_pool_ETH_BETH_LP).div(
_strategyPool
);
uint256 _amount_ETH_ANYETH_LP = _amount.mul(_pool_ETH_ANYETH_LP).div(
_strategyPool
);
// Withdrawing automatically harvests yields
_withdrawWault(_amount_ETH_BETH_LP);
_withdrawNerve(_amount_ETH_ANYETH_LP);
(
uint256 _amountETHFromWault,
uint256 _amountBETH
) = _removeLiquidityWault(_amount_ETH_BETH_LP);
(
uint256 _amountETHFromNerve,
uint256 _amountANYETH
) = _removeLiquidityNerve(_amount_ETH_ANYETH_LP);
_pool_ETH_BETH_LP = _pool_ETH_BETH_LP.sub(_amount_ETH_BETH_LP);
_pool_ETH_ANYETH_LP = _pool_ETH_ANYETH_LP.sub(_amount_ETH_ANYETH_LP);
uint256 _totalRewards = _liquidateRewards(); // in ETH
uint256 _fees = _totalRewards.mul(yieldFeePerc).div(DENOMINATOR);
_splitYieldFees(_fees);
// Swap BETH and anyETH back to ETH
uint256 _amountETHFromBETH = _swapBETHforETH(_amountBETH);
uint256 _amountETHFromANYETH = _swapANYETHforETH(_amountANYETH);
uint256 _amountETH = _amountETHFromWault.add(_amountETHFromNerve).add(
_totalRewards
);
_amountETH = _amountETH.sub(_fees).add(_amountETHFromBETH).add(
_amountETHFromANYETH
);
// Send deserved ETH back to Vault
ETH.safeTransfer(address(vault), _amountETH);
}
/// @notice Harvest yields from farms and reinvest them
function compound() external override onlyVault whenNotPaused {
_harvest();
uint256 _amount = _liquidateRewards();
invest(_amount);
}
/* ========= PRIVATE FUNCTIONS ========= */
/// @notice Invest ETH-BETH LP tokens into WexMaster
function _investWault(uint256 _amount) private {
require(
_amount > 0,
"Strategy::_investWault: Invalid Amount (_amount <= 0)"
);
WAULT_FARM.deposit(WAULT_PID, _amount, false);
}
/// @notice Invest ETH-anyETH LP tokens into MasterMind
function _investNerve(uint256 _amount) private {
require(
_amount > 0,
"Strategy::_investNerve: Invalid Amount (_amount <= 0)"
);
NERVE_FARM.deposit(NERVE_PID, _amount);
}
/// @notice Withdraw ETH-BETH LP Tokens from WexMaster
function _withdrawWault(uint256 _amount) private {
WAULT_FARM.withdraw(WAULT_PID, _amount, true);
}
/// @notice Withdraw ETH-anyETH LP Tokens from MasterMind
function _withdrawNerve(uint256 _amount) private {
NERVE_FARM.withdraw(NERVE_PID, _amount);
}
/// @notice Harvest yields from farms
function _harvest() private {
uint256 _claimedWEX = _harvestWault();
uint256 _claimedNRV = _harvestNerve();
totalWaultYield = totalWaultYield.add(_claimedWEX);
totalNerveYield = totalNerveYield.add(_claimedNRV);
emit Harvested(_claimedWEX, _claimedNRV);
}
/// @notice Harvest Wault Rewards
function _harvestWault() private returns (uint256 _rewardsClaimed) {
uint256 _pendingRewards = WAULT_FARM.pendingWex(
WAULT_PID,
address(this)
);
_rewardsClaimed = 0;
// Check if pending WEX is above 0
if (_pendingRewards > 0) {
WAULT_FARM.claim(WAULT_PID);
_rewardsClaimed = _pendingRewards;
}
}
/// @notice Harvest Nerve Rewards
function _harvestNerve() private returns (uint256 _rewardsClaimed) {
uint256 _pendingRewards = NERVE_FARM.pendingNerve(
NERVE_PID,
address(this)
);
_rewardsClaimed = 0;
// Check if pending NRV is above 0
// TODO: Write logic to claim NRV rewards, Nerve Finance locks up 2/3 rewards and does not have claim function
if (_pendingRewards > 0) {
NERVE_FARM.withdraw(NERVE_PID, 0);
_rewardsClaimed = _pendingRewards;
}
}
/// @notice Swaps ETH for BETH on Pancake Router
function _swapETHforBETH(uint256 _amount)
private
returns (uint256 _amountBETH)
{
uint256[] memory _amounts = _swapExactTokensForTokens(
address(ETH),
address(BETH),
_amount
);
_amountBETH = _amounts[1];
}
/// @notice Swaps ETH for anyETH on Pancake Router
function _swapETHforANYETH(uint256 _amount)
private
returns (uint256 _amountANYETH)
{
// Only nerveswap has liquidity
uint256 _amountsOut = NERVE_SWAP.calculateSwap(
ETH_NERVE_TOKEN_ID,
ANYETH_NERVE_TOKEN_ID,
_amount
);
if (_amountsOut > 0) {
_amountANYETH = NERVE_SWAP.swap(
ETH_NERVE_TOKEN_ID,
ANYETH_NERVE_TOKEN_ID,
_amount,
0,
block.timestamp
);
} else {
// Not enough amount to swap
_amountANYETH = 0;
}
}
/// @notice Swaps BETH for ETH on Pancake Router
function _swapBETHforETH(uint256 _amount)
private
returns (uint256 _amountETH)
{
uint256[] memory _amounts = _swapExactTokensForTokens(
address(BETH),
address(ETH),
_amount
);
_amountETH = _amounts[1];
}
/// @notice Swaps ANYETH for ETH on Pancake Router
function _swapANYETHforETH(uint256 _amount)
private
returns (uint256 _amountETH)
{
// Only nerveswap has liquidity
uint256 _amountsOut = NERVE_SWAP.calculateSwap(
ANYETH_NERVE_TOKEN_ID,
ETH_NERVE_TOKEN_ID,
_amount
);
if (_amountsOut > 0) {
_amountETH = NERVE_SWAP.swap(
ANYETH_NERVE_TOKEN_ID,
ETH_NERVE_TOKEN_ID,
_amount,
0,
block.timestamp
);
} else {
// Not enough amount to swap
_amountETH = 0;
}
}
/// @notice Get Wault ETH-BETH LP tokens
function _addLiquidityWault(uint256 _amountETH, uint256 _amountBETH)
private
returns (uint256)
{
(uint256 _amountA, uint256 _amountB, uint256 _liquidity) = WAULT_ROUTER
.addLiquidity(
address(ETH),
address(BETH),
_amountETH,
_amountBETH,
0,
0,
address(this),
block.timestamp
);
emit LiquidityAdded(
address(ETH),
address(BETH),
_amountA,
_amountB,
_liquidity,
address(WAULT_ROUTER)
);
return _liquidity;
}
/// @notice Get Nerve ETH-anyETH LP tokens
function _addLiquidityNerve(uint256 _amountETH, uint256 _amountANYETH)
private
returns (uint256 _liquidity)
{
uint256[] memory _amounts = new uint256[](2);
_amounts[0] = _amountETH;
_amounts[1] = _amountANYETH;
_liquidity = NERVE_SWAP.addLiquidity(_amounts, 0, block.timestamp);
emit LiquidityAdded(
address(ETH),
address(ANYETH),
_amountETH,
_amountANYETH,
_liquidity,
address(NERVE_SWAP)
);
}
/// @notice Remove ETH-BETH Liquidity from Wault Swap
function _removeLiquidityWault(uint256 _amount)
private
returns (uint256 _amountA, uint256 _amountB)
{
(_amountA, _amountB) = WAULT_ROUTER.removeLiquidity(
address(ETH),
address(BETH),
_amount,
0,
0,
address(this),
block.timestamp
);
emit LiquidityRemoved(
address(ETH_BETH_LP),
_amount,
_amountA,
_amountB,
address(WAULT_ROUTER)
);
}
/// @notice Remove ETH-anyETH Liquidity from Nerve Swap
function _removeLiquidityNerve(uint256 _amount)
private
returns (uint256 _amountA, uint256 _amountB)
{
uint256[] memory _minAmounts = new uint256[](2);
_minAmounts[0] = 0;
_minAmounts[1] = 0;
uint256[] memory _returnedAmounts = NERVE_SWAP.removeLiquidity(
_amount,
_minAmounts,
block.timestamp
);
_amountA = _returnedAmounts[0];
_amountB = _returnedAmounts[1];
emit LiquidityRemoved(
address(ETH_ANYETH_LP),
_amount,
_amountA,
_amountB,
address(NERVE_SWAP)
);
}
/// @notice Convert all rewards (WEX + NRV) into base token (ETH)
function _liquidateRewards() private returns (uint256 _totalRewards) {
// Liquidate Wault Rewards
uint256 _waultRewards = _liquidateWaultRewards();
// Liquidate Nerve Rewards
uint256 _nerveRewards = _liquidateNerveRewards();
// Calculate total ETH gained from rewards
_totalRewards = _waultRewards.add(_nerveRewards);
}
/// @notice Function to transfer fees that collect from yield to wallets
/// @param _amount Fees to transfer in ETH Token
function _splitYieldFees(uint256 _amount) private {
uint256 _creditToAdmin = (_amount).mul(2).div(5);
uint256 _creditToCommunityWallet = (_amount).mul(2).div(5);
uint256 _creditToStrategist = (_amount).mul(1).div(5);
ETH.safeTransfer(admin, _creditToAdmin); // 40%
ETH.safeTransfer(communityWallet, _creditToCommunityWallet); // 40%
ETH.safeTransfer(strategist, _creditToStrategist); // 20%
}
/// @notice Converts WEX rewards to ETH
function _liquidateWaultRewards() private returns (uint256 _yieldAmount) {
uint256 _balanceOfWEX = WEX.balanceOf(address(this));
_yieldAmount = 0;
if (_balanceOfWEX > 0) {
uint256[] memory _amounts = _swapExactTokensForTokens2(
address(WEX),
address(ETH),
_balanceOfWEX
);
_yieldAmount = _amounts[2];
}
}
/// @notice Converts NRV rewards to ETH
function _liquidateNerveRewards() private returns (uint256 _yieldAmount) {
uint256 _balanceOfNRV = NRV.balanceOf(address(this));
_yieldAmount = 0;
if (_balanceOfNRV > 0) {
uint256[] memory _amounts = _swapExactTokensForTokens2(
address(NRV),
address(ETH),
_balanceOfNRV
);
_yieldAmount = _amounts[2];
}
}
/// @notice Function to swap tokens with PancakeSwap
/// @param _tokenA Token to be swapped
/// @param _tokenB Token to be received
/// @param _amountIn Amount of token to be swapped
/// @return _amounts Array that contains swapped amounts
function _swapExactTokensForTokens(
address _tokenA,
address _tokenB,
uint256 _amountIn
) private returns (uint256[] memory _amounts) {
address[] memory _path = _getPath(_tokenA, _tokenB);
uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut(
_amountIn,
_path
);
if (_amountsOut[1] > 0) {
_amounts = PANCAKE_ROUTER.swapExactTokensForTokens(
_amountIn,
0,
_path,
address(this),
block.timestamp
);
} else {
// Not enough amount to swap
uint256[] memory _zeroReturn = new uint256[](2);
_zeroReturn[0] = 0;
_zeroReturn[1] = 0;
return _zeroReturn;
}
}
/// @notice Function to swap Exotic tokens with PancakeSwap
/// @dev For tokens that cannot be swapped directly
/// @param _tokenA Token to be swapped
/// @param _tokenB Token to be received
/// @param _amountIn Amount of token to be swapped
/// @return _amounts Array that contains swapped amounts
function _swapExactTokensForTokens2(
address _tokenA,
address _tokenB,
uint256 _amountIn
) private returns (uint256[] memory _amounts) {
address[] memory _path = _getPath2(_tokenA, _tokenB);
uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut(
_amountIn,
_path
);
if (_amountsOut[2] > 0) {
_amounts = PANCAKE_ROUTER.swapExactTokensForTokens(
_amountIn,
0,
_path,
address(this),
block.timestamp
);
} else {
// Not enough amount to swap
uint256[] memory _zeroReturn = new uint256[](2);
_zeroReturn[0] = 0;
_zeroReturn[2] = 0;
return _zeroReturn;
}
}
/// @notice Function to get path for PancakeSwap swap functions
/// @param _tokenA Token to be swapped
/// @param _tokenB Token to be received
/// @return _path Array of address
function _getPath(address _tokenA, address _tokenB)
private
pure
returns (address[] memory)
{
address[] memory _path = new address[](2);
_path[0] = _tokenA;
_path[1] = _tokenB;
return _path;
}
/// @notice Function to get path for PancakeSwap swap functions, for exotic tokens
/// @param _tokenA Token to be swapped
/// @param _tokenB Token to be received
/// @return _path Array of address with WBNB in between
function _getPath2(address _tokenA, address _tokenB)
private
view
returns (address[] memory)
{
address[] memory _path = new address[](3);
_path[0] = _tokenA;
_path[1] = address(WBNB);
_path[2] = _tokenB;
return _path;
}
/// @notice Calculate price of 1 ETH-BETH LP in ETH
function _calcPriceETH_BETH_LP()
public
view
override
returns (uint256 _valueInEth)
{
uint256 _totalSupply = ETH_BETH_LP.totalSupply();
(uint256 _amountETH, uint256 _amountBETH, ) = ETH_BETH_LP.getReserves();
address[] memory _path = _getPath(address(BETH), address(ETH));
uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut(ONE, _path);
uint256 _priceBETH = _amountsOut[1];
uint256 _valueBETH = _amountBETH.mul(_priceBETH).div(1e18);
uint256 _totalAmount = _amountETH.add(_valueBETH);
_valueInEth = _totalAmount.mul(1e18).div(_totalSupply);
}
/// @notice Calculate price of 1 ETH-anyETH LP in ETH
function _calcPriceETH_ANYETH_LP()
public
view
override
returns (uint256 _valueInEth)
{
_valueInEth = NERVE_SWAP.getVirtualPrice(); // 1e18
}
/* ========== ADMIN FUNCTIONS ========== */
/// @notice Function to set new admin address from vault contract
/// @dev Only can set Once
/// @param _address Address of Vault
function setVault(address _address) external onlyOwner {
require(
address(vault) == address(0),
"Strategy::setVault:Vault already set"
);
vault = IVault(_address);
emit SetVault(_address);
}
/// @notice Function to set new admin address from vault contract
/// @param _address Address of new admin
function setAdmin(address _address) external override onlyVault {
admin = _address;
emit SetAdmin(_address);
}
/// @notice Function to set new strategist address from vault contract
/// @param _address Address of new strategist
function setStrategist(address _address) external override onlyVault {
strategist = _address;
emit SetStrategist(_address);
}
/// @notice Function to reimburse vault minimum keep amount by removing liquidity from all farms
function reimburse() external override onlyVault {
// Get total reimburse amount (6 decimals)
uint256 _reimburseAmount = vault.getMinimumKeep();
withdraw(_reimburseAmount);
}
/// @notice Function to reimburse vault minimum keep amount by removing liquidity from all farms
function emergencyWithdraw() external override onlyVault whenNotPaused {
(uint256 _amount_ETH_BETH_LP, , ) = WAULT_FARM.userInfo(
WAULT_PID,
address(this)
);
(uint256 _amount_ETH_ANYETH_LP, ) = NERVE_FARM.userInfo(
NERVE_PID,
address(this)
);
// Withdrawing automatically harvests yields
_withdrawWault(_amount_ETH_BETH_LP);
_withdrawNerve(_amount_ETH_ANYETH_LP);
(
uint256 _amountETHFromWault,
uint256 _amountBETH
) = _removeLiquidityWault(_amount_ETH_BETH_LP);
(
uint256 _amountETHFromNerve,
uint256 _amountANYETH
) = _removeLiquidityNerve(_amount_ETH_ANYETH_LP);
uint256 _totalRewards = _liquidateRewards(); // in ETH
uint256 _fees = _totalRewards.mul(yieldFeePerc).div(DENOMINATOR);
_splitYieldFees(_fees);
// Swap BETH and anyETH back to ETH
uint256 _amountETHFromBETH = _swapBETHforETH(_amountBETH);
uint256 _amountETHFromANYETH = _swapANYETHforETH(_amountANYETH);
uint256 _amountETH = __calcETH(
_amountETHFromWault,
_amountETHFromNerve,
_totalRewards,
_fees,
_amountETHFromBETH,
_amountETHFromANYETH
);
// Send deserved ETH back to Vault
ETH.safeTransfer(address(vault), _amountETH);
_pause();
}
function __calcETH(
uint256 a,
uint256 b,
uint256 c,
uint256 d,
uint256 e,
uint256 f
) private pure returns (uint256 _amountETH) {
_amountETH = a.add(b).add(c).sub(d).add(e);
_amountETH = _amountETH.add(f);
}
/// @notice Function to invest back WETH into farms after emergencyWithdraw()
function reinvest() external override onlyVault whenPaused {
_unpause();
}
}
| @notice Function to swap tokens with PancakeSwap @param _tokenA Token to be swapped @param _tokenB Token to be received @param _amountIn Amount of token to be swapped @return _amounts Array that contains swapped amounts Not enough amount to swap | function _swapExactTokensForTokens(
address _tokenA,
address _tokenB,
uint256 _amountIn
) private returns (uint256[] memory _amounts) {
address[] memory _path = _getPath(_tokenA, _tokenB);
uint256[] memory _amountsOut = PANCAKE_ROUTER.getAmountsOut(
_amountIn,
_path
);
if (_amountsOut[1] > 0) {
_amounts = PANCAKE_ROUTER.swapExactTokensForTokens(
_amountIn,
0,
_path,
address(this),
block.timestamp
);
uint256[] memory _zeroReturn = new uint256[](2);
_zeroReturn[0] = 0;
_zeroReturn[1] = 0;
return _zeroReturn;
}
}
| 6,472,822 | [
1,
2083,
358,
7720,
2430,
598,
12913,
23780,
12521,
225,
389,
2316,
37,
3155,
358,
506,
7720,
1845,
225,
389,
2316,
38,
3155,
358,
506,
5079,
225,
389,
8949,
382,
16811,
434,
1147,
358,
506,
7720,
1845,
327,
389,
8949,
87,
1510,
716,
1914,
7720,
1845,
30980,
2288,
7304,
3844,
358,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
389,
22270,
14332,
5157,
1290,
5157,
12,
203,
3639,
1758,
389,
2316,
37,
16,
203,
3639,
1758,
389,
2316,
38,
16,
203,
3639,
2254,
5034,
389,
8949,
382,
203,
565,
262,
3238,
1135,
261,
11890,
5034,
8526,
3778,
389,
8949,
87,
13,
288,
203,
3639,
1758,
8526,
3778,
389,
803,
273,
389,
588,
743,
24899,
2316,
37,
16,
389,
2316,
38,
1769,
203,
3639,
2254,
5034,
8526,
3778,
389,
8949,
87,
1182,
273,
453,
1258,
3587,
6859,
67,
1457,
1693,
654,
18,
588,
6275,
87,
1182,
12,
203,
5411,
389,
8949,
382,
16,
203,
5411,
389,
803,
203,
3639,
11272,
203,
3639,
309,
261,
67,
8949,
87,
1182,
63,
21,
65,
405,
374,
13,
288,
203,
5411,
389,
8949,
87,
273,
453,
1258,
3587,
6859,
67,
1457,
1693,
654,
18,
22270,
14332,
5157,
1290,
5157,
12,
203,
7734,
389,
8949,
382,
16,
203,
7734,
374,
16,
203,
7734,
389,
803,
16,
203,
7734,
1758,
12,
2211,
3631,
203,
7734,
1203,
18,
5508,
203,
5411,
11272,
203,
5411,
2254,
5034,
8526,
3778,
389,
7124,
990,
273,
394,
2254,
5034,
8526,
12,
22,
1769,
203,
5411,
389,
7124,
990,
63,
20,
65,
273,
374,
31,
203,
5411,
389,
7124,
990,
63,
21,
65,
273,
374,
31,
203,
5411,
327,
389,
7124,
990,
31,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "./deb/ERC20.sol";
import "./deb/ICrossDomainMessenger.sol";
import "./deb/StructLib.sol";
/// @title SourceDomainSideBridge Contract
/// @author Sherif Abdelmoatty
/// @notice This contract is to be deployed in the source rollup
contract SourceDomainSideBridge {
address constant ETHER_ADDRESS = 0x0000000000000000000000000000000000000000;
address constant ovmL2CrossDomainMessenger = 0x4200000000000000000000000000000000000007; //ovmL2CrossDomainMessenger contract address(Optimism Kovan)
uint constant public CONTRACT_FEE_BASIS_POINTS = 5; //fee basis points
uint constant public FIXED_FEE = 3002 gwei; //fixed fee - to discourage small transactions, and acts as a governance fee
uint constant public MAX_TRADE_LIMIT = 0.1 ether; //max allowed tokens to be transfered
mapping(bytes32 => bool) public validTransferHashes; //mapping of valid transfer hashes
mapping(bytes32 => bool) public knownHashOnions; //mapping of known hash onions
bytes32 processedRewardHashOnion; //the last known hash onion
address l1DomainSideContractAddress; //l1DomainSideContract deployed contract address on mainnet
uint256 currentNonce; //the number of transfer created
address public governance; //governance address - only to collect governance fees
uint256 governanceBalance; //governance balance
event Transaction(StructLib.TransferData transferData);
event ClaimPayed(bytes32 transferDataHash, bool success);
event NewKnownHashOnionAdded(bytes32 newKnownHashOnions);
/// @notice only allows a message from l1DomainSideBridge contract through the L2CrossDomainMessenger bridge
modifier onlyL1Contract(){
ICrossDomainMessenger l2cdm = ICrossDomainMessenger(ovmL2CrossDomainMessenger);
require(
msg.sender == address(ovmL2CrossDomainMessenger)
&& l2cdm.xDomainMessageSender() == l1DomainSideContractAddress
);
_;
}
/// @notice onlyGovernance modifier
/// @notice allow only the Governor to access
modifier onlyGovernance {
require(msg.sender == governance, "Governance: You are not the Governor!!!");
_;
}
/// @param _l1DomainSideContractAddress is the address of the contract in etherium/kovan L1
constructor(address _l1DomainSideContractAddress){
l1DomainSideContractAddress = _l1DomainSideContractAddress;
governance = msg.sender;
}
/// @notice transfer the required funds plus fees to be sent to the current contract balance
/// @param _tokenAddress at destination rollup
/// @param _destination is reciever address at the destination rollup
/// @param _amount is amount to be transfered in kwei
/// @param _startTime is a blocknumber in the future that this transaction can only be executed after
/// @param _feeRampup will be multiplied by the fee ramp up if the LP claimed and sent the transfer by the startTime block, and will decrease by one for each block after that
/// @return the hash of the valid transfer
function transfer(address _tokenAddress, address _destination, uint256 _amount,
uint256 _startTime, uint256 _feeRampup) external payable returns(bytes32){
uint256 fee = _amount * CONTRACT_FEE_BASIS_POINTS;
uint256 amountPlusFee = _amount * 1000 + fee;
require(fee * _feeRampup < _amount * 1000, "feeRampup maximum cost should be less than the total amount");
if(_tokenAddress == ETHER_ADDRESS){
require(_amount* 1000 < MAX_TRADE_LIMIT, "Amount higher than maximum trade limit");
require(msg.value >= amountPlusFee + FIXED_FEE, "No Suffecient ether");
}else{
ERC20 token = ERC20(_tokenAddress);
token.transferFrom(msg.sender, address(this), amountPlusFee);
require(msg.value >= FIXED_FEE, "No Suffecient ether for the fixed ether fee");
}
StructLib.TransferData memory transferData;
transferData.tokenAddress = _tokenAddress;
transferData.destination = _destination;
transferData.amount = _amount * 1000;
transferData.fee = fee;
if(_startTime < block.number){
transferData.startTime = block.number;
}else{
transferData.startTime = _startTime;
}
transferData.feeRampup = _feeRampup;
transferData.nonce = currentNonce;
currentNonce++;
governanceBalance = governanceBalance + FIXED_FEE/2;
bytes32 transferDataHash = sha256(abi.encode(transferData));
validTransferHashes[transferDataHash] = true;
emit Transaction(transferData);
return transferDataHash;
}
/// @notice process the processClaims structs to be paid to the liquidity providers
/// @param _rewardData is an array of RewardData structs to be paid to liquidity providers(emitted by the destination contract)
function processClaims(StructLib.RewardData[] memory _rewardData) external payable {
bytes32 newProcessedRewardHashOnion = calculateNewProcessedRewardHashOnion(_rewardData);
require(knownHashOnions[newProcessedRewardHashOnion], "Invalide RewardData list.");
processedRewardHashOnion = newProcessedRewardHashOnion;
for(uint n = 0; n < _rewardData.length; n++) {
if(validTransferHashes[_rewardData[n].transferDataHash]){
bool success;
if(_rewardData[n].tokenAddress == ETHER_ADDRESS){
(bool suc, ) = payable(_rewardData[n].claimer).call{value: _rewardData[n].amountPlusFee + FIXED_FEE/2}("");
success = suc;
}else{
ERC20 token = ERC20(_rewardData[n].tokenAddress);
success = token.transfer(_rewardData[n].claimer, _rewardData[n].amountPlusFee);
(bool suc, ) = payable(_rewardData[n].claimer).call{value: FIXED_FEE/2}("");
success = success && suc;
}
emit ClaimPayed(_rewardData[n].transferDataHash, success);
}
}
}
/// @notice this function is only called from the contract at the etherium L1
/// @notice through the rollup messenger contract to add a new known hash onion
function addNewKnownHashOnion(bytes32 _newKnownHashOnions) external onlyL1Contract{
knownHashOnions[_newKnownHashOnions] = true;
emit NewKnownHashOnionAdded(_newKnownHashOnions);
}
/// @notice get governance balance
/// @return governance balance
function GetGovernanceBalance() external view onlyGovernance returns(uint256){
return governanceBalance;
}
/// @notice collect governance fees
function collectGovernanceFixedFees() external onlyGovernance{
payable(governance).transfer(governanceBalance);
governanceBalance = 0;
}
/// @notice calculates the new hash onion
/// @param _rewardData is an array of RewardData structs to be paid to liquidity providers(emitted by the destination contract)
/// @return hash onion
function calculateNewProcessedRewardHashOnion(StructLib.RewardData[] memory _rewardData) private view returns (bytes32){
bytes32 newProcessedRewardHashOnion = processedRewardHashOnion;
for(uint n = 0; n < _rewardData.length; n++) {
newProcessedRewardHashOnion =
sha256(abi.encode(newProcessedRewardHashOnion,_rewardData[n]));
}
return newProcessedRewardHashOnion;
}
} | @notice collect governance fees | function collectGovernanceFixedFees() external onlyGovernance{
payable(governance).transfer(governanceBalance);
governanceBalance = 0;
}
| 12,550,875 | [
1,
14676,
314,
1643,
82,
1359,
1656,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3274,
43,
1643,
82,
1359,
7505,
2954,
281,
1435,
3903,
1338,
43,
1643,
82,
1359,
95,
203,
3639,
8843,
429,
12,
75,
1643,
82,
1359,
2934,
13866,
12,
75,
1643,
82,
1359,
13937,
1769,
203,
3639,
314,
1643,
82,
1359,
13937,
273,
374,
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
] |
./full_match/5/0xABcaaeBAdb32a03cA7Ec292103b4809fF677B857/sources/contracts/StrategyGenLevCompFarmWETH.sol | lets leaveif we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered | function prepareMigration(address _newStrategy) internal override {
if(!forceMigrate){
(uint256 deposits, uint256 borrows) = getLivePosition();
_withdrawSome(deposits.sub(borrows));
(, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));
require(borrowBalance < 10_000, "DELEVERAGE_FIRST");
IERC20 _comp = IERC20(comp);
uint _compB = _comp.balanceOf(address(this));
if(_compB > 0){
_comp.safeTransfer(_newStrategy, _compB);
}
}
}
| 1,859,545 | [
1,
17307,
8851,
430,
732,
848,
1404,
1464,
73,
5682,
316,
1245,
1960,
444,
4508,
2045,
287,
6837,
358,
374,
471,
745,
17895,
26923,
3229,
4124,
3180,
1464,
6084,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2911,
10224,
12,
2867,
389,
2704,
4525,
13,
2713,
3849,
288,
203,
203,
3639,
309,
12,
5,
5734,
19594,
15329,
203,
5411,
261,
11890,
5034,
443,
917,
1282,
16,
2254,
5034,
324,
280,
3870,
13,
273,
9014,
688,
2555,
5621,
203,
5411,
389,
1918,
9446,
17358,
12,
323,
917,
1282,
18,
1717,
12,
70,
280,
3870,
10019,
203,
203,
5411,
261,
16,
269,
2254,
5034,
29759,
13937,
16,
262,
273,
276,
1345,
18,
588,
3032,
4568,
12,
2867,
12,
2211,
10019,
203,
203,
5411,
2583,
12,
70,
15318,
13937,
411,
1728,
67,
3784,
16,
315,
1639,
900,
2204,
2833,
67,
15354,
8863,
203,
203,
5411,
467,
654,
39,
3462,
389,
2919,
273,
467,
654,
39,
3462,
12,
2919,
1769,
203,
5411,
2254,
389,
2919,
38,
273,
389,
2919,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
309,
24899,
2919,
38,
405,
374,
15329,
203,
7734,
389,
2919,
18,
4626,
5912,
24899,
2704,
4525,
16,
389,
2919,
38,
1769,
203,
5411,
289,
203,
3639,
289,
203,
540,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
contract Quorum {
uint public index;
// 여기다 나중에 주소 선언해주면 좋을듯
struct Person {
uint age;
string name;
uint index;
address Address;
}
Person[] people;
mapping(string => uint) number;
function createpeople(uint age, string memory name) public returns (uint){
Person memory person = Person(age, name, index, msg.sender);
people.push(person);
number[name] = index;
index ++;
}
function get(string memory name) public view returns (uint) {
return number[name];
}
//api 로 받아오는 부분
//arbitrage 논리 자체는 detect가 가능하다는 것으로 논리를 펼치기
function balancing(uint number_1, uint number_2) payable public {
uint parameter = (number_1 - number_2) / number_1 * 100 ;
if(parameter > 5) {
0xB63821320A1FA1ABf15d92C4561538e63f6ccdcC.transfer(parameter / 2);
}
else {
0xB63821320A1FA1ABf15d92C4561538e63f6ccdcC.transfer(1);
}
}
} | api 로 받아오는 부분arbitrage 논리 자체는 detect가 가능하다는 것으로 논리를 펼치기 | function balancing(uint number_1, uint number_2) payable public {
uint parameter = (number_1 - number_2) / number_1 * 100 ;
if(parameter > 5) {
0xB63821320A1FA1ABf15d92C4561538e63f6ccdcC.transfer(parameter / 2);
}
else {
0xB63821320A1FA1ABf15d92C4561538e63f6ccdcC.transfer(1);
}
}
| 12,924,483 | [
1,
2425,
225,
172,
99,
255,
225,
172,
113,
254,
173,
248,
231,
173,
251,
102,
172,
237,
247,
225,
172,
119,
227,
172,
119,
231,
297,
3682,
86,
410,
225,
172,
232,
125,
172,
104,
110,
225,
173,
257,
243,
173,
115,
117,
172,
237,
247,
5966,
171,
113,
227,
225,
171,
113,
227,
172,
237,
103,
174,
248,
251,
172,
238,
102,
172,
237,
247,
225,
171,
115,
230,
173,
255,
125,
172,
99,
255,
225,
172,
232,
125,
172,
104,
110,
172,
103,
125,
225,
174,
241,
125,
173,
122,
251,
171,
121,
113,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
324,
16142,
12,
11890,
1300,
67,
21,
16,
2254,
1300,
67,
22,
13,
8843,
429,
1071,
288,
203,
3639,
2254,
1569,
273,
261,
2696,
67,
21,
300,
1300,
67,
22,
13,
342,
1300,
67,
21,
380,
2130,
274,
203,
3639,
309,
12,
6775,
405,
1381,
13,
288,
203,
5411,
374,
20029,
4449,
28,
5340,
31273,
37,
21,
2046,
21,
2090,
74,
3600,
72,
9975,
39,
24,
4313,
3600,
7414,
73,
4449,
74,
26,
952,
7201,
39,
18,
13866,
12,
6775,
342,
576,
1769,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
374,
20029,
4449,
28,
5340,
31273,
37,
21,
2046,
21,
2090,
74,
3600,
72,
9975,
39,
24,
4313,
3600,
7414,
73,
4449,
74,
26,
952,
7201,
39,
18,
13866,
12,
21,
1769,
203,
3639,
289,
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
] |
./full_match/1/0x9D531816b38c77859FD3702F4E09e5d6C45B775e/sources/browser/FaasPool/ValueLiquidProfitCollector.sol | use balancer/vliquid use Uniswap path: _input -> valueToken | if (_pool != address(0)) {
IERC20(_input).safeApprove(_pool, 0);
IERC20(_input).safeApprove(_pool, _amount);
IBPool(_pool).swapExactAmountIn(_input, _amount, valueToken, 1, type(uint256).max);
address[] memory path = uniswapPaths[_input];
if (path.length == 0) {
path = new address[](2);
path[0] = _input;
path[1] = valueToken;
}
IERC20(_input).safeApprove(address(unirouter), 0);
IERC20(_input).safeApprove(address(unirouter), _amount);
unirouter.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(1800));
}
| 2,993,658 | [
1,
1202,
14887,
19,
90,
549,
26595,
999,
1351,
291,
91,
438,
589,
30,
389,
2630,
317,
460,
1345,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
309,
261,
67,
6011,
480,
1758,
12,
20,
3719,
288,
203,
5411,
467,
654,
39,
3462,
24899,
2630,
2934,
4626,
12053,
537,
24899,
6011,
16,
374,
1769,
203,
5411,
467,
654,
39,
3462,
24899,
2630,
2934,
4626,
12053,
537,
24899,
6011,
16,
389,
8949,
1769,
203,
5411,
23450,
2864,
24899,
6011,
2934,
22270,
14332,
6275,
382,
24899,
2630,
16,
389,
8949,
16,
460,
1345,
16,
404,
16,
618,
12,
11890,
5034,
2934,
1896,
1769,
203,
5411,
1758,
8526,
3778,
589,
273,
640,
291,
91,
438,
4466,
63,
67,
2630,
15533,
203,
5411,
309,
261,
803,
18,
2469,
422,
374,
13,
288,
203,
7734,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
7734,
589,
63,
20,
65,
273,
389,
2630,
31,
203,
7734,
589,
63,
21,
65,
273,
460,
1345,
31,
203,
5411,
289,
203,
5411,
467,
654,
39,
3462,
24899,
2630,
2934,
4626,
12053,
537,
12,
2867,
12,
318,
77,
10717,
3631,
374,
1769,
203,
5411,
467,
654,
39,
3462,
24899,
2630,
2934,
4626,
12053,
537,
12,
2867,
12,
318,
77,
10717,
3631,
389,
8949,
1769,
203,
5411,
7738,
10717,
18,
22270,
14332,
5157,
1290,
5157,
24899,
8949,
16,
404,
16,
589,
16,
1758,
12,
2211,
3631,
2037,
18,
1289,
12,
2643,
713,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-05-17
*/
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File contracts/OpenZeppelin/utils/ReentrancyGuard.sol
pragma solidity 0.6.12;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/OpenZeppelin/utils/EnumerableSet.sol
pragma solidity 0.6.12;
/**
* @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 contracts/OpenZeppelin/utils/Address.sol
pragma solidity 0.6.12;
/**
* @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 contracts/OpenZeppelin/utils/Context.sol
pragma solidity 0.6.12;
/*
* @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/OpenZeppelin/access/AccessControl.sol
pragma solidity 0.6.12;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @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 {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File contracts/Access/MISOAdminAccess.sol
pragma solidity 0.6.12;
contract MISOAdminAccess is AccessControl {
/// @dev Whether access is initialised.
bool private initAccess;
/// @notice Events for adding and removing various roles.
event AdminRoleGranted(
address indexed beneficiary,
address indexed caller
);
event AdminRoleRemoved(
address indexed beneficiary,
address indexed caller
);
/// @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses.
constructor() public {
}
/**
* @notice Initializes access controls.
* @param _admin Admins address.
*/
function initAccessControls(address _admin) public {
require(!initAccess, "Already initialised");
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
initAccess = true;
}
/////////////
// Lookups //
/////////////
/**
* @notice Used to check whether an address has the admin role.
* @param _address EOA or contract being checked.
* @return bool True if the account has the role or false if it does not.
*/
function hasAdminRole(address _address) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _address);
}
///////////////
// Modifiers //
///////////////
/**
* @notice Grants the admin role to an address.
* @dev The sender must have the admin role.
* @param _address EOA or contract receiving the new role.
*/
function addAdminRole(address _address) external {
grantRole(DEFAULT_ADMIN_ROLE, _address);
emit AdminRoleGranted(_address, _msgSender());
}
/**
* @notice Removes the admin role from an address.
* @dev The sender must have the admin role.
* @param _address EOA or contract affected.
*/
function removeAdminRole(address _address) external {
revokeRole(DEFAULT_ADMIN_ROLE, _address);
emit AdminRoleRemoved(_address, _msgSender());
}
}
// File contracts/Access/MISOAccessControls.sol
pragma solidity 0.6.12;
/**
* @notice Access Controls
* @author Attr: BlockRocket.tech
*/
contract MISOAccessControls is MISOAdminAccess {
/// @notice Role definitions
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
/// @notice Events for adding and removing various roles
event MinterRoleGranted(
address indexed beneficiary,
address indexed caller
);
event MinterRoleRemoved(
address indexed beneficiary,
address indexed caller
);
event OperatorRoleGranted(
address indexed beneficiary,
address indexed caller
);
event OperatorRoleRemoved(
address indexed beneficiary,
address indexed caller
);
event SmartContractRoleGranted(
address indexed beneficiary,
address indexed caller
);
event SmartContractRoleRemoved(
address indexed beneficiary,
address indexed caller
);
/**
* @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses
*/
constructor() public {
}
/////////////
// Lookups //
/////////////
/**
* @notice Used to check whether an address has the minter role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasMinterRole(address _address) public view returns (bool) {
return hasRole(MINTER_ROLE, _address);
}
/**
* @notice Used to check whether an address has the smart contract role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasSmartContractRole(address _address) public view returns (bool) {
return hasRole(SMART_CONTRACT_ROLE, _address);
}
/**
* @notice Used to check whether an address has the operator role
* @param _address EOA or contract being checked
* @return bool True if the account has the role or false if it does not
*/
function hasOperatorRole(address _address) public view returns (bool) {
return hasRole(OPERATOR_ROLE, _address);
}
///////////////
// Modifiers //
///////////////
/**
* @notice Grants the minter role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addMinterRole(address _address) external {
grantRole(MINTER_ROLE, _address);
emit MinterRoleGranted(_address, _msgSender());
}
/**
* @notice Removes the minter role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeMinterRole(address _address) external {
revokeRole(MINTER_ROLE, _address);
emit MinterRoleRemoved(_address, _msgSender());
}
/**
* @notice Grants the smart contract role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addSmartContractRole(address _address) external {
grantRole(SMART_CONTRACT_ROLE, _address);
emit SmartContractRoleGranted(_address, _msgSender());
}
/**
* @notice Removes the smart contract role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeSmartContractRole(address _address) external {
revokeRole(SMART_CONTRACT_ROLE, _address);
emit SmartContractRoleRemoved(_address, _msgSender());
}
/**
* @notice Grants the operator role to an address
* @dev The sender must have the admin role
* @param _address EOA or contract receiving the new role
*/
function addOperatorRole(address _address) external {
grantRole(OPERATOR_ROLE, _address);
emit OperatorRoleGranted(_address, _msgSender());
}
/**
* @notice Removes the operator role from an address
* @dev The sender must have the admin role
* @param _address EOA or contract affected
*/
function removeOperatorRole(address _address) external {
revokeRole(OPERATOR_ROLE, _address);
emit OperatorRoleRemoved(_address, _msgSender());
}
}
// File contracts/Utils/SafeTransfer.sol
pragma solidity 0.6.12;
contract SafeTransfer {
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Helper function to handle both ETH and ERC20 payments
function _safeTokenPayment(
address _token,
address payable _to,
uint256 _amount
) internal {
if (address(_token) == ETH_ADDRESS) {
_safeTransferETH(_to,_amount );
} else {
_safeTransfer(_token, _to, _amount);
}
}
/// @dev Helper function to handle both ETH and ERC20 payments
function _tokenPayment(
address _token,
address payable _to,
uint256 _amount
) internal {
if (address(_token) == ETH_ADDRESS) {
_to.transfer(_amount);
} else {
_safeTransfer(_token, _to, _amount);
}
}
/// @dev Transfer helper from UniswapV2 Router
function _safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
/**
* There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2
* Im trying to make it a habit to put external calls last (reentrancy)
* You can put this in an internal function if you like.
*/
function _safeTransfer(
address token,
address to,
uint256 amount
) internal virtual {
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory data) =
token.call(
// 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)"))
abi.encodeWithSelector(0xa9059cbb, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed
}
function _safeTransferFrom(
address token,
address from,
uint256 amount
) internal virtual {
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory data) =
token.call(
// 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)"))
abi.encodeWithSelector(0x23b872dd, from, address(this), amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed
}
function _safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function _safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/interfaces/IERC20.sol
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File contracts/Utils/BoringERC20.sol
pragma solidity 0.6.12;
// solhint-disable avoid-low-level-calls
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
/// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token symbol.
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
/// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token name.
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
/// @param token The address of the ERC-20 token contract.
/// @return (uint8) Token decimals.
function safeDecimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
// File contracts/Utils/BoringBatchable.sol
pragma solidity 0.6.12;
// solhint-disable avoid-low-level-calls
// solhint-disable no-inline-assembly
// Audit on 5-Jan-2021 by Keno and BoringCrypto
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
/// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.
/// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense
// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
// C3: The length of the loop is fully under user control, so can't be exploited
// C7: Delegatecall is only used on the same contract, so it's safe
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {
successes = new bool[](calls.length);
results = new bytes[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(calls[i]);
require(success || !revertOnFail, _getRevertMsg(result));
successes[i] = success;
results[i] = result;
}
}
}
contract BoringBatchable is BaseBoringBatchable {
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
// File contracts/Utils/BoringMath.sol
pragma solidity 0.6.12;
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "BoringMath: Div zero");
c = a / b;
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
function to16(uint256 a) internal pure returns (uint16 c) {
require(a <= uint16(-1), "BoringMath: uint16 Overflow");
c = uint16(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath16 {
function add(uint16 a, uint16 b) internal pure returns (uint16 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint16 a, uint16 b) internal pure returns (uint16 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
// File contracts/Utils/Documents.sol
pragma solidity 0.6.12;
/**
* @title Standard implementation of ERC1643 Document management
*/
contract Documents {
struct Document {
uint32 docIndex; // Store the document name indexes
uint64 lastModified; // Timestamp at which document details was last modified
string data; // data of the document that exist off-chain
}
// mapping to store the documents details in the document
mapping(string => Document) internal _documents;
// mapping to store the document name indexes
mapping(string => uint32) internal _docIndexes;
// Array use to store all the document name present in the contracts
string[] _docNames;
// Document Events
event DocumentRemoved(string indexed _name, string _data);
event DocumentUpdated(string indexed _name, string _data);
/**
* @notice Used to attach a new document to the contract, or update the data or hash of an existing attached document
* @dev Can only be executed by the owner of the contract.
* @param _name Name of the document. It should be unique always
* @param _data Off-chain data of the document from where it is accessible to investors/advisors to read.
*/
function _setDocument(string calldata _name, string calldata _data) internal {
require(bytes(_name).length > 0, "Zero name is not allowed");
require(bytes(_data).length > 0, "Should not be a empty data");
// Document storage document = _documents[_name];
if (_documents[_name].lastModified == uint64(0)) {
_docNames.push(_name);
_documents[_name].docIndex = uint32(_docNames.length);
}
_documents[_name] = Document(_documents[_name].docIndex, uint64(now), _data);
emit DocumentUpdated(_name, _data);
}
/**
* @notice Used to remove an existing document from the contract by giving the name of the document.
* @dev Can only be executed by the owner of the contract.
* @param _name Name of the document. It should be unique always
*/
function _removeDocument(string calldata _name) internal {
require(_documents[_name].lastModified != uint64(0), "Document should exist");
uint32 index = _documents[_name].docIndex - 1;
if (index != _docNames.length - 1) {
_docNames[index] = _docNames[_docNames.length - 1];
_documents[_docNames[index]].docIndex = index + 1;
}
_docNames.pop();
emit DocumentRemoved(_name, _documents[_name].data);
delete _documents[_name];
}
/**
* @notice Used to return the details of a document with a known name (`string`).
* @param _name Name of the document
* @return string The data associated with the document.
* @return uint256 the timestamp at which the document was last modified.
*/
function getDocument(string calldata _name) external view returns (string memory, uint256) {
return (
_documents[_name].data,
uint256(_documents[_name].lastModified)
);
}
/**
* @notice Used to retrieve a full list of documents attached to the smart contract.
* @return string List of all documents names present in the contract.
*/
function getAllDocuments() external view returns (string[] memory) {
return _docNames;
}
/**
* @notice Used to retrieve the total documents in the smart contract.
* @return uint256 Count of the document names present in the contract.
*/
function getDocumentCount() external view returns (uint256) {
return _docNames.length;
}
/**
* @notice Used to retrieve the document name from index in the smart contract.
* @return string Name of the document name.
*/
function getDocumentName(uint256 _index) external view returns (string memory) {
require(_index < _docNames.length, "Index out of bounds");
return _docNames[_index];
}
}
// File contracts/interfaces/IPointList.sol
pragma solidity 0.6.12;
// ----------------------------------------------------------------------------
// White List interface
// ----------------------------------------------------------------------------
interface IPointList {
function isInList(address account) external view returns (bool);
function hasPoints(address account, uint256 amount) external view returns (bool);
function setPoints(
address[] memory accounts,
uint256[] memory amounts
) external;
function initPointList(address accessControl) external ;
}
// File contracts/interfaces/IMisoMarket.sol
pragma solidity 0.6.12;
interface IMisoMarket {
function init(bytes calldata data) external payable;
function initMarket( bytes calldata data ) external;
function marketTemplate() external view returns (uint256);
}
// File contracts/Auctions/BatchAuction.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
//----------------------------------------------------------------------------------
// I n s t a n t
//
// .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo.
// .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo.
// .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO:
// .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO'
// 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO'
//
//----------------------------------------------------------------------------------
//
// Chef Gonpachi's Batch Auction
//
// An auction where contributions are swaped for a batch of tokens pro-rata
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// Made for Sushi.com
//
// Enjoy. (c) Chef Gonpachi, Kusatoshi, SSMikazu 2021
// <https://github.com/chefgonpachi/MISO/>
//
// ---------------------------------------------------------------------
// SPDX-License-Identifier: GPL-3.0
// ---------------------------------------------------------------------
/// @notice Attribution to delta.financial
/// @notice Attribution to dutchswap.com
contract BatchAuction is IMisoMarket, MISOAccessControls, BoringBatchable, SafeTransfer, Documents, ReentrancyGuard {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringMath64 for uint64;
using BoringERC20 for IERC20;
/// @notice MISOMarket template id for the factory contract.
/// @dev For different marketplace types, this must be incremented.
uint256 public constant override marketTemplate = 3;
/// @dev The placeholder ETH address.
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Main market variables.
struct MarketInfo {
uint64 startTime;
uint64 endTime;
uint128 totalTokens;
}
MarketInfo public marketInfo;
/// @notice Market dynamic variables.
struct MarketStatus {
uint128 commitmentsTotal;
uint128 minimumCommitmentAmount;
bool finalized;
bool usePointList;
}
MarketStatus public marketStatus;
address public auctionToken;
/// @notice The currency the crowdsale accepts for payment. Can be ETH or token address.
address public paymentCurrency;
/// @notice Address that manages auction approvals.
address public pointList;
address payable public wallet; // Where the auction funds will get paid
mapping(address => uint256) public commitments;
/// @notice Amount of tokens to claim per address.
mapping(address => uint256) public claimed;
/// @notice Event for updating auction times. Needs to be before auction starts.
event AuctionTimeUpdated(uint256 startTime, uint256 endTime);
/// @notice Event for updating auction prices. Needs to be before auction starts.
event AuctionPriceUpdated(uint256 minimumCommitmentAmount);
/// @notice Event for updating auction wallet. Needs to be before auction starts.
event AuctionWalletUpdated(address wallet);
/// @notice Event for adding a commitment.
event AddedCommitment(address addr, uint256 commitment);
/// @notice Event for finalization of the auction.
event AuctionFinalized();
/// @notice Event for cancellation of the auction.
event AuctionCancelled();
/**
* @notice Initializes main contract variables and transfers funds for the auction.
* @dev Init function.
* @param _funder The address that funds the token for crowdsale.
* @param _token Address of the token being sold.
* @param _totalTokens The total number of tokens to sell in auction.
* @param _startTime Auction start time.
* @param _endTime Auction end time.
* @param _paymentCurrency The currency the crowdsale accepts for payment. Can be ETH or token address.
* @param _minimumCommitmentAmount Minimum amount collected at which the auction will be successful.
* @param _admin Address that can finalize auction.
* @param _wallet Address where collected funds will be forwarded to.
*/
function initAuction(
address _funder,
address _token,
uint256 _totalTokens,
uint256 _startTime,
uint256 _endTime,
address _paymentCurrency,
uint256 _minimumCommitmentAmount,
address _admin,
address _pointList,
address payable _wallet
) public {
require(_startTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds");
require(_endTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds");
require(_startTime >= block.timestamp, "BatchAuction: start time is before current time");
require(_endTime > _startTime, "BatchAuction: end time must be older than start time");
require(_totalTokens > 0,"BatchAuction: total tokens must be greater than zero");
require(_admin != address(0), "BatchAuction: admin is the zero address");
require(_wallet != address(0), "BatchAuction: wallet is the zero address");
require(IERC20(_token).decimals() == 18, "BatchAuction: Token does not have 18 decimals");
if (_paymentCurrency != ETH_ADDRESS) {
require(IERC20(_paymentCurrency).decimals() > 0, "BatchAuction: Payment currency is not ERC20");
}
marketStatus.minimumCommitmentAmount = BoringMath.to128(_minimumCommitmentAmount);
marketInfo.startTime = BoringMath.to64(_startTime);
marketInfo.endTime = BoringMath.to64(_endTime);
marketInfo.totalTokens = BoringMath.to128(_totalTokens);
auctionToken = _token;
paymentCurrency = _paymentCurrency;
wallet = _wallet;
initAccessControls(_admin);
_setList(_pointList);
_safeTransferFrom(auctionToken, _funder, _totalTokens);
}
///--------------------------------------------------------
/// Commit to buying tokens!
///--------------------------------------------------------
receive() external payable {
revertBecauseUserDidNotProvideAgreement();
}
/**
* @dev Attribution to the awesome delta.financial contracts
*/
function marketParticipationAgreement() public pure returns (string memory) {
return "I understand that I am interacting with a smart contract. I understand that tokens commited are subject to the token issuer and local laws where applicable. I have reviewed the code of this smart contract and understand it fully. I agree to not hold developers or other people associated with the project liable for any losses or misunderstandings";
}
/**
* @dev Not using modifiers is a purposeful choice for code readability.
*/
function revertBecauseUserDidNotProvideAgreement() internal pure {
revert("No agreement provided, please review the smart contract before interacting with it");
}
/**
* @notice Commit ETH to buy tokens on auction.
* @param _beneficiary Auction participant ETH address.
*/
function commitEth(address payable _beneficiary, bool readAndAgreedToMarketParticipationAgreement) public payable {
require(paymentCurrency == ETH_ADDRESS, "BatchAuction: payment currency is not ETH");
require(msg.value > 0, "BatchAuction: Value must be higher than 0");
if(readAndAgreedToMarketParticipationAgreement == false) {
revertBecauseUserDidNotProvideAgreement();
}
_addCommitment(_beneficiary, msg.value);
}
/**
* @notice Buy Tokens by commiting approved ERC20 tokens to this contract address.
* @param _amount Amount of tokens to commit.
*/
function commitTokens(uint256 _amount, bool readAndAgreedToMarketParticipationAgreement) public {
commitTokensFrom(msg.sender, _amount, readAndAgreedToMarketParticipationAgreement);
}
/**
* @notice Checks if amout not 0 and makes the transfer and adds commitment.
* @dev Users must approve contract prior to committing tokens to auction.
* @param _from User ERC20 address.
* @param _amount Amount of approved ERC20 tokens.
*/
function commitTokensFrom(address _from, uint256 _amount, bool readAndAgreedToMarketParticipationAgreement) public nonReentrant {
require(paymentCurrency != ETH_ADDRESS, "BatchAuction: Payment currency is not a token");
if(readAndAgreedToMarketParticipationAgreement == false) {
revertBecauseUserDidNotProvideAgreement();
}
require(_amount> 0, "BatchAuction: Value must be higher than 0");
_safeTransferFrom(paymentCurrency, msg.sender, _amount);
_addCommitment(_from, _amount);
}
/// @notice Commits to an amount during an auction
/**
* @notice Updates commitment for this address and total commitment of the auction.
* @param _addr Auction participant address.
* @param _commitment The amount to commit.
*/
function _addCommitment(address _addr, uint256 _commitment) internal {
require(block.timestamp >= marketInfo.startTime && block.timestamp <= marketInfo.endTime, "BatchAuction: outside auction hours");
uint256 newCommitment = commitments[_addr].add(_commitment);
if (marketStatus.usePointList) {
require(IPointList(pointList).hasPoints(_addr, newCommitment));
}
commitments[_addr] = newCommitment;
marketStatus.commitmentsTotal = BoringMath.to128(uint256(marketStatus.commitmentsTotal).add(_commitment));
emit AddedCommitment(_addr, _commitment);
}
/**
* @notice Calculates amount of auction tokens for user to receive.
* @param amount Amount of tokens to commit.
* @return Auction token amount.
*/
function _getTokenAmount(uint256 amount) internal view returns (uint256) {
if (marketStatus.commitmentsTotal == 0) return 0;
return amount.mul(1e18).div(tokenPrice());
}
/**
* @notice Calculates the price of each token from all commitments.
* @return Token price.
*/
function tokenPrice() public view returns (uint256) {
return uint256(marketStatus.commitmentsTotal).mul(1e18).div(uint256(marketInfo.totalTokens));
}
///--------------------------------------------------------
/// Finalize Auction
///--------------------------------------------------------
/// @notice Auction finishes successfully above the reserve
/// @dev Transfer contract funds to initialized wallet.
function finalize() public nonReentrant
{
require(hasAdminRole(msg.sender)
|| wallet == msg.sender
|| hasSmartContractRole(msg.sender)
|| finalizeTimeExpired(), "BatchAuction: Sender must be admin");
require(!marketStatus.finalized, "BatchAuction: Auction has already finalized");
require(block.timestamp > marketInfo.endTime, "BatchAuction: Auction has not finished yet");
if (auctionSuccessful()) {
/// @dev Successful auction
/// @dev Transfer contributed tokens to wallet.
_safeTokenPayment(paymentCurrency, wallet, uint256(marketStatus.commitmentsTotal));
} else {
/// @dev Failed auction
/// @dev Return auction tokens back to wallet.
require(block.timestamp > marketInfo.endTime, "BatchAuction: Auction has not finished yet");
_safeTokenPayment(auctionToken, wallet, marketInfo.totalTokens);
}
marketStatus.finalized = true;
emit AuctionFinalized();
}
/**
* @notice Cancel Auction
* @dev Admin can cancel the auction before it starts
*/
function cancelAuction() public nonReentrant
{
require(hasAdminRole(msg.sender));
MarketStatus storage status = marketStatus;
require(!status.finalized, "Crowdsale: already finalized");
require( uint256(status.commitmentsTotal) == 0, "Crowdsale: Funds already raised" );
_safeTokenPayment(auctionToken, wallet, uint256(marketInfo.totalTokens));
status.finalized = true;
emit AuctionCancelled();
}
/// @notice Withdraws bought tokens, or returns commitment if the sale is unsuccessful.
function withdrawTokens() public {
withdrawTokens(msg.sender);
}
/// @notice Withdraw your tokens once the Auction has ended.
function withdrawTokens(address payable beneficiary) public nonReentrant {
if (auctionSuccessful()) {
require(marketStatus.finalized, "BatchAuction: not finalized");
/// @dev Successful auction! Transfer claimed tokens.
uint256 tokensToClaim = tokensClaimable(beneficiary);
require(tokensToClaim > 0, "BatchAuction: No tokens to claim");
claimed[beneficiary] = claimed[beneficiary].add(tokensToClaim);
_safeTokenPayment(auctionToken, beneficiary, tokensToClaim);
} else {
/// @dev Auction did not meet reserve price.
/// @dev Return committed funds back to user.
require(block.timestamp > marketInfo.endTime, "BatchAuction: Auction has not finished yet");
uint256 fundsCommitted = commitments[beneficiary];
require(fundsCommitted > 0, "BatchAuction: No funds committed");
commitments[beneficiary] = 0; // Stop multiple withdrawals and free some gas
_safeTokenPayment(paymentCurrency, beneficiary, fundsCommitted);
}
}
/**
* @notice How many tokens the user is able to claim.
* @param _user Auction participant address.
* @return Tokens left to claim.
*/
function tokensClaimable(address _user) public view returns (uint256) {
if (commitments[_user] == 0) return 0;
uint256 tokensAvailable = _getTokenAmount(commitments[_user]);
return tokensAvailable.sub(claimed[_user]);
}
/**
* @notice Checks if raised more than minimum amount.
* @return True if tokens sold greater than or equals to the minimum commitment amount.
*/
function auctionSuccessful() public view returns (bool) {
return uint256(marketStatus.commitmentsTotal) >= uint256(marketStatus.minimumCommitmentAmount) && uint256(marketStatus.commitmentsTotal) > 0;
}
/**
* @notice Checks if the auction has ended.
* @return bool True if current time is greater than auction end time.
*/
function auctionEnded() public view returns (bool) {
return block.timestamp > marketInfo.endTime;
}
/**
* @notice Checks if the auction has been finalised.
* @return bool True if auction has been finalised.
*/
function finalized() public view returns (bool) {
return marketStatus.finalized;
}
/// @notice Returns true if 7 days have passed since the end of the auction
function finalizeTimeExpired() public view returns (bool) {
return uint256(marketInfo.endTime) + 7 days < block.timestamp;
}
//--------------------------------------------------------
// Documents
//--------------------------------------------------------
function setDocument(string calldata _name, string calldata _data) external {
require(hasAdminRole(msg.sender) );
_setDocument( _name, _data);
}
function setDocuments(string[] calldata _name, string[] calldata _data) external {
require(hasAdminRole(msg.sender) );
uint256 numDocs = _name.length;
for (uint256 i = 0; i < numDocs; i++) {
_setDocument( _name[i], _data[i]);
}
}
function removeDocument(string calldata _name) external {
require(hasAdminRole(msg.sender));
_removeDocument(_name);
}
//--------------------------------------------------------
// Point Lists
//--------------------------------------------------------
function setList(address _list) external {
require(hasAdminRole(msg.sender));
_setList(_list);
}
function enableList(bool _status) external {
require(hasAdminRole(msg.sender));
marketStatus.usePointList = _status;
}
function _setList(address _pointList) private {
if (_pointList != address(0)) {
pointList = _pointList;
marketStatus.usePointList = true;
}
}
//--------------------------------------------------------
// Setter Functions
//--------------------------------------------------------
/**
* @notice Admin can set start and end time through this function.
* @param _startTime Auction start time.
* @param _endTime Auction end time.
*/
function setAuctionTime(uint256 _startTime, uint256 _endTime) external {
require(hasAdminRole(msg.sender));
require(_startTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds");
require(_endTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds");
require(_startTime >= block.timestamp, "BatchAuction: start time is before current time");
require(_endTime > _startTime, "BatchAuction: end time must be older than start price");
require(marketStatus.commitmentsTotal == 0, "BatchAuction: auction cannot have already started");
marketInfo.startTime = BoringMath.to64(_startTime);
marketInfo.endTime = BoringMath.to64(_endTime);
emit AuctionTimeUpdated(_startTime,_endTime);
}
/**
* @notice Admin can set start and min price through this function.
* @param _minimumCommitmentAmount Auction minimum raised target.
*/
function setAuctionPrice(uint256 _minimumCommitmentAmount) external {
require(hasAdminRole(msg.sender));
require(marketStatus.commitmentsTotal == 0, "BatchAuction: auction cannot have already started");
marketStatus.minimumCommitmentAmount = BoringMath.to128(_minimumCommitmentAmount);
emit AuctionPriceUpdated(_minimumCommitmentAmount);
}
/**
* @notice Admin can set the auction wallet through this function.
* @param _wallet Auction wallet is where funds will be sent.
*/
function setAuctionWallet(address payable _wallet) external {
require(hasAdminRole(msg.sender));
require(_wallet != address(0), "BatchAuction: wallet is the zero address");
wallet = _wallet;
emit AuctionWalletUpdated(_wallet);
}
//--------------------------------------------------------
// Market Launchers
//--------------------------------------------------------
function init(bytes calldata _data) external override payable {
}
function initMarket(
bytes calldata _data
) public override {
(
address _funder,
address _token,
uint256 _totalTokens,
uint256 _startTime,
uint256 _endTime,
address _paymentCurrency,
uint256 _minimumCommitmentAmount,
address _admin,
address _pointList,
address payable _wallet
) = abi.decode(_data, (
address,
address,
uint256,
uint256,
uint256,
address,
uint256,
address,
address,
address
));
initAuction(_funder, _token, _totalTokens, _startTime, _endTime, _paymentCurrency, _minimumCommitmentAmount, _admin, _pointList, _wallet);
}
function getBatchAuctionInitData(
address _funder,
address _token,
uint256 _totalTokens,
uint256 _startTime,
uint256 _endTime,
address _paymentCurrency,
uint256 _minimumCommitmentAmount,
address _admin,
address _pointList,
address payable _wallet
)
external
pure
returns (bytes memory _data)
{
return abi.encode(
_funder,
_token,
_totalTokens,
_startTime,
_endTime,
_paymentCurrency,
_minimumCommitmentAmount,
_admin,
_pointList,
_wallet
);
}
function getBaseInformation() external view returns(
address token,
uint64 startTime,
uint64 endTime,
bool marketFinalized
) {
return (auctionToken, marketInfo.startTime, marketInfo.endTime, marketStatus.finalized);
}
function getTotalTokens() external view returns(uint256) {
return uint256(marketInfo.totalTokens);
}
} | * @notice Calculates the price of each token from all commitments. @return Token price./ | function tokenPrice() public view returns (uint256) {
return uint256(marketStatus.commitmentsTotal).mul(1e18).div(uint256(marketInfo.totalTokens));
}
| 15,033,934 | [
1,
10587,
326,
6205,
434,
1517,
1147,
628,
777,
3294,
1346,
18,
327,
3155,
6205,
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
] | [
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,
1147,
5147,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
2254,
5034,
12,
27151,
1482,
18,
7371,
1346,
5269,
2934,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
11890,
5034,
12,
27151,
966,
18,
4963,
5157,
10019,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.4;
contract ModelRepository {
Model[] models;
Gradient[] grads;
// Structs
struct IPFS {
bytes32 first;
bytes32 second;
}
struct Gradient {
bool evaluated;
// submitted from miner
address from;
IPFS grad;
uint modelId;
// submitted from trainer
uint newModelError;
IPFS newWeights;
}
struct Model {
address owner;
IPFS initialWeights;
IPFS weights;
uint bounty;
uint initialError;
uint bestError;
uint targetError;
}
// Modifiers
modifier onlyByModelOwner(uint gradientId) {
require(msg.sender == models[grads[gradientId].modelId].owner);
_;
}
modifier onlyIfGradientNotYetEvaluated(uint gradientId) {
require(grads[gradientId].evaluated == false);
_;
}
// Functions
/// @dev Transfers currency from this contract to the receiver's address.
/// @param receiver Address of receiver.
/// @param amount Amount of currency to be transferred.
function transferAmount(address receiver, uint amount) private {
assert(receiver.send(amount));
}
/// @notice Adds a new model to the blockchain.
/// @dev Model is associated to bounty and sender.
/// @param weights Model's initial weights' IPFS address.
/// @param initialError Model's initial error value.
/// @param targetError Model's target error value.
function addModel(bytes32[] weights, uint initialError, uint targetError) public payable {
IPFS memory ipfsWeights;
ipfsWeights.first = weights[0];
ipfsWeights.second = weights[1];
Model memory newModel;
newModel.weights = ipfsWeights;
newModel.initialWeights = ipfsWeights;
newModel.bounty = msg.value;
newModel.owner = msg.sender;
newModel.initialError = initialError;
newModel.bestError = initialError;
newModel.targetError = targetError;
models.push(newModel);
}
/// @notice Calculates the incentive to be payed to the miner based on the
/// solved error, the model's bounty and the model's total error.
/// @dev Incentive is calculated as a percentage of total error solved, times
/// the total bounty.
/// @param bounty Model's associated bounty.
/// @param totalError Model's total error.
/// @param solvedError Total error solved by miner.
/// @return The calculated incentive.
function calculateIncentive(uint bounty, uint totalError, uint solvedError) pure public returns(uint total) {
return (bounty*solvedError) / totalError;
}
/// @notice Evaluates if gradient with given id, resulting error and weights.
/// Then, decreases the model error and pays the miner accordingly.
/// @dev Miner is payed only if model's best error hasn't reached targetError.
/// @param gradientId Id of the gradient to be evaluated.
/// @param newModelError New error of gradient to be evaluated.
/// @param newWeightsAddress IPFS address of the new weights.
function evalGradient(uint gradientId, uint newModelError, bytes32[] newWeightsAddress) onlyByModelOwner(gradientId) onlyIfGradientNotYetEvaluated(gradientId) public {
grads[gradientId].newWeights.first = newWeightsAddress[0];
grads[gradientId].newWeights.second = newWeightsAddress[1];
grads[gradientId].newModelError = newModelError;
Model storage model = models[grads[gradientId].modelId];
if (newModelError < model.bestError && model.targetError < model.bestError) {
uint totalError = model.initialError - model.targetError;
uint solvedError = model.bestError - newModelError;
uint incentive = calculateIncentive(model.bounty, totalError, solvedError);
model.bestError = newModelError;
model.weights = grads[gradientId].newWeights;
transferAmount(grads[gradientId].from, incentive);
}
grads[gradientId].evaluated = true;
}
/// @notice Adds a new gradient to the blockchain.
/// @dev Submitted gradient's new weights and new model error are set to
/// zero.
/// @param modelId Id of the model to which the new gradients correspond.
/// @param gradientAddress IPFS address of the gradient being added.
function addGradient(uint modelId, bytes32[] gradientAddress) public {
require(models[modelId].owner != 0);
IPFS memory ipfsGradientAddress;
ipfsGradientAddress.first = gradientAddress[0];
ipfsGradientAddress.second = gradientAddress[1];
IPFS memory newWeights;
newWeights.first = bytes32(0);
newWeights.second = bytes32(0);
Gradient memory newGrad;
newGrad.grad = ipfsGradientAddress;
newGrad.from = msg.sender;
newGrad.modelId = modelId;
newGrad.newModelError = 0;
newGrad.newWeights = newWeights;
newGrad.evaluated = false;
grads.push(newGrad);
}
/// @notice Return the number of models stored in the blockchain.
/// @return The number of models stored in the blockchain.
function getNumModels() constant public returns(uint256 modelCount) {
return models.length;
}
/// @notice Return the number of gradients in the blockchain for model with
/// given id.
/// @return The number of gradients in the blockchain for model with
/// given id.
function getNumGradientsforModel(uint modelId) constant public returns (uint num) {
num = 0;
for (uint i = 0; i<grads.length; i++) {
if (grads[i].modelId == modelId) {
num += 1;
}
}
return num;
}
/// @notice Return the gradient with given id associated to model with given
/// model id.
/// @param modelId Id of model to be queried.
/// @param gradientId Id of gradient for given model.
/// @return The queried gradient as a tuple with form (index in array, from address, gradient address, gradient's new model error, gradient's weight address).
function getGradient(uint modelId, uint gradientId) constant public returns (uint, address, bytes32[], uint, bytes32[]) {
uint num = 0;
for (uint i = 0; i<grads.length; i++) {
if (grads[i].modelId == modelId) {
if (num == gradientId) {
bytes32[] memory gradientAddress = new bytes32[](2);
gradientAddress[0] = grads[i].grad.first;
gradientAddress[1] = grads[i].grad.second;
bytes32[] memory weightsAddress = new bytes32[](2);
weightsAddress[0] = grads[i].newWeights.first;
weightsAddress[1] = grads[i].newWeights.second;
return (i, grads[i].from, gradientAddress, grads[i].newModelError, weightsAddress);
}
num += 1;
}
}
}
/// @notice Return the model with given unique id.
/// @param modelId Id of model to be retrieved.
/// @return The model associated to the id, as a tuple with form (owner, bounty, initialError, targetError, weight address).
function getModel(uint modelId) constant public returns (address,uint,uint,uint,bytes32[]) {
Model memory currentModel;
currentModel = models[modelId];
bytes32[] memory weights = new bytes32[](2);
weights[0] = currentModel.weights.first;
weights[1] = currentModel.weights.second;
return (currentModel.owner, currentModel.bounty, currentModel.initialError, currentModel.targetError, weights);
}
}
| @notice Return the gradient with given id associated to model with given model id. @param modelId Id of model to be queried. @param gradientId Id of gradient for given model. @return The queried gradient as a tuple with form (index in array, from address, gradient address, gradient's new model error, gradient's weight address). | function getGradient(uint modelId, uint gradientId) constant public returns (uint, address, bytes32[], uint, bytes32[]) {
uint num = 0;
for (uint i = 0; i<grads.length; i++) {
if (grads[i].modelId == modelId) {
if (num == gradientId) {
bytes32[] memory gradientAddress = new bytes32[](2);
gradientAddress[0] = grads[i].grad.first;
gradientAddress[1] = grads[i].grad.second;
bytes32[] memory weightsAddress = new bytes32[](2);
weightsAddress[0] = grads[i].newWeights.first;
weightsAddress[1] = grads[i].newWeights.second;
return (i, grads[i].from, gradientAddress, grads[i].newModelError, weightsAddress);
}
num += 1;
}
}
}
| 6,379,987 | [
1,
990,
326,
10292,
598,
864,
612,
3627,
358,
938,
598,
864,
938,
612,
18,
225,
25468,
3124,
434,
938,
358,
506,
23264,
18,
225,
10292,
548,
3124,
434,
10292,
364,
864,
938,
18,
327,
1021,
23264,
10292,
487,
279,
3193,
598,
646,
261,
1615,
316,
526,
16,
628,
1758,
16,
10292,
1758,
16,
10292,
1807,
394,
938,
555,
16,
10292,
1807,
3119,
1758,
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,
225,
445,
7162,
12573,
12,
11890,
25468,
16,
2254,
10292,
548,
13,
5381,
1071,
1135,
261,
11890,
16,
1758,
16,
1731,
1578,
63,
6487,
2254,
16,
1731,
1578,
63,
5717,
288,
203,
565,
2254,
818,
273,
374,
31,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
32,
2752,
2377,
18,
2469,
31,
277,
27245,
288,
203,
1377,
309,
261,
2752,
2377,
63,
77,
8009,
2284,
548,
422,
25468,
13,
288,
203,
3639,
309,
261,
2107,
422,
10292,
548,
13,
288,
203,
203,
1850,
1731,
1578,
8526,
3778,
10292,
1887,
273,
394,
1731,
1578,
8526,
12,
22,
1769,
203,
203,
1850,
10292,
1887,
63,
20,
65,
273,
3087,
2377,
63,
77,
8009,
9974,
18,
3645,
31,
203,
1850,
10292,
1887,
63,
21,
65,
273,
3087,
2377,
63,
77,
8009,
9974,
18,
8538,
31,
203,
203,
1850,
1731,
1578,
8526,
3778,
5376,
1887,
273,
394,
1731,
1578,
8526,
12,
22,
1769,
203,
1850,
5376,
1887,
63,
20,
65,
273,
3087,
2377,
63,
77,
8009,
2704,
16595,
18,
3645,
31,
203,
1850,
5376,
1887,
63,
21,
65,
273,
3087,
2377,
63,
77,
8009,
2704,
16595,
18,
8538,
31,
203,
203,
1850,
327,
261,
77,
16,
3087,
2377,
63,
77,
8009,
2080,
16,
10292,
1887,
16,
3087,
2377,
63,
77,
8009,
2704,
1488,
668,
16,
5376,
1887,
1769,
203,
3639,
289,
203,
3639,
818,
1011,
404,
31,
203,
1377,
289,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-10-11
*/
// File: solidity/contracts/utility/interfaces/IOwned.sol
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
/*
Owned contract interface
*/
interface IOwned {
// this function isn't since the compiler emits automatically generated getter functions as external
function owner() external view returns (address);
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
}
// File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
pragma solidity 0.6.12;
/*
Converter Anchor interface
*/
interface IConverterAnchor is IOwned {
}
// File: solidity/contracts/token/interfaces/IERC20Token.sol
pragma solidity 0.6.12;
/*
ERC20 Standard Token interface
*/
interface IERC20Token {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
}
// File: solidity/contracts/utility/interfaces/IWhitelist.sol
pragma solidity 0.6.12;
/*
Whitelist interface
*/
interface IWhitelist {
function isWhitelisted(address _address) external view returns (bool);
}
// File: solidity/contracts/converter/interfaces/IConverter.sol
pragma solidity 0.6.12;
/*
Converter interface
*/
interface IConverter is IOwned {
function converterType() external pure returns (uint16);
function anchor() external view returns (IConverterAnchor);
function isActive() external view returns (bool);
function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) external view returns (uint256, uint256);
function convert(IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary) external payable returns (uint256);
function conversionWhitelist() external view returns (IWhitelist);
function conversionFee() external view returns (uint32);
function maxConversionFee() external view returns (uint32);
function reserveBalance(IERC20Token _reserveToken) external view returns (uint256);
receive() external payable;
function transferAnchorOwnership(address _newOwner) external;
function acceptAnchorOwnership() external;
function setConversionFee(uint32 _conversionFee) external;
function setConversionWhitelist(IWhitelist _whitelist) external;
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) external;
function withdrawETH(address payable _to) external;
function addReserve(IERC20Token _token, uint32 _ratio) external;
// deprecated, backward compatibility
function token() external view returns (IConverterAnchor);
function transferTokenOwnership(address _newOwner) external;
function acceptTokenOwnership() external;
function connectors(IERC20Token _address) external view returns (uint256, uint32, bool, bool, bool);
function getConnectorBalance(IERC20Token _connectorToken) external view returns (uint256);
function connectorTokens(uint256 _index) external view returns (IERC20Token);
function connectorTokenCount() external view returns (uint16);
}
// File: solidity/contracts/converter/interfaces/IConverterUpgrader.sol
pragma solidity 0.6.12;
/*
Converter Upgrader interface
*/
interface IConverterUpgrader {
function upgrade(bytes32 _version) external;
function upgrade(uint16 _version) external;
}
// File: solidity/contracts/converter/interfaces/IBancorFormula.sol
pragma solidity 0.6.12;
/*
Bancor Formula interface
*/
interface IBancorFormula {
function purchaseTargetAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
external view returns (uint256);
function saleTargetAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount)
external view returns (uint256);
function crossReserveTargetAmount(uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount)
external view returns (uint256);
function fundCost(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
external view returns (uint256);
function fundSupplyAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
external view returns (uint256);
function liquidateReserveAmount(uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount)
external view returns (uint256);
function balancedWeights(uint256 _primaryReserveStakedBalance,
uint256 _primaryReserveBalance,
uint256 _secondaryReserveBalance,
uint256 _reserveRateNumerator,
uint256 _reserveRateDenominator)
external view returns (uint32, uint32);
}
// File: solidity/contracts/utility/Owned.sol
pragma solidity 0.6.12;
/**
* @dev Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public override owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() internal view {
require(msg.sender == owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public override ownerOnly {
require(_newOwner != owner, "ERR_SAME_OWNER");
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() override public {
require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// File: solidity/contracts/utility/Utils.sol
pragma solidity 0.6.12;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
// 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 {
require(_value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
_validAddress(_address);
_;
}
// error message binary size optimization
function _validAddress(address _address) internal pure {
require(_address != address(0), "ERR_INVALID_ADDRESS");
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
_notThis(_address);
_;
}
// error message binary size optimization
function _notThis(address _address) internal view {
require(_address != address(this), "ERR_ADDRESS_IS_SELF");
}
}
// File: solidity/contracts/utility/interfaces/IContractRegistry.sol
pragma solidity 0.6.12;
/*
Contract Registry interface
*/
interface IContractRegistry {
function addressOf(bytes32 _contractName) external view returns (address);
}
// File: solidity/contracts/utility/ContractRegistryClient.sol
pragma solidity 0.6.12;
/**
* @dev Base contract for ContractRegistry clients
*/
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
bytes32 internal constant CHAINLINK_ORACLE_WHITELIST = "ChainlinkOracleWhitelist";
IContractRegistry public registry; // address of the current contract-registry
IContractRegistry public prevRegistry; // address of the previous contract-registry
bool public onlyOwnerCanUpdateRegistry; // only an owner can update the contract-registry
/**
* @dev verifies that the caller is mapped to the given contract name
*
* @param _contractName contract name
*/
modifier only(bytes32 _contractName) {
_only(_contractName);
_;
}
// error message binary size optimization
function _only(bytes32 _contractName) internal view {
require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED");
}
/**
* @dev initializes a new ContractRegistryClient instance
*
* @param _registry address of a contract-registry contract
*/
constructor(IContractRegistry _registry) internal validAddress(address(_registry)) {
registry = IContractRegistry(_registry);
prevRegistry = IContractRegistry(_registry);
}
/**
* @dev updates to the new contract-registry
*/
function updateRegistry() public {
// verify that this function is permitted
require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
// get the new contract-registry
IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
// verify that the new contract-registry is different and not zero
require(newRegistry != registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY");
// verify that the new contract-registry is pointing to a non-zero contract-registry
require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
// save a backup of the current contract-registry before replacing it
prevRegistry = registry;
// replace the current contract-registry with the new contract-registry
registry = newRegistry;
}
/**
* @dev restores the previous contract-registry
*/
function restoreRegistry() public ownerOnly {
// restore the previous contract-registry
registry = prevRegistry;
}
/**
* @dev restricts the permission to update the contract-registry
*
* @param _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only
*/
function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly {
// change the permission to update the contract-registry
onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
}
/**
* @dev returns the address associated with the given contract name
*
* @param _contractName contract name
*
* @return contract address
*/
function addressOf(bytes32 _contractName) internal view returns (address) {
return registry.addressOf(_contractName);
}
}
// File: solidity/contracts/utility/ReentrancyGuard.sol
pragma solidity 0.6.12;
/**
* @dev ReentrancyGuard
*
* The contract provides protection against re-entrancy - calling a function (directly or
* indirectly) from within itself.
*/
contract ReentrancyGuard {
uint256 private constant UNLOCKED = 1;
uint256 private constant LOCKED = 2;
// LOCKED while protected code is being executed, UNLOCKED otherwise
uint256 private state = UNLOCKED;
/**
* @dev ensures instantiation only by sub-contracts
*/
constructor() internal {}
// protects a function against reentrancy attacks
modifier protected() {
_protected();
state = LOCKED;
_;
state = UNLOCKED;
}
// error message binary size optimization
function _protected() internal view {
require(state == UNLOCKED, "ERR_REENTRANCY");
}
}
// File: solidity/contracts/utility/SafeMath.sol
pragma solidity 0.6.12;
/**
* @dev Library for basic math operations with overflow/underflow protection
*/
library SafeMath {
/**
* @dev returns the sum of _x and _y, reverts if the calculation overflows
*
* @param _x value 1
* @param _y value 2
*
* @return sum
*/
function add(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
require(z >= _x, "ERR_OVERFLOW");
return z;
}
/**
* @dev returns the difference of _x minus _y, reverts if the calculation underflows
*
* @param _x minuend
* @param _y subtrahend
*
* @return difference
*/
function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_x >= _y, "ERR_UNDERFLOW");
return _x - _y;
}
/**
* @dev returns the product of multiplying _x by _y, reverts if the calculation overflows
*
* @param _x factor 1
* @param _y factor 2
*
* @return product
*/
function mul(uint256 _x, uint256 _y) internal pure returns (uint256) {
// gas optimization
if (_x == 0)
return 0;
uint256 z = _x * _y;
require(z / _x == _y, "ERR_OVERFLOW");
return z;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*
* @param _x dividend
* @param _y divisor
*
* @return quotient
*/
function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
require(_y > 0, "ERR_DIVIDE_BY_ZERO");
uint256 c = _x / _y;
return c;
}
}
// File: solidity/contracts/utility/TokenHandler.sol
pragma solidity 0.6.12;
contract TokenHandler {
bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)"));
bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)"));
bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)"));
/**
* @dev executes the ERC20 token's `approve` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _spender approved address
* @param _value allowance amount
*/
function safeApprove(IERC20Token _token, address _spender, uint256 _value) internal {
(bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_APPROVE_FAILED');
}
/**
* @dev executes the ERC20 token's `transfer` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _to target address
* @param _value transfer amount
*/
function safeTransfer(IERC20Token _token, address _to, uint256 _value) internal {
(bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_TRANSFER_FAILED');
}
/**
* @dev executes the ERC20 token's `transferFrom` function and reverts upon failure
* the main purpose of this function is to prevent a non standard ERC20 token
* from failing silently
*
* @param _token ERC20 token address
* @param _from source address
* @param _to target address
* @param _value transfer amount
*/
function safeTransferFrom(IERC20Token _token, address _from, address _to, uint256 _value) internal {
(bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_TRANSFER_FROM_FAILED');
}
}
// File: solidity/contracts/utility/interfaces/ITokenHolder.sol
pragma solidity 0.6.12;
/*
Token Holder interface
*/
interface ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) external;
}
// File: solidity/contracts/utility/TokenHolder.sol
pragma solidity 0.6.12;
/**
* @dev We consider every contract to be a 'token holder' since it's currently not possible
* for a contract to deny receiving tokens.
*
* The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
* the owner to send tokens that were sent to the contract by mistake back to their sender.
*
* Note that we use the non standard ERC-20 interface which has no return value for transfer
* in order to support both non standard as well as standard token contracts.
* see https://github.com/ethereum/solidity/issues/4116
*/
contract TokenHolder is ITokenHolder, TokenHandler, Owned, Utils {
/**
* @dev withdraws tokens held by the contract and sends them to an account
* can only be called by the owner
*
* @param _token ERC20 token contract address
* @param _to account to receive the new amount
* @param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
virtual
override
ownerOnly
validAddress(address(_token))
validAddress(_to)
notThis(_to)
{
safeTransfer(_token, _to, _amount);
}
}
// File: solidity/contracts/token/interfaces/IEtherToken.sol
pragma solidity 0.6.12;
/*
Ether Token interface
*/
interface IEtherToken is IERC20Token {
function deposit() external payable;
function withdraw(uint256 _amount) external;
function depositTo(address _to) external payable;
function withdrawTo(address payable _to, uint256 _amount) external;
}
// File: solidity/contracts/bancorx/interfaces/IBancorX.sol
pragma solidity 0.6.12;
interface IBancorX {
function token() external view returns (IERC20Token);
function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) external;
function getXTransferAmount(uint256 _xTransferId, address _for) external view returns (uint256);
}
// File: solidity/contracts/converter/ConverterBase.sol
pragma solidity 0.6.12;
/**
* @dev ConverterBase
*
* The converter contains the main logic for conversions between different ERC20 tokens.
*
* It is also the upgradable part of the mechanism (note that upgrades are opt-in).
*
* The anchor must be set on construction and cannot be changed afterwards.
* Wrappers are provided for some of the anchor's functions, for easier access.
*
* Once the converter accepts ownership of the anchor, it becomes the anchor's sole controller
* and can execute any of its functions.
*
* To upgrade the converter, anchor ownership must be transferred to a new converter, along with
* any relevant data.
*
* Note that the converter can transfer anchor ownership to a new converter that
* doesn't allow upgrades anymore, for finalizing the relationship between the converter
* and the anchor.
*
* Converter types (defined as uint16 type) -
* 0 = liquid token converter
* 1 = liquidity pool v1 converter
* 2 = liquidity pool v2 converter
*
* Note that converters don't currently support tokens with transfer fees.
*/
abstract contract ConverterBase is IConverter, TokenHandler, TokenHolder, ContractRegistryClient, ReentrancyGuard {
using SafeMath for uint256;
uint32 internal constant PPM_RESOLUTION = 1000000;
IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
struct Reserve {
uint256 balance; // reserve balance
uint32 weight; // reserve weight, represented in ppm, 1-1000000
bool deprecated1; // deprecated
bool deprecated2; // deprecated
bool isSet; // true if the reserve is valid, false otherwise
}
/**
* @dev version number
*/
uint16 public constant version = 41;
IConverterAnchor public override anchor; // converter anchor contract
IWhitelist public override conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter
IERC20Token[] public reserveTokens; // ERC20 standard token addresses (prior version 17, use 'connectorTokens' instead)
mapping (IERC20Token => Reserve) public reserves; // reserve token addresses -> reserve data (prior version 17, use 'connectors' instead)
uint32 public reserveRatio = 0; // ratio between the reserves and the market cap, equal to the total reserve weights
uint32 public override maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract,
// represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%)
uint32 public override conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee
bool public constant conversionsEnabled = true; // deprecated, backward compatibility
/**
* @dev triggered when the converter is activated
*
* @param _type converter type
* @param _anchor converter anchor
* @param _activated true if the converter was activated, false if it was deactivated
*/
event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
/**
* @dev triggered when a conversion between two tokens occurs
*
* @param _fromToken source ERC20 token
* @param _toToken target ERC20 token
* @param _trader wallet that initiated the trade
* @param _amount amount converted, in the source token
* @param _return amount returned, minus conversion fee
* @param _conversionFee conversion fee
*/
event Conversion(
IERC20Token indexed _fromToken,
IERC20Token indexed _toToken,
address indexed _trader,
uint256 _amount,
uint256 _return,
int256 _conversionFee
);
/**
* @dev triggered when the rate between two tokens in the converter changes
* note that the event might be dispatched for rate updates between any two tokens in the converter
* note that prior to version 28, you should use the 'PriceDataUpdate' event instead
*
* @param _token1 address of the first token
* @param _token2 address of the second token
* @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator)
* @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator)
*/
event TokenRateUpdate(
IERC20Token indexed _token1,
IERC20Token indexed _token2,
uint256 _rateN,
uint256 _rateD
);
/**
* @dev triggered when the conversion fee is updated
*
* @param _prevFee previous fee percentage, represented in ppm
* @param _newFee new fee percentage, represented in ppm
*/
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
/**
* @dev used by sub-contracts to initialize a new converter
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
)
validAddress(address(_anchor))
ContractRegistryClient(_registry)
internal
validConversionFee(_maxConversionFee)
{
anchor = _anchor;
maxConversionFee = _maxConversionFee;
}
// ensures that the converter is active
modifier active() {
_active();
_;
}
// error message binary size optimization
function _active() internal view {
require(isActive(), "ERR_INACTIVE");
}
// ensures that the converter is not active
modifier inactive() {
_inactive();
_;
}
// error message binary size optimization
function _inactive() internal view {
require(!isActive(), "ERR_ACTIVE");
}
// validates a reserve token address - verifies that the address belongs to one of the reserve tokens
modifier validReserve(IERC20Token _address) {
_validReserve(_address);
_;
}
// error message binary size optimization
function _validReserve(IERC20Token _address) internal view {
require(reserves[_address].isSet, "ERR_INVALID_RESERVE");
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
_validConversionFee(_conversionFee);
_;
}
// error message binary size optimization
function _validConversionFee(uint32 _conversionFee) internal pure {
require(_conversionFee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE");
}
// validates reserve weight
modifier validReserveWeight(uint32 _weight) {
_validReserveWeight(_weight);
_;
}
// error message binary size optimization
function _validReserveWeight(uint32 _weight) internal pure {
require(_weight > 0 && _weight <= PPM_RESOLUTION, "ERR_INVALID_RESERVE_WEIGHT");
}
// overrides interface declaration
function converterType() public pure virtual override returns (uint16);
// overrides interface declaration
function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount)
public
view
virtual
override
returns (uint256, uint256);
/**
* @dev deposits ether
* can only be called if the converter has an ETH reserve
*/
receive() external override payable { //injected LOCKED ETHER
require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_INVALID_RESERVE"); // require(hasETHReserve(), "ERR_INVALID_RESERVE");
// a workaround for a problem when running solidity-coverage
// see https://github.com/sc-forks/solidity-coverage/issues/487
}
/**
* @dev withdraws ether
* can only be called by the owner if the converter is inactive or by upgrader contract
* can only be called after the upgrader contract has accepted the ownership of this contract
* can only be called if the converter has an ETH reserve
*
* @param _to address to send the ETH to
*/
function withdrawETH(address payable _to)
public
override
protected
ownerOnly
validReserve(ETH_RESERVE_ADDRESS)
{
address converterUpgrader = addressOf(CONVERTER_UPGRADER);
// verify that the converter is inactive or that the owner is the upgrader contract
require(!isActive() || owner == converterUpgrader, "ERR_ACCESS_DENIED");
_to.transfer(0);
// sync the ETH reserve balance
syncReserveBalance(ETH_RESERVE_ADDRESS);
}
/**
* @dev checks whether or not the converter version is 28 or higher
*
* @return true, since the converter version is 28 or higher
*/
function isV28OrHigher() public pure returns (bool) {
return true;
}
/**
* @dev allows the owner to update & enable the conversion whitelist contract address
* when set, only addresses that are whitelisted are actually allowed to use the converter
* note that the whitelist check is actually done by the BancorNetwork contract
*
* @param _whitelist address of a whitelist contract
*/
function setConversionWhitelist(IWhitelist _whitelist)
public
override
ownerOnly
notThis(address(_whitelist))
{
conversionWhitelist = _whitelist;
}
/**
* @dev returns true if the converter is active, false otherwise
*
* @return true if the converter is active, false otherwise
*/
function isActive() public view virtual override returns (bool) {
return anchor.owner() == address(this);
}
/**
* @dev transfers the anchor ownership
* the new owner needs to accept the transfer
* can only be called by the converter upgrder while the upgrader is the owner
* note that prior to version 28, you should use 'transferAnchorOwnership' instead
*
* @param _newOwner new token owner
*/
function transferAnchorOwnership(address _newOwner)
public
override
ownerOnly
only(CONVERTER_UPGRADER)
{
anchor.transferOwnership(_newOwner);
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* most converters are also activated as soon as they accept the anchor ownership
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public virtual override ownerOnly {
// verify the the converter has at least one reserve
require(reserveTokenCount() > 0, "ERR_INVALID_RESERVE_COUNT");
anchor.acceptOwnership();
syncReserveBalances();
}
/**
* @dev updates the current conversion fee
* can only be called by the contract owner
*
* @param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee) public override ownerOnly {
require(_conversionFee <= maxConversionFee, "ERR_INVALID_CONVERSION_FEE");
emit ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/**
* @dev withdraws tokens held by the converter and sends them to an account
* can only be called by the owner
* note that reserve tokens can only be withdrawn by the owner while the converter is inactive
* unless the owner is the converter upgrader contract
*
* @param _token ERC20 token contract address
* @param _to account to receive the new amount
* @param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
override(IConverter, TokenHolder)
protected
ownerOnly
{
address converterUpgrader = addressOf(CONVERTER_UPGRADER);
// if the token is not a reserve token, allow withdrawal
// otherwise verify that the converter is inactive or that the owner is the upgrader contract
require(!reserves[_token].isSet || !isActive() || owner == converterUpgrader, "ERR_ACCESS_DENIED");
super.withdrawTokens(_token, _to, _amount);
// if the token is a reserve token, sync the reserve balance
if (reserves[_token].isSet)
syncReserveBalance(_token);
}
/**
* @dev upgrades the converter to the latest version
* can only be called by the owner
* note that the owner needs to call acceptOwnership on the new converter after the upgrade
*/
function upgrade() public ownerOnly {
IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER));
// trigger de-activation event
emit Activation(converterType(), anchor, false);
transferOwnership(address(converterUpgrader));
converterUpgrader.upgrade(version);
acceptOwnership();
}
/**
* @dev returns the number of reserve tokens defined
* note that prior to version 17, you should use 'connectorTokenCount' instead
*
* @return number of reserve tokens
*/
function reserveTokenCount() public view returns (uint16) {
return uint16(reserveTokens.length);
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IERC20Token _token, uint32 _weight)
public
virtual
override
ownerOnly
inactive
validAddress(address(_token))
notThis(address(_token))
validReserveWeight(_weight)
{
// validate input
require(address(_token) != address(anchor) && !reserves[_token].isSet, "ERR_INVALID_RESERVE");
require(_weight <= PPM_RESOLUTION - reserveRatio, "ERR_INVALID_RESERVE_WEIGHT");
require(reserveTokenCount() < uint16(-1), "ERR_INVALID_RESERVE_COUNT");
Reserve storage newReserve = reserves[_token];
newReserve.balance = 0;
newReserve.weight = _weight;
newReserve.isSet = true;
reserveTokens.push(_token);
reserveRatio += _weight;
}
/**
* @dev returns the reserve's weight
* added in version 28
*
* @param _reserveToken reserve token contract address
*
* @return reserve weight
*/
function reserveWeight(IERC20Token _reserveToken)
public
view
validReserve(_reserveToken)
returns (uint32)
{
return reserves[_reserveToken].weight;
}
/**
* @dev returns the reserve's balance
* note that prior to version 17, you should use 'getConnectorBalance' instead
*
* @param _reserveToken reserve token contract address
*
* @return reserve balance
*/
function reserveBalance(IERC20Token _reserveToken)
public
override
view
validReserve(_reserveToken)
returns (uint256)
{
return reserves[_reserveToken].balance;
}
/**
* @dev checks whether or not the converter has an ETH reserve
*
* @return true if the converter has an ETH reserve, false otherwise
*/
function hasETHReserve() public view returns (bool) {
return reserves[ETH_RESERVE_ADDRESS].isSet;
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function convert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) //injected LOCKED ETHER
public
override
payable
protected
only(BANCOR_NETWORK)
returns (uint256)
{
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
// if a whitelist is set, verify that both and trader and the beneficiary are whitelisted
require(address(conversionWhitelist) == address(0) ||
(conversionWhitelist.isWhitelisted(_trader) && conversionWhitelist.isWhitelisted(_beneficiary)),
"ERR_NOT_WHITELISTED");
return doConvert(_sourceToken, _targetToken, _amount, _trader, _beneficiary);
}
/**
* @dev converts a specific amount of source tokens to target tokens
* called by ConverterBase and allows the inherited contracts to implement custom conversion logic
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(
IERC20Token _sourceToken,
IERC20Token _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary)
internal
virtual
returns (uint256);
/**
* @dev returns the conversion fee for a given target amount
*
* @param _targetAmount target amount
*
* @return conversion fee
*/
function calculateFee(uint256 _targetAmount) internal view returns (uint256) {
return _targetAmount.mul(conversionFee).div(PPM_RESOLUTION);
}
/**
* @dev syncs the stored reserve balance for a given reserve with the real reserve balance
*
* @param _reserveToken address of the reserve token
*/
function syncReserveBalance(IERC20Token _reserveToken) internal validReserve(_reserveToken) {
if (_reserveToken == ETH_RESERVE_ADDRESS)
reserves[_reserveToken].balance = address(this).balance;
else
reserves[_reserveToken].balance = _reserveToken.balanceOf(address(this));
}
/**
* @dev syncs all stored reserve balances
*/
function syncReserveBalances() internal {
uint256 reserveCount = reserveTokens.length;
for (uint256 i = 0; i < reserveCount; i++)
syncReserveBalance(reserveTokens[i]);
}
/**
* @dev helper, dispatches the Conversion event
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _trader address of the caller who executed the conversion
* @param _amount amount purchased/sold (in the source token)
* @param _returnAmount amount returned (in the target token)
*/
function dispatchConversionEvent(
IERC20Token _sourceToken,
IERC20Token _targetToken,
address _trader,
uint256 _amount,
uint256 _returnAmount,
uint256 _feeAmount)
internal
{
// fee amount is converted to 255 bits -
// negative amount means the fee is taken from the source token, positive amount means its taken from the target token
// currently the fee is always taken from the target token
// since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow
assert(_feeAmount < 2 ** 255);
emit Conversion(_sourceToken, _targetToken, _trader, _amount, _returnAmount, int256(_feeAmount));
}
/**
* @dev deprecated since version 28, backward compatibility - use only for earlier versions
*/
function token() public view override returns (IConverterAnchor) {
return anchor;
}
/**
* @dev deprecated, backward compatibility
*/
function transferTokenOwnership(address _newOwner) public override ownerOnly {
transferAnchorOwnership(_newOwner);
}
/**
* @dev deprecated, backward compatibility
*/
function acceptTokenOwnership() public override ownerOnly {
acceptAnchorOwnership();
}
/**
* @dev deprecated, backward compatibility
*/
function connectors(IERC20Token _address) public view override returns (uint256, uint32, bool, bool, bool) {
Reserve memory reserve = reserves[_address];
return(reserve.balance, reserve.weight, false, false, reserve.isSet);
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokens(uint256 _index) public view override returns (IERC20Token) {
return ConverterBase.reserveTokens[_index];
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokenCount() public view override returns (uint16) {
return reserveTokenCount();
}
/**
* @dev deprecated, backward compatibility
*/
function getConnectorBalance(IERC20Token _connectorToken) public view override returns (uint256) {
return reserveBalance(_connectorToken);
}
/**
* @dev deprecated, backward compatibility
*/
function getReturn(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public view returns (uint256, uint256) {
return targetAmountAndFee(_sourceToken, _targetToken, _amount);
}
}
// File: solidity/contracts/converter/LiquidityPoolConverter.sol
pragma solidity 0.6.12;
/**
* @dev Liquidity Pool Converter
*
* The liquidity pool converter is the base contract for specific types of converters that
* manage liquidity pools.
*
* Liquidity pools have 2 reserves or more and they allow converting between them.
*
* Note that TokenRateUpdate events are dispatched for pool tokens as well.
* The pool token is the first token in the event in that case.
*/
abstract contract LiquidityPoolConverter is ConverterBase {
/**
* @dev triggered after liquidity is added
*
* @param _provider liquidity provider
* @param _reserveToken reserve token address
* @param _amount reserve token amount
* @param _newBalance reserve token new balance
* @param _newSupply pool token new supply
*/
event LiquidityAdded(
address indexed _provider,
IERC20Token indexed _reserveToken,
uint256 _amount,
uint256 _newBalance,
uint256 _newSupply
);
/**
* @dev triggered after liquidity is removed
*
* @param _provider liquidity provider
* @param _reserveToken reserve token address
* @param _amount reserve token amount
* @param _newBalance reserve token new balance
* @param _newSupply pool token new supply
*/
event LiquidityRemoved(
address indexed _provider,
IERC20Token indexed _reserveToken,
uint256 _amount,
uint256 _newBalance,
uint256 _newSupply
);
/**
* @dev initializes a new LiquidityPoolConverter instance
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
)
ConverterBase(_anchor, _registry, _maxConversionFee)
internal
{
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* also activates the converter
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public virtual override {
// verify that the converter has at least 2 reserves
require(reserveTokenCount() > 1, "ERR_INVALID_RESERVE_COUNT");
super.acceptAnchorOwnership();
}
}
// File: solidity/contracts/token/interfaces/IDSToken.sol
pragma solidity 0.6.12;
/*
DSToken interface
*/
interface IDSToken is IConverterAnchor, IERC20Token {
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
}
// File: solidity/contracts/utility/Math.sol
pragma solidity 0.6.12;
/**
* @dev Library for complex math operations
*/
library Math {
using SafeMath for uint256;
/**
* @dev returns the largest integer smaller than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the largest integer smaller than or equal to the square root of the positive integer
*/
function floorSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = _num / 2 + 1;
uint256 y = (x + _num / x) / 2;
while (x > y) {
x = y;
y = (x + _num / x) / 2;
}
return x;
}
/**
* @dev computes a reduced-scalar ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _max maximum desired scalar
*
* @return ratio's numerator and denominator
*/
function reducedRatio(uint256 _n, uint256 _d, uint256 _max) internal pure returns (uint256, uint256) {
if (_n > _max || _d > _max)
return normalizedRatio(_n, _d, _max);
return (_n, _d);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
*/
function normalizedRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) {
if (_a == _b)
return (_scale / 2, _scale / 2);
if (_a < _b)
return accurateRatio(_a, _b, _scale);
(uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
return (x, y);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a < b".
*/
function accurateRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) {
uint256 maxVal = uint256(-1) / _scale;
if (_a > maxVal) {
uint256 c = _a / (maxVal + 1) + 1;
_a /= c;
_b /= c;
}
uint256 x = roundDiv(_a * _scale, _a.add(_b));
uint256 y = _scale - x;
return (x, y);
}
/**
* @dev computes the nearest integer to a given quotient without overflowing or underflowing.
*/
function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
return _n / _d + _n % _d / (_d - _d / 2);
}
/**
* @dev returns the average number of decimal digits in a given list of positive integers
*
* @param _values list of positive integers
*
* @return the average number of decimal digits in the given list of positive integers
*/
function geometricMean(uint256[] memory _values) internal pure returns (uint256) {
uint256 numOfDigits = 0;
uint256 length = _values.length;
for (uint256 i = 0; i < length; i++)
numOfDigits += decimalLength(_values[i]);
return uint256(10) ** (roundDivUnsafe(numOfDigits, length) - 1);
}
/**
* @dev returns the number of decimal digits in a given positive integer
*
* @param _x positive integer
*
* @return the number of decimal digits in the given positive integer
*/
function decimalLength(uint256 _x) internal pure returns (uint256) {
uint256 y = 0;
for (uint256 x = _x; x > 0; x /= 10)
y++;
return y;
}
/**
* @dev returns the nearest integer to a given quotient
* the computation is overflow-safe assuming that the input is sufficiently small
*
* @param _n quotient numerator
* @param _d quotient denominator
*
* @return the nearest integer to the given quotient
*/
function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) {
return (_n + _d / 2) / _d;
}
}
// File: solidity/contracts/utility/Types.sol
pragma solidity 0.6.12;
/**
* @dev Provides types that can be used by various contracts
*/
struct Fraction {
uint256 n; // numerator
uint256 d; // denominator
}
// File: solidity/contracts/converter/types/liquidity-pool-v1/LiquidityPoolV1Converter.sol
pragma solidity 0.6.12;
/**
* @dev Liquidity Pool v1 Converter
*
* The liquidity pool v1 converter is a specialized version of a converter that manages
* a classic bancor liquidity pool.
*
* Even though pools can have many reserves, the standard pool configuration
* is 2 reserves with 50%/50% weights.
*/
contract LiquidityPoolV1Converter is LiquidityPoolConverter {
using Math for *;
IEtherToken internal etherToken = IEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
uint256 internal constant MAX_RATE_FACTOR_LOWER_BOUND = 1e30;
// the period of time taken into account when calculating the recent averate rate
uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes;
// true if the pool is a 2 reserves / 50%/50% weights pool, false otherwise
bool public isStandardPool = false;
// only used in standard pools
Fraction public prevAverageRate; // average rate after the previous conversion (1 reserve token 0 in reserve token 1 units)
uint256 public prevAverageRateUpdateTime; // last time when the previous rate was updated (in seconds)
/**
* @dev triggered after a conversion with new price data
* deprecated, use `TokenRateUpdate` from version 28 and up
*
* @param _connectorToken reserve token
* @param _tokenSupply pool token supply
* @param _connectorBalance reserve balance
* @param _connectorWeight reserve weight
*/
event PriceDataUpdate(
IERC20Token indexed _connectorToken,
uint256 _tokenSupply,
uint256 _connectorBalance,
uint32 _connectorWeight
);
/**
* @dev initializes a new LiquidityPoolV1Converter instance
*
* @param _token pool token governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IDSToken _token,
IContractRegistry _registry,
uint32 _maxConversionFee
)
LiquidityPoolConverter(_token, _registry, _maxConversionFee)
public
{
}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public pure override returns (uint16) {
return 1;
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* also activates the converter
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public override ownerOnly {
super.acceptAnchorOwnership();
emit Activation(converterType(), anchor, true);
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IERC20Token _token, uint32 _weight) public override ownerOnly {
super.addReserve(_token, _weight);
isStandardPool =
reserveTokens.length == 2 &&
reserves[reserveTokens[0]].weight == PPM_RESOLUTION / 2 &&
reserves[reserveTokens[1]].weight == PPM_RESOLUTION / 2;
}
/**
* @dev returns the expected target amount of converting one reserve to another along with the fee
*
* @param _sourceToken contract address of the source reserve token
* @param _targetToken contract address of the target reserve token
* @param _amount amount of tokens received from the user
*
* @return expected target amount
* @return expected fee
*/
function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount)
public
view
override
active
validReserve(_sourceToken)
validReserve(_targetToken)
returns (uint256, uint256)
{
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
uint256 amount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount(
reserveBalance(_sourceToken),
reserves[_sourceToken].weight,
reserveBalance(_targetToken),
reserves[_targetToken].weight,
_amount
);
// return the amount minus the conversion fee and the conversion fee
uint256 fee = calculateFee(amount);
return (amount - fee, fee);
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary)
internal
override
returns (uint256)
{
// update the recent average rate
if (isStandardPool && prevAverageRateUpdateTime < time()) {
prevAverageRate = recentAverageRate();
prevAverageRateUpdateTime = time();
}
// get expected target amount and fee
(uint256 amount, uint256 fee) = targetAmountAndFee(_sourceToken, _targetToken, _amount);
// ensure that the trade gives something in return
require(amount != 0, "ERR_ZERO_TARGET_AMOUNT");
// ensure that the trade won't deplete the reserve balance
assert(amount < reserveBalance(_targetToken));
// ensure that the input amount was already deposited
if (_sourceToken == ETH_RESERVE_ADDRESS)
require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
else
require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserveBalance(_sourceToken)) >= _amount, "ERR_INVALID_AMOUNT");
// sync the reserve balances
syncReserveBalance(_sourceToken);
reserves[_targetToken].balance = reserves[_targetToken].balance.sub(amount);
// transfer funds to the beneficiary in the to reserve token
if (_targetToken == ETH_RESERVE_ADDRESS)
_beneficiary.transfer(0);
else
safeTransfer(_targetToken, _beneficiary, amount);
// dispatch the conversion event
dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
// dispatch rate updates
dispatchTokenRateUpdateEvents(_sourceToken, _targetToken);
return amount;
}
/**
* @dev returns the recent average rate of 1 `_token` in the other reserve token units
* note that the rate can only be queried for reserves in a standard pool
*
* @param _token token to get the rate for
* @return recent average rate between the reserves (numerator)
* @return recent average rate between the reserves (denominator)
*/
function recentAverageRate(IERC20Token _token) external view returns (uint256, uint256) {
// verify that the pool is standard
require(isStandardPool, "ERR_NON_STANDARD_POOL");
// get the recent average rate of reserve 0
Fraction memory rate = recentAverageRate();
if (_token == reserveTokens[0]) {
return (rate.n, rate.d);
}
return (rate.d, rate.n);
}
/**
* @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units
*
* @return recent average rate between the reserves
*/
function recentAverageRate() internal view returns (Fraction memory) {
// get the elapsed time since the previous average rate was calculated
uint256 timeElapsed = time() - prevAverageRateUpdateTime;
// if the previous average rate was calculated in the current block, return it
if (timeElapsed == 0) {
return prevAverageRate;
}
// get the current rate between the reserves
uint256 currentRateN = reserves[reserveTokens[1]].balance;
uint256 currentRateD = reserves[reserveTokens[0]].balance;
// if the previous average rate was calculated a while ago, the average rate is equal to the current rate
if (timeElapsed >= AVERAGE_RATE_PERIOD) {
return Fraction({ n: currentRateN, d: currentRateD });
}
// given N as the sampling window, the new rate is calculated according to the following formula:
// newRate = prevAverageRate + timeElapsed * [currentRate - prevAverageRate] / N
// calculate the numerator and the denumerator of the new rate
Fraction memory prevAverage = prevAverageRate;
uint256 x = prevAverage.d.mul(currentRateN);
uint256 y = prevAverage.n.mul(currentRateD);
// since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath:
uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed));
uint256 newRateD = prevAverage.d.mul(currentRateD).mul(AVERAGE_RATE_PERIOD);
(newRateN, newRateD) = Math.reducedRatio(newRateN, newRateD, MAX_RATE_FACTOR_LOWER_BOUND);
return Fraction({ n: newRateN, d: newRateD });
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
* note that prior to version 28, you should use 'fund' instead
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _minReturn token minimum return-amount
*
* @return amount of pool tokens issued
*/
function addLiquidity(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn) //injected LOCKED ETHER
public
payable
protected
active
returns (uint256)
{
// verify the user input
verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn);
// if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH
for (uint256 i = 0; i < _reserveTokens.length; i++)
if (_reserveTokens[i] == ETH_RESERVE_ADDRESS)
require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH");
// if the input value of ETH is larger than zero, then verify that one of the reserves is ETH
if (msg.value > 0) {
require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_NO_ETH_RESERVE");
}
// get the total supply
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
// transfer from the user an equally-worth amount of each one of the reserve tokens
uint256 amount = addLiquidityToPool(_reserveTokens, _reserveAmounts, totalSupply);
// verify that the equivalent amount of tokens is equal to or larger than the user's expectation
require(amount >= _minReturn, "ERR_RETURN_TOO_LOW");
// issue the tokens to the user
IDSToken(address(anchor)).issue(msg.sender, amount);
// return the amount of pool tokens issued
return amount;
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
* note that prior to version 28, you should use 'liquidate' instead
*
* @param _amount token amount
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum return-amount of each reserve token
*
* @return the amount of each reserve token granted for the given amount of pool tokens
*/
function removeLiquidity(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts)
public
protected
active
returns (uint256[] memory)
{
// verify the user input
verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);
// get the total supply BEFORE destroying the user tokens
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
// destroy the user tokens
IDSToken(address(anchor)).destroy(msg.sender, _amount);
// transfer to the user an equivalent amount of each one of the reserve tokens
return removeLiquidityFromPool(_reserveTokens, _reserveMinReturnAmounts, totalSupply, _amount);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
* for example, if the caller increases the supply by 10%,
* then it will cost an amount equal to 10% of each reserve token balance
* note that starting from version 28, you should use 'addLiquidity' instead
*
* @param _amount amount to increase the supply by (in the pool token)
*
* @return amount of pool tokens issued
*/
function fund(uint256 _amount) //injected LOCKED ETHER
public
payable
protected
returns (uint256)
{
syncReserveBalances();
reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value);
uint256 supply = IDSToken(address(anchor)).totalSupply();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
// iterate through the reserve tokens and transfer a percentage equal to the weight between
// _amount and the total supply in each reserve from the caller to the converter
uint256 reserveCount = reserveTokens.length;
for (uint256 i = 0; i < reserveCount; i++) {
IERC20Token reserveToken = reserveTokens[i];
uint256 rsvBalance = reserves[reserveToken].balance;
uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount);
// transfer funds from the caller in the reserve token
if (reserveToken == ETH_RESERVE_ADDRESS) {
if (msg.value > reserveAmount) {
msg.sender.transfer(0);
}
else if (msg.value < reserveAmount) {
require(msg.value == 0, "ERR_INVALID_ETH_VALUE");
safeTransferFrom(etherToken, msg.sender, address(this), reserveAmount);
etherToken.withdraw(reserveAmount);
}
}
else {
safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount);
}
// sync the reserve balance
uint256 newReserveBalance = rsvBalance.add(reserveAmount);
reserves[reserveToken].balance = newReserveBalance;
uint256 newPoolTokenSupply = supply.add(_amount);
// dispatch liquidity update for the pool token/reserve
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight);
}
// issue new funds to the caller in the pool token
IDSToken(address(anchor)).issue(msg.sender, _amount);
// return the amount of pool tokens issued
return _amount;
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
* for example, if the holder sells 10% of the supply,
* then they will receive 10% of each reserve token balance in return
* note that starting from version 28, you should use 'removeLiquidity' instead
*
* @param _amount amount to liquidate (in the pool token)
*
* @return the amount of each reserve token granted for the given amount of pool tokens
*/
function liquidate(uint256 _amount)
public
protected
returns (uint256[] memory)
{
require(_amount > 0, "ERR_ZERO_AMOUNT");
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
IDSToken(address(anchor)).destroy(msg.sender, _amount);
uint256[] memory reserveMinReturnAmounts = new uint256[](reserveTokens.length);
for (uint256 i = 0; i < reserveMinReturnAmounts.length; i++)
reserveMinReturnAmounts[i] = 1;
return removeLiquidityFromPool(reserveTokens, reserveMinReturnAmounts, totalSupply, _amount);
}
/**
* @dev given the amount of one of the reserve tokens to add liquidity of,
* returns the required amount of each one of the other reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param _reserveTokens address of each reserve token
* @param _reserveTokenIndex index of the relevant reserve token
* @param _reserveAmount amount of the relevant reserve token
*
* @return the required amount of each one of the reserve tokens
*/
function addLiquidityCost(IERC20Token[] memory _reserveTokens, uint256 _reserveTokenIndex, uint256 _reserveAmount)
public
view
returns (uint256[] memory)
{
uint256[] memory reserveAmounts = new uint256[](_reserveTokens.length);
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
uint256 amount = formula.fundSupplyAmount(totalSupply, reserves[_reserveTokens[_reserveTokenIndex]].balance, reserveRatio, _reserveAmount);
for (uint256 i = 0; i < reserveAmounts.length; i++)
reserveAmounts[i] = formula.fundCost(totalSupply, reserves[_reserveTokens[i]].balance, reserveRatio, amount);
return reserveAmounts;
}
/**
* @dev given the amount of one of the reserve tokens to add liquidity of,
* returns the amount of pool tokens entitled for it
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param _reserveToken address of the reserve token
* @param _reserveAmount amount of the reserve token
*
* @return the amount of pool tokens entitled
*/
function addLiquidityReturn(IERC20Token _reserveToken, uint256 _reserveAmount)
public
view
returns (uint256)
{
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
return formula.fundSupplyAmount(totalSupply, reserves[_reserveToken].balance, reserveRatio, _reserveAmount);
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param _amount amount of pool tokens
* @param _reserveTokens address of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReturn(uint256 _amount, IERC20Token[] memory _reserveTokens)
public
view
returns (uint256[] memory)
{
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
return removeLiquidityReserveAmounts(_amount, _reserveTokens, totalSupply, formula);
}
/**
* @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
* we take this input in order to allow specifying the corresponding reserve amounts in any order
*
* @param _reserveTokens array of reserve tokens
* @param _reserveAmounts array of reserve amounts
* @param _amount token amount
*/
function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount)
private
view
{
uint256 i;
uint256 j;
uint256 length = reserveTokens.length;
require(length == _reserveTokens.length, "ERR_INVALID_RESERVE");
require(length == _reserveAmounts.length, "ERR_INVALID_AMOUNT");
for (i = 0; i < length; i++) {
// verify that every input reserve token is included in the reserve tokens
require(reserves[_reserveTokens[i]].isSet, "ERR_INVALID_RESERVE");
for (j = 0; j < length; j++) {
if (reserveTokens[i] == _reserveTokens[j])
break;
}
// verify that every reserve token is included in the input reserve tokens
require(j < length, "ERR_INVALID_RESERVE");
// verify that every input reserve token amount is larger than zero
require(_reserveAmounts[i] > 0, "ERR_INVALID_AMOUNT");
}
// verify that the input token amount is larger than zero
require(_amount > 0, "ERR_ZERO_AMOUNT");
}
/**
* @dev adds liquidity (reserve) to the pool
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _totalSupply token total supply
*
* @return amount of pool tokens issued
*/
function addLiquidityToPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply)
private
returns (uint256)
{
if (_totalSupply == 0)
return addLiquidityToEmptyPool(_reserveTokens, _reserveAmounts);
return addLiquidityToNonEmptyPool(_reserveTokens, _reserveAmounts, _totalSupply);
}
/**
* @dev adds liquidity (reserve) to the pool when it's empty
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
*
* @return amount of pool tokens issued
*/
function addLiquidityToEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts)
private
returns (uint256)
{
// calculate the geometric-mean of the reserve amounts approved by the user
uint256 amount = Math.geometricMean(_reserveAmounts);
// transfer each one of the reserve amounts from the user to the pool
for (uint256 i = 0; i < _reserveTokens.length; i++) {
IERC20Token reserveToken = _reserveTokens[i];
uint256 reserveAmount = _reserveAmounts[i];
if (reserveToken != ETH_RESERVE_ADDRESS) // ETH has already been transferred as part of the transaction
safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount);
reserves[reserveToken].balance = reserveAmount;
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, reserveAmount, amount);
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateUpdateEvent(amount, reserveToken, reserveAmount, reserves[reserveToken].weight);
}
// return the amount of pool tokens issued
return amount;
}
/**
* @dev adds liquidity (reserve) to the pool when it's not empty
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _totalSupply token total supply
*
* @return amount of pool tokens issued
*/
function addLiquidityToNonEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply)
private
returns (uint256)
{
syncReserveBalances();
reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value);
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
uint256 amount = getMinShare(formula, _totalSupply, _reserveTokens, _reserveAmounts);
uint256 newPoolTokenSupply = _totalSupply.add(amount);
for (uint256 i = 0; i < _reserveTokens.length; i++) {
IERC20Token reserveToken = _reserveTokens[i];
uint256 rsvBalance = reserves[reserveToken].balance;
uint256 reserveAmount = formula.fundCost(_totalSupply, rsvBalance, reserveRatio, amount);
require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT");
assert(reserveAmount <= _reserveAmounts[i]);
// transfer each one of the reserve amounts from the user to the pool
if (reserveToken != ETH_RESERVE_ADDRESS) // ETH has already been transferred as part of the transaction
safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount);
else if (_reserveAmounts[i] > reserveAmount) // transfer the extra amount of ETH back to the user
msg.sender.transfer(0);
uint256 newReserveBalance = rsvBalance.add(reserveAmount);
reserves[reserveToken].balance = newReserveBalance;
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight);
}
// return the amount of pool tokens issued
return amount;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param _amount amount of pool tokens
* @param _reserveTokens address of each reserve token
* @param _totalSupply token total supply
* @param _formula formula contract
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReserveAmounts(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256 _totalSupply, IBancorFormula _formula)
private
view
returns (uint256[] memory)
{
uint256[] memory reserveAmounts = new uint256[](_reserveTokens.length);
for (uint256 i = 0; i < reserveAmounts.length; i++)
reserveAmounts[i] = _formula.liquidateReserveAmount(_totalSupply, reserves[_reserveTokens[i]].balance, reserveRatio, _amount);
return reserveAmounts;
}
/**
* @dev removes liquidity (reserve) from the pool
*
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum return-amount of each reserve token
* @param _totalSupply token total supply
* @param _amount token amount
*
* @return the amount of each reserve token granted for the given amount of pool tokens
*/
function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount)
private
returns (uint256[] memory)
{
syncReserveBalances();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
uint256 newPoolTokenSupply = _totalSupply.sub(_amount);
uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, _reserveTokens, _totalSupply, formula);
for (uint256 i = 0; i < _reserveTokens.length; i++) {
IERC20Token reserveToken = _reserveTokens[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
uint256 newReserveBalance = reserves[reserveToken].balance.sub(reserveAmount);
reserves[reserveToken].balance = newReserveBalance;
// transfer each one of the reserve amounts from the pool to the user
if (reserveToken == ETH_RESERVE_ADDRESS)
msg.sender.transfer(0);
else
safeTransfer(reserveToken, msg.sender, reserveAmount);
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight);
}
// return the amount of each reserve token granted for the given amount of pool tokens
return reserveAmounts;
}
function getMinShare(IBancorFormula formula, uint256 _totalSupply, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts) private view returns (uint256) {
uint256 minIndex = 0;
for (uint256 i = 1; i < _reserveTokens.length; i++) {
if (_reserveAmounts[i].mul(reserves[_reserveTokens[minIndex]].balance) < _reserveAmounts[minIndex].mul(reserves[_reserveTokens[i]].balance))
minIndex = i;
}
return formula.fundSupplyAmount(_totalSupply, reserves[_reserveTokens[minIndex]].balance, reserveRatio, _reserveAmounts[minIndex]);
}
/**
* @dev dispatches token rate update events for the reserve tokens and the pool token
*
* @param _sourceToken address of the source reserve token
* @param _targetToken address of the target reserve token
*/
function dispatchTokenRateUpdateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private {
uint256 poolTokenSupply = IDSToken(address(anchor)).totalSupply();
uint256 sourceReserveBalance = reserveBalance(_sourceToken);
uint256 targetReserveBalance = reserveBalance(_targetToken);
uint32 sourceReserveWeight = reserves[_sourceToken].weight;
uint32 targetReserveWeight = reserves[_targetToken].weight;
// dispatch token rate update event for the reserve tokens
uint256 rateN = targetReserveBalance.mul(sourceReserveWeight);
uint256 rateD = sourceReserveBalance.mul(targetReserveWeight);
emit TokenRateUpdate(_sourceToken, _targetToken, rateN, rateD);
// dispatch token rate update events for the pool token
dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _sourceToken, sourceReserveBalance, sourceReserveWeight);
dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _targetToken, targetReserveBalance, targetReserveWeight);
// dispatch price data update events (deprecated events)
emit PriceDataUpdate(_sourceToken, poolTokenSupply, sourceReserveBalance, sourceReserveWeight);
emit PriceDataUpdate(_targetToken, poolTokenSupply, targetReserveBalance, targetReserveWeight);
}
/**
* @dev dispatches token rate update event for the pool token
*
* @param _poolTokenSupply total pool token supply
* @param _reserveToken address of the reserve token
* @param _reserveBalance reserve balance
* @param _reserveWeight reserve weight
*/
function dispatchPoolTokenRateUpdateEvent(uint256 _poolTokenSupply, IERC20Token _reserveToken, uint256 _reserveBalance, uint32 _reserveWeight) private {
emit TokenRateUpdate(IDSToken(address(anchor)), _reserveToken, _reserveBalance.mul(PPM_RESOLUTION), _poolTokenSupply.mul(_reserveWeight));
}
/**
* @dev returns the current time
* utility to allow overrides for tests
*/
function time() internal view virtual returns (uint256) {
return now;
}
}
// File: solidity/contracts/converter/interfaces/ITypedConverterFactory.sol
pragma solidity 0.6.12;
/*
Typed Converter Factory interface
*/
interface ITypedConverterFactory {
function converterType() external pure returns (uint16);
function createConverter(IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee) external returns (IConverter);
}
// File: solidity/contracts/converter/types/liquidity-pool-v1/LiquidityPoolV1ConverterFactory.sol
pragma solidity 0.6.12;
/*
LiquidityPoolV1Converter Factory
*/
contract LiquidityPoolV1ConverterFactory is ITypedConverterFactory {
/**
* @dev returns the converter type the factory is associated with
*
* @return converter type
*/
function converterType() external pure override returns (uint16) {
return 1;
}
/**
* @dev creates a new converter with the given arguments and transfers
* the ownership to the caller
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*
* @return a new converter
*/
function createConverter(IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee)
external
virtual
override
returns (IConverter)
{
IConverter converter = new LiquidityPoolV1Converter(IDSToken(address(_anchor)), _registry, _maxConversionFee);
converter.transferOwnership(msg.sender);
return converter;
}
} | * @dev deprecated since version 28, backward compatibility - use only for earlier versions/ | function token() public view override returns (IConverterAnchor) {
return anchor;
}
| 12,987,270 | [
1,
14089,
3241,
1177,
9131,
16,
12555,
8926,
300,
999,
1338,
364,
13805,
5244,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1147,
1435,
1071,
1476,
3849,
1135,
261,
45,
5072,
11605,
13,
288,
203,
3639,
327,
6984,
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,
-100,
-100
] |
./partial_match/1/0x6B0B234fB2f380309D47A7E9391E29E9a179395a/sources/src/v0.8/vendor/openzeppelin-solidity/v4.8.0/contracts/utils/math/Math.sol | * @dev Return the log in base 10, following the selected rounding direction, of a positive value. Returns 0 if given 0./ | function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
| 3,963,352 | [
1,
990,
326,
613,
316,
1026,
1728,
16,
3751,
326,
3170,
13885,
4068,
16,
434,
279,
6895,
460,
18,
2860,
374,
309,
864,
374,
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
] | [
1,
1,
1,
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
] | [
1,
225,
445,
613,
2163,
12,
11890,
5034,
460,
16,
11370,
310,
13885,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
22893,
288,
203,
1377,
2254,
5034,
563,
273,
613,
2163,
12,
1132,
1769,
203,
1377,
327,
563,
397,
261,
17376,
422,
11370,
310,
18,
1211,
597,
1728,
2826,
563,
411,
460,
692,
404,
294,
374,
1769,
203,
565,
289,
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
] |
// Consider this smart contract.
// Add a function called start() that adds the address of the account that calls it to the dynamic array called players.
// Deploy and test the contract on Rinkeby Testnet.
//SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.9.0;
contract Game{
address[] public players;
// Add a function called start() that adds the address of the account that calls it to the dynamic array called players.
function start() public{
// super similar to a regular pushing on JS
// note to add the sender to the players array.
players.push(msg.sender);
}
} | Add a function called start() that adds the address of the account that calls it to the dynamic array called players. | contract Game{
address[] public players;
function start() public{
players.push(msg.sender);
}
} | 12,630,870 | [
1,
986,
279,
445,
2566,
787,
1435,
716,
4831,
326,
1758,
434,
326,
2236,
716,
4097,
518,
358,
326,
5976,
526,
2566,
18115,
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
] | [
1,
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,
16351,
14121,
95,
203,
565,
1758,
8526,
1071,
18115,
31,
203,
203,
203,
203,
225,
445,
787,
1435,
1071,
95,
203,
565,
18115,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
225,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0x8e3d2ea1ad8774159DE8e3E871E434d58329F6B2/sources/apps/avai/src/contracts/interfaces/IBaseVault.sol | Events for general vault operations Buying out a vault event Events for collateral operations Events for token operations | interface IBaseVault {
event CreateVault(uint256 vaultID, address creator);
event DestroyVault(uint256 vaultID);
event TransferVault(uint256 vaultID, address from, address to);
event LiquidateVault(
uint256 vaultID,
address owner,
address buyer,
uint256 amountPaid,
uint256 tokenExtract
);
event DepositCollateral(uint256 vaultID, uint256 amount);
event WithdrawCollateral(uint256 vaultID, uint256 amount);
event BorrowToken(uint256 vaultID, uint256 amount);
event PayBackToken(uint256 vaultID, uint256 amount, uint256 closingFee);
function createVault() external;
function destroyVault(uint256 vaultID) external;
function transferVault(uint256 vaultID, address to) external;
pragma solidity ^0.8.0;
}
| 7,179,111 | [
1,
3783,
364,
7470,
9229,
5295,
605,
9835,
310,
596,
279,
9229,
871,
9043,
364,
4508,
2045,
287,
5295,
9043,
364,
1147,
5295,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
2171,
12003,
288,
203,
225,
871,
1788,
12003,
12,
11890,
5034,
9229,
734,
16,
1758,
11784,
1769,
203,
225,
871,
15701,
12003,
12,
11890,
5034,
9229,
734,
1769,
203,
225,
871,
12279,
12003,
12,
11890,
5034,
9229,
734,
16,
1758,
628,
16,
1758,
358,
1769,
203,
203,
225,
871,
511,
18988,
350,
340,
12003,
12,
203,
565,
2254,
5034,
9229,
734,
16,
203,
565,
1758,
3410,
16,
203,
565,
1758,
27037,
16,
203,
565,
2254,
5034,
3844,
16507,
350,
16,
203,
565,
2254,
5034,
1147,
4976,
203,
225,
11272,
203,
203,
225,
871,
4019,
538,
305,
13535,
2045,
287,
12,
11890,
5034,
9229,
734,
16,
2254,
5034,
3844,
1769,
203,
225,
871,
3423,
9446,
13535,
2045,
287,
12,
11890,
5034,
9229,
734,
16,
2254,
5034,
3844,
1769,
203,
203,
225,
871,
605,
15318,
1345,
12,
11890,
5034,
9229,
734,
16,
2254,
5034,
3844,
1769,
203,
225,
871,
13838,
2711,
1345,
12,
11890,
5034,
9229,
734,
16,
2254,
5034,
3844,
16,
2254,
5034,
7647,
14667,
1769,
203,
203,
225,
445,
752,
12003,
1435,
3903,
31,
203,
203,
225,
445,
5546,
12003,
12,
11890,
5034,
9229,
734,
13,
3903,
31,
203,
203,
225,
445,
7412,
12003,
12,
11890,
5034,
9229,
734,
16,
1758,
358,
13,
3903,
31,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
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
] |
./partial_match/4/0x7675CfdEB68Ff95AD4345Bf01Db866fCf73c5c42/sources/ethDepsitor.sol | return the current sharePrice | function getSharePrice()
public view
returns(uint256)
{
return sharePrice;
}
| 8,544,451 | [
1,
2463,
326,
783,
7433,
5147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7932,
834,
5147,
1435,
203,
1377,
1071,
1476,
203,
1377,
1135,
12,
11890,
5034,
13,
203,
225,
288,
203,
1377,
327,
7433,
5147,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >= 0.5.0 < 0.6.0;
import "./SafeMath.sol";
import "./usingOraclize.sol";
contract MarketCoin is usingOraclize {
// Use SafeMath library for uint256
using SafeMath for uint256;
//
// VARIABLES
//
bool public oraclizeRecursiveQuery;
address owner;
address updater;
//
// EVENTS
//
event LogNewOraclizeQuery(string _message);
event LogNewPrice(bytes32 _currency, uint256 _price, uint256 _timestamp);
constructor() public payable {
oraclize_setProof(proofType_Android | proofStorage_IPFS);
// Remove that before production.
// OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
// Set default values.
owner = msg.sender;
updater = msg.sender;
oraclizeRecursiveQuery = false;
// Initialize coins array for 3 currencies.
// There u can use e.g. https://min-api.cryptocompare.com/ API for oraclize.
currencies[bytes32("pln")] = Currency(0,
"", true); // pln
currencies[bytes32("eur")] = Currency(0,
"", true); // eur
currencies[bytes32("usd")] = Currency(0,
"", true); // usd
}
// Store currency details: price, api (for oraclize queries), mark currency as existing.
struct Currency {
uint256 price; // Currency price in wei.
string api; // Currency api for oraclize queries.
bool init; // Check if currency already exists.
}
mapping(bytes32 => Currency) currencies;
// Store oraclize query callback function details.
struct OraclizeCallback {
bytes32 currency; // Currency type, e.g. usd.
uint256 timestamp; // Delay to the next oraclize query.
}
mapping(bytes32 => OraclizeCallback) oraclizeCallback;
//
// SERVER SUPPORT
//
/* Update currency price.
* @param {bytes32} _currency - currency type in bytes32 format, e.g. usd => "0x757364"
* @param {uint256} _value - given currency price in wei
*/
function manualUpdate(bytes32 _currency, uint256 _value) external {
require(currencies[_currency].init, "Cannot find given currency");
require(msg.sender == updater, "Function for the smart contract updater");
// Update currency price.
currencies[_currency].price = _value;
// Emit a new event with updated price.
emit LogNewPrice(_currency, _value, now);
}
//
// ORACLIZE SUPPORT
//
/* Oraclize callback function.
* @param {bytes32} _queryId - oraclize query id
* @param {string} - result from a oraclize query
* @param {bytes} - authenticity proofs, https://docs.oraclize.it/#ethereum-quick-start-authenticity-proofs
*/
function __callback(bytes32 _queryId, string memory _result, bytes memory _proof) public {
require(msg.sender == oraclize_cbAddress(), "Callback function error");
// Recursive update.
if(oraclizeRecursiveQuery) {
oraclizeUpdate(oraclizeCallback[_queryId].currency, oraclizeCallback[_queryId].timestamp);
}
// Update price.
currencies[oraclizeCallback[_queryId].currency].price = toWei(_result);
// Emit a new event with updated price.
emit LogNewPrice(oraclizeCallback[_queryId].currency, currencies[oraclizeCallback[_queryId].currency].price, now);
}
/* Runs a new oraclize query.
* @param {bytes32} _currency - currency type in bytes32 format, e.g. usd => "0x757364"
* @param {uint256} _timestamp - delay to execute oraclize query.
*/
function oraclizeUpdate(bytes32 _currency, uint256 _timestamp) public payable {
require(currencies[_currency].init, "Cannot find given currency");
// Check if there (in smart contract) is enough money.
if (oraclize_getPrice("URL") > address(this).balance) {
emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee!");
} else {
emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer...");
// For query id.
bytes32 queryId;
// Check if oraclize_query should be called with a delay.
if(_timestamp > 0) {
queryId = oraclize_query(_timestamp, "URL", currencies[_currency].api); // Delay to next update
} else {
queryId = oraclize_query("URL", currencies[_currency].api); // Without delay.
}
// Save query details - query id and delay timestamp.
oraclizeCallback[queryId] = OraclizeCallback(_currency, _timestamp);
}
}
//
// UTILS
//
/* Convert given string value to wei.
* @param {string} _value - pric in a string format, e.g. "650.50"
* @return {uint256} - converted value to wei
*/
function toWei(string memory _value) public pure returns (uint256) {
// Convert string to int, e.g. "650.50" => 65050
uint256 valueInt = parseInt(_value, 2);
// Convert price to wei (e.g. from $0.01, 0.01 pln)
uint256 dividend = 1;
uint256 weiValue = dividend.mul(1e18).div(valueInt);
return weiValue;
}
/* Donations for a smart contract.
*/
function sendEtherToSmartContract() external payable {
require(msg.value > 0, "Not enough funds");
}
//
// GETTERS
//
/* Gives currency details.
* @param {bytes32} _currency - currency type, e.g. usd
* @return {uint256, string} - current currency price, api
*/
function getCurrencyDetails(bytes32 _currency) external view returns(uint256, string memory) {
require(currencies[_currency].init, "Cannot find given currency");
Currency memory currency = currencies[_currency];
return(
currency.price,
currency.api
);
}
/* Return current pln price.
*/
function PLN() external view returns(uint256) {
return currencies[bytes32("pln")].price;
}
/* Return current eur price.
*/
function EUR() external view returns(uint256) {
return currencies[bytes32("eur")].price;
}
/* Return current usd price.
*/
function USD() external view returns(uint256) {
return currencies[bytes32("usd")].price;
}
/* Return current gbp price.
*/
function GBP() external view returns(uint256) {
return currencies[bytes32("gbp")].price;
}
/* Gives currency price.
* @param {bytes32} _currency - currency type, e.g. usd
* @return {uint256} - current currency price
*/
function getCurrencyPrice(bytes32 _currency) external view returns(uint256) {
require(currencies[_currency].init, "Cannot find given currency");
return currencies[_currency].price;
}
//
// DEVELOPERS
//
/* Change smart contract owner.
* @param {address} _owner - new smart contract owner address
*/
function changeContractOwner(address _owner) external {
require(msg.sender == owner, "Function for the smart contract developers");
// Update a new smart contract owner.
owner = _owner;
}
/* Add a new currency.
* @param {bytes32} _currency - new currency type, e.g. usd
* @param {string} _api - api for oraclize query update
*/
function addCurrency(bytes32 _currency, string calldata _api) external {
require(msg.sender == owner, "Function for the smart contract developers");
require(currencies[_currency].init, "This currency already exists");
// Set a new currency.
currencies[_currency] = Currency(0, _api, true);
}
/* Change currency api.
* @param {bytes32} _currency - currency type, e.g. usd
* @param {string} _api - api for oraclize query update
*/
function changeCurrencyAPI(bytes32 _currency, string calldata _api) external {
require(msg.sender == owner, "Function for the smart contract developers");
require(!currencies[_currency].init, "Cannot find given currency");
// Set a new currency api.
currencies[_currency].api = _api;
}
/* Enable / disable recursive oraclize updates.
* @param {bool} _type - true / false (enable / disable)
*/
function oraclizeSetRecursiveOption(bool _type) external {
require(msg.sender == owner, "Function for the smart contract developers");
oraclizeRecursiveQuery = _type;
}
/* Get smart contract balance.
*/
function getSmartContractBalance() external view returns (uint256) {
require(msg.sender == owner, "Function for the smart contract developers");
return address(this).balance;
}
}
| Store currency details: price, api (for oraclize queries), mark currency as existing. | struct Currency {
}
mapping(bytes32 => Currency) currencies;
| 15,803,873 | [
1,
2257,
5462,
3189,
30,
6205,
16,
1536,
261,
1884,
578,
10150,
554,
6218,
3631,
2267,
5462,
487,
2062,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
13078,
288,
203,
565,
289,
203,
203,
565,
2874,
12,
3890,
1578,
516,
13078,
13,
19239,
31,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./libs/IUniRouter02.sol";
import "./libs/IWETH.sol";
interface IToken {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
}
contract BrewlabsLockup is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Whether it is initialized
bool public isInitialized;
uint256 public duration = 365; // 365 days
// Whether a limit is set for users
bool public hasUserLimit;
// The pool limit (0 if none)
uint256 public poolLimitPerUser;
// The block number when staking starts.
uint256 public startBlock;
// The block number when staking ends.
uint256 public bonusEndBlock;
// swap router and path, slipPage
uint256 public slippageFactor = 950; // 5% default slippage tolerance
uint256 public constant slippageFactorUL = 995;
address public uniRouterAddress;
address[] public reflectionToStakedPath;
address[] public earnedToStakedPath;
address public walletA;
address public buyBackWallet = 0xE1f1dd010BBC2860F81c8F90Ea4E38dB949BB16F;
uint256 public performanceFee = 0.00089 ether;
// The precision factor
uint256 public PRECISION_FACTOR;
uint256 public PRECISION_FACTOR_REFLECTION;
// The staked token
IERC20 public stakingToken;
// The earned token
IERC20 public earnedToken;
// The dividend token of staking token
address public dividendToken;
// Accrued token per share
uint256 public accDividendPerShare;
uint256 public totalStaked;
uint256 private totalEarned;
uint256 private totalReflections;
uint256 private reflectionDebt;
struct Lockup {
uint8 stakeType;
uint256 duration;
uint256 depositFee;
uint256 withdrawFee;
uint256 rate;
uint256 accTokenPerShare;
uint256 lastRewardBlock;
uint256 totalStaked;
}
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256 locked;
uint256 available;
}
struct Stake {
uint8 stakeType;
uint256 amount; // amount to stake
uint256 duration; // the lockup duration of the stake
uint256 end; // when does the staking period end
uint256 rewardDebt; // Reward debt
uint256 reflectionDebt; // Reflection debt
}
uint256 constant MAX_STAKES = 256;
Lockup[] public lockups;
mapping(address => Stake[]) public userStakes;
mapping(address => UserInfo) public userStaked;
event Deposit(address indexed user, uint256 stakeType, uint256 amount);
event Withdraw(address indexed user, uint256 stakeType, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event AdminTokenRecovered(address tokenRecovered, uint256 amount);
event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock);
event LockupUpdated(uint8 _type, uint256 _duration, uint256 _fee0, uint256 _fee1, uint256 _rate);
event RewardsStop(uint256 blockNumber);
event UpdatePoolLimit(uint256 poolLimitPerUser, bool hasLimit);
event ServiceInfoUpadted(address _addr, uint256 _fee);
event DurationUpdated(uint256 _duration);
event SetSettings(
uint256 _slippageFactor,
address _uniRouter,
address[] _path0,
address[] _path1,
address _walletA
);
constructor() {}
/*
* @notice Initialize the contract
* @param _stakingToken: staked token address
* @param _earnedToken: earned token address
* @param _dividendToken: reflection token address
* @param _uniRouter: uniswap router address for swap tokens
* @param _earnedToStakedPath: swap path to compound (earned -> staking path)
* @param _reflectionToStakedPath: swap path to compound (reflection -> staking path)
*/
function initialize(
IERC20 _stakingToken,
IERC20 _earnedToken,
address _dividendToken,
address _uniRouter,
address[] memory _earnedToStakedPath,
address[] memory _reflectionToStakedPath
) external onlyOwner {
require(!isInitialized, "Already initialized");
// Make this contract initialized
isInitialized = true;
stakingToken = _stakingToken;
earnedToken = _earnedToken;
dividendToken = _dividendToken;
walletA = msg.sender;
uint256 decimalsRewardToken = uint256(IToken(address(earnedToken)).decimals());
require(decimalsRewardToken < 30, "Must be inferior to 30");
PRECISION_FACTOR = uint256(10**(40 - decimalsRewardToken));
uint256 decimalsdividendToken = 18;
if(address(dividendToken) != address(0x0)) {
decimalsdividendToken = uint256(IToken(address(dividendToken)).decimals());
require(decimalsdividendToken < 30, "Must be inferior to 30");
}
PRECISION_FACTOR_REFLECTION = uint256(10**(40 - decimalsRewardToken));
uniRouterAddress = _uniRouter;
earnedToStakedPath = _earnedToStakedPath;
reflectionToStakedPath = _reflectionToStakedPath;
}
/*
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to withdraw (in earnedToken)
*/
function deposit(uint256 _amount, uint8 _stakeType) external nonReentrant {
require(startBlock > 0 && startBlock < block.number, "Staking hasn't started yet");
require(_amount > 0, "Amount should be greator than 0");
require(_stakeType < lockups.length, "Invalid stake type");
_updatePool(_stakeType);
UserInfo storage user = userStaked[msg.sender];
Stake[] storage stakes = userStakes[msg.sender];
Lockup storage lockup = lockups[_stakeType];
uint256 pending = 0;
uint256 pendingCompound = 0;
uint256 pendingReflection = 0;
uint256 compounded = 0;
for(uint256 j = 0; j < stakes.length; j++) {
Stake storage stake = stakes[j];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
pendingReflection = pendingReflection + (
stake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - stake.reflectionDebt
);
uint256 _pending = stake.amount * lockup.accTokenPerShare / PRECISION_FACTOR - stake.rewardDebt;
if(stake.end > block.timestamp) {
pendingCompound = pendingCompound + _pending;
if(address(stakingToken) != address(earnedToken) && _pending > 0) {
uint256 _beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(_pending, earnedToStakedPath, address(this));
uint256 _afterAmount = stakingToken.balanceOf(address(this));
_pending = _afterAmount - _beforeAmount;
}
compounded = compounded + _pending;
stake.amount = stake.amount + _pending;
} else {
pending = pending + _pending;
}
stake.rewardDebt = stake.amount * lockup.accTokenPerShare / PRECISION_FACTOR;
stake.reflectionDebt = stake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
if (pendingCompound > 0) {
require(availableRewardTokens() >= pendingCompound, "Insufficient reward tokens");
if(totalEarned > pendingCompound) {
totalEarned = totalEarned - pendingCompound;
} else {
totalEarned = 0;
}
}
if (pendingReflection > 0) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
uint256 beforeAmount = stakingToken.balanceOf(address(this));
stakingToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 afterAmount = stakingToken.balanceOf(address(this));
uint256 realAmount = afterAmount - beforeAmount;
if (hasUserLimit) {
require(
realAmount + user.amount <= poolLimitPerUser,
"User amount above limit"
);
}
if (lockup.depositFee > 0) {
uint256 fee = realAmount * lockup.depositFee / 10000;
if (fee > 0) {
stakingToken.safeTransfer(walletA, fee);
realAmount = realAmount - fee;
}
}
_addStake(_stakeType, msg.sender, lockup.duration, realAmount);
user.amount = user.amount + realAmount + compounded;
lockup.totalStaked = lockup.totalStaked + realAmount + compounded;
totalStaked = totalStaked + realAmount + compounded;
emit Deposit(msg.sender, _stakeType, realAmount + compounded);
}
function _addStake(uint8 _stakeType, address _account, uint256 _duration, uint256 _amount) internal {
Stake[] storage stakes = userStakes[_account];
uint256 end = block.timestamp + _duration * 1 days;
uint256 i = stakes.length;
require(i < MAX_STAKES, "Max stakes");
stakes.push(); // grow the array
// find the spot where we can insert the current stake
// this should make an increasing list sorted by end
while (i != 0 && stakes[i - 1].end > end) {
// shift it back one
stakes[i] = stakes[i - 1];
i -= 1;
}
Lockup storage lockup = lockups[_stakeType];
// insert the stake
Stake storage newStake = stakes[i];
newStake.stakeType = _stakeType;
newStake.duration = _duration;
newStake.end = end;
newStake.amount = _amount;
newStake.rewardDebt = newStake.amount * lockup.accTokenPerShare / PRECISION_FACTOR;
newStake.reflectionDebt = newStake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
/*
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in earnedToken)
*/
function withdraw(uint256 _amount, uint8 _stakeType) external nonReentrant {
require(_amount > 0, "Amount should be greator than 0");
require(_stakeType < lockups.length, "Invalid stake type");
_updatePool(_stakeType);
UserInfo storage user = userStaked[msg.sender];
Stake[] storage stakes = userStakes[msg.sender];
Lockup storage lockup = lockups[_stakeType];
uint256 pending = 0;
uint256 pendingCompound = 0;
uint256 pendingReflection = 0;
uint256 compounded = 0;
uint256 remained = _amount;
for(uint256 j = 0; j < stakes.length; j++) {
Stake storage stake = stakes[j];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
if(remained == 0) break;
uint256 _pending = stake.amount * lockup.accTokenPerShare / PRECISION_FACTOR - stake.rewardDebt;
pendingReflection = pendingReflection + (
stake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - stake.reflectionDebt
);
if(stake.end > block.timestamp) {
pendingCompound = pendingCompound + _pending;
if(address(stakingToken) != address(earnedToken) && _pending > 0) {
uint256 _beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(_pending, earnedToStakedPath, address(this));
uint256 _afterAmount = stakingToken.balanceOf(address(this));
_pending = _afterAmount - _beforeAmount;
}
compounded = compounded + _pending;
stake.amount = stake.amount + _pending;
} else {
pending = pending + _pending;
if(stake.amount > remained) {
stake.amount = stake.amount - remained;
remained = 0;
} else {
remained = remained - stake.amount;
stake.amount = 0;
}
}
stake.rewardDebt = stake.amount * lockup.accTokenPerShare / PRECISION_FACTOR;
stake.reflectionDebt = stake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
if (pendingCompound > 0) {
require(availableRewardTokens() >= pendingCompound, "Insufficient reward tokens");
if(totalEarned > pendingCompound) {
totalEarned = totalEarned - pendingCompound;
} else {
totalEarned = 0;
}
emit Deposit(msg.sender, _stakeType, compounded);
}
if (pendingReflection > 0) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
uint256 realAmount = _amount - remained;
user.amount = user.amount - realAmount + pendingCompound;
lockup.totalStaked = lockup.totalStaked - realAmount + pendingCompound;
totalStaked = totalStaked - realAmount + pendingCompound;
if(realAmount > 0) {
if (lockup.withdrawFee > 0) {
uint256 fee = realAmount * lockup.withdrawFee / 10000;
stakingToken.safeTransfer(walletA, fee);
realAmount = realAmount - fee;
}
stakingToken.safeTransfer(address(msg.sender), realAmount);
}
emit Withdraw(msg.sender, _stakeType, realAmount);
}
function claimReward(uint8 _stakeType) external payable nonReentrant {
if(_stakeType >= lockups.length) return;
if(startBlock == 0) return;
_transferPerformanceFee();
_updatePool(_stakeType);
UserInfo storage user = userStaked[msg.sender];
Stake[] storage stakes = userStakes[msg.sender];
Lockup storage lockup = lockups[_stakeType];
uint256 pending = 0;
uint256 pendingCompound = 0;
uint256 compounded = 0;
for(uint256 j = 0; j < stakes.length; j++) {
Stake storage stake = stakes[j];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
uint256 _pending = stake.amount * lockup.accTokenPerShare / PRECISION_FACTOR - stake.rewardDebt;
if(stake.end > block.timestamp) {
pendingCompound = pendingCompound + _pending;
if(address(stakingToken) != address(earnedToken) && _pending > 0) {
uint256 _beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(_pending, earnedToStakedPath, address(this));
uint256 _afterAmount = stakingToken.balanceOf(address(this));
_pending = _afterAmount - _beforeAmount;
}
compounded = compounded + _pending;
stake.amount = stake.amount + _pending;
stake.reflectionDebt = stake.reflectionDebt + _pending * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
} else {
pending = pending + _pending;
}
stake.rewardDebt = stake.amount * lockup.accTokenPerShare / PRECISION_FACTOR;
}
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
if (pendingCompound > 0) {
require(availableRewardTokens() >= pendingCompound, "Insufficient reward tokens");
if(totalEarned > pendingCompound) {
totalEarned = totalEarned - pendingCompound;
} else {
totalEarned = 0;
}
user.amount = user.amount + compounded;
lockup.totalStaked = lockup.totalStaked + compounded;
totalStaked = totalStaked + compounded;
emit Deposit(msg.sender, _stakeType, compounded);
}
}
function claimDividend(uint8 _stakeType) external payable nonReentrant {
if(_stakeType >= lockups.length) return;
if(startBlock == 0) return;
_transferPerformanceFee();
_updatePool(_stakeType);
Stake[] storage stakes = userStakes[msg.sender];
uint256 pendingReflection = 0;
for(uint256 j = 0; j < stakes.length; j++) {
Stake storage stake = stakes[j];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
pendingReflection = pendingReflection + (
stake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - stake.reflectionDebt
);
stake.reflectionDebt = stake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
if (pendingReflection > 0) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
}
function compoundReward(uint8 _stakeType) external payable nonReentrant {
if(_stakeType >= lockups.length) return;
if(startBlock == 0) return;
_transferPerformanceFee();
_updatePool(_stakeType);
UserInfo storage user = userStaked[msg.sender];
Stake[] storage stakes = userStakes[msg.sender];
Lockup storage lockup = lockups[_stakeType];
uint256 pending = 0;
uint256 compounded = 0;
for(uint256 j = 0; j < stakes.length; j++) {
Stake storage stake = stakes[j];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
uint256 _pending = stake.amount * lockup.accTokenPerShare / PRECISION_FACTOR - stake.rewardDebt;
pending = pending + _pending;
if(address(stakingToken) != address(earnedToken) && _pending > 0) {
uint256 _beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(_pending, earnedToStakedPath, address(this));
uint256 _afterAmount = stakingToken.balanceOf(address(this));
_pending = _afterAmount - _beforeAmount;
}
compounded = compounded + _pending;
stake.amount = stake.amount + _pending;
stake.rewardDebt = stake.amount * lockup.accTokenPerShare / PRECISION_FACTOR;
stake.reflectionDebt = stake.reflectionDebt + _pending * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
user.amount = user.amount + compounded;
lockup.totalStaked = lockup.totalStaked + compounded;
totalStaked = totalStaked + compounded;
emit Deposit(msg.sender, _stakeType, compounded);
}
}
function compoundDividend(uint8 _stakeType) external payable nonReentrant {
if(_stakeType >= lockups.length) return;
if(startBlock == 0) return;
_transferPerformanceFee();
_updatePool(_stakeType);
UserInfo storage user = userStaked[msg.sender];
Stake[] storage stakes = userStakes[msg.sender];
Lockup storage lockup = lockups[_stakeType];
uint256 pendingReflection = 0;
uint256 compounded = 0;
for(uint256 j = 0; j < stakes.length; j++) {
Stake storage stake = stakes[j];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
uint256 _pending = stake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - stake.reflectionDebt;
pendingReflection = pendingReflection + _pending;
if(address(stakingToken) != address(dividendToken) && _pending > 0) {
if(address(dividendToken) == address(0x0)) {
address wethAddress = IUniRouter02(uniRouterAddress).WETH();
IWETH(wethAddress).deposit{ value: _pending }();
}
uint256 _beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(_pending, reflectionToStakedPath, address(this));
uint256 _afterAmount = stakingToken.balanceOf(address(this));
_pending = _afterAmount - _beforeAmount;
}
compounded = compounded + _pending;
stake.amount = stake.amount + _pending;
stake.rewardDebt = stake.rewardDebt + _pending * lockup.accTokenPerShare / PRECISION_FACTOR;
stake.reflectionDebt = stake.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
totalReflections = totalReflections - pendingReflection;
if (pendingReflection > 0) {
user.amount = user.amount + compounded;
lockup.totalStaked = lockup.totalStaked + compounded;
totalStaked = totalStaked + compounded;
emit Deposit(msg.sender, _stakeType, compounded);
}
}
function _transferPerformanceFee() internal {
require(msg.value >= performanceFee, 'should pay small gas to compound or harvest');
payable(buyBackWallet).transfer(performanceFee);
if(msg.value > performanceFee) {
payable(msg.sender).transfer(msg.value - performanceFee);
}
}
/*
* @notice Withdraw staked tokens without caring about rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw(uint8 _stakeType) external nonReentrant {
if(_stakeType >= lockups.length) return;
UserInfo storage user = userStaked[msg.sender];
Stake[] storage stakes = userStakes[msg.sender];
Lockup storage lockup = lockups[_stakeType];
uint256 amountToTransfer = 0;
for(uint256 j = 0; j < stakes.length; j++) {
Stake storage stake = stakes[j];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
amountToTransfer = amountToTransfer + stake.amount;
stake.amount = 0;
stake.rewardDebt = 0;
stake.reflectionDebt = 0;
}
if (amountToTransfer > 0) {
stakingToken.safeTransfer(address(msg.sender), amountToTransfer);
user.amount = user.amount - amountToTransfer;
lockup.totalStaked = lockup.totalStaked - amountToTransfer;
totalStaked = totalStaked - amountToTransfer;
}
emit EmergencyWithdraw(msg.sender, amountToTransfer);
}
function rewardPerBlock(uint8 _stakeType) external view returns (uint256) {
if(_stakeType >= lockups.length) return 0;
return lockups[_stakeType].rate;
}
/**
* @notice Available amount of reward token
*/
function availableRewardTokens() public view returns (uint256) {
if(address(earnedToken) == address(dividendToken)) return totalEarned;
uint256 _amount = earnedToken.balanceOf(address(this));
if (address(earnedToken) == address(stakingToken)) {
if (_amount < totalStaked) return 0;
return _amount - totalStaked;
}
return _amount;
}
/**
* @notice Available amount of reflection token
*/
function availableDividendTokens() public view returns (uint256) {
if(address(dividendToken) == address(0x0)) {
return address(this).balance;
}
uint256 _amount = IERC20(dividendToken).balanceOf(address(this));
if(address(dividendToken) == address(earnedToken)) {
if(_amount < totalEarned) return 0;
_amount = _amount - totalEarned;
}
if(address(dividendToken) == address(stakingToken)) {
if(_amount < totalStaked) return 0;
_amount = _amount - totalStaked;
}
return _amount;
}
function userInfo(uint8 _stakeType, address _account) external view returns (uint256 amount, uint256 available, uint256 locked) {
Stake[] storage stakes = userStakes[_account];
for(uint256 i = 0; i < stakes.length; i++) {
Stake storage stake = stakes[i];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
amount = amount + stake.amount;
if(block.timestamp > stake.end) {
available = available + stake.amount;
} else {
locked = locked + stake.amount;
}
}
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _account, uint8 _stakeType) external view returns (uint256) {
if(_stakeType >= lockups.length) return 0;
if(startBlock == 0) return 0;
Stake[] storage stakes = userStakes[_account];
Lockup storage lockup = lockups[_stakeType];
if(lockup.totalStaked == 0) return 0;
uint256 adjustedTokenPerShare = lockup.accTokenPerShare;
if (block.number > lockup.lastRewardBlock && lockup.totalStaked != 0 && lockup.lastRewardBlock > 0) {
uint256 multiplier = _getMultiplier(lockup.lastRewardBlock, block.number);
uint256 reward = multiplier * lockup.rate;
adjustedTokenPerShare = lockup.accTokenPerShare + reward * PRECISION_FACTOR / lockup.totalStaked;
}
uint256 pending = 0;
for(uint256 i = 0; i < stakes.length; i++) {
Stake storage stake = stakes[i];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
pending = pending + (
stake.amount * adjustedTokenPerShare / PRECISION_FACTOR - stake.rewardDebt
);
}
return pending;
}
function pendingDividends(address _account, uint8 _stakeType) external view returns (uint256) {
if(_stakeType >= lockups.length) return 0;
if(startBlock == 0) return 0;
Stake[] storage stakes = userStakes[_account];
if(totalStaked == 0) return 0;
uint256 reflectionAmount = availableDividendTokens();
uint256 sTokenBal = stakingToken.balanceOf(address(this));
if(address(stakingToken) == dividendToken) {
sTokenBal = sTokenBal - reflectionAmount;
}
uint256 adjustedReflectionPerShare = accDividendPerShare + (
(reflectionAmount - totalReflections) * PRECISION_FACTOR_REFLECTION / sTokenBal
);
uint256 pendingReflection = 0;
for(uint256 i = 0; i < stakes.length; i++) {
Stake storage stake = stakes[i];
if(stake.stakeType != _stakeType) continue;
if(stake.amount == 0) continue;
pendingReflection = pendingReflection + (
stake.amount * adjustedReflectionPerShare / PRECISION_FACTOR_REFLECTION - stake.reflectionDebt
);
}
return pendingReflection;
}
/************************
** Admin Methods
*************************/
function harvest() external onlyOwner {
_updatePool(0);
uint256 _amount = stakingToken.balanceOf(address(this));
_amount = _amount - totalStaked;
uint256 pendingReflection = _amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - reflectionDebt;
if(pendingReflection > 0) {
if(address(dividendToken) == address(0x0)) {
payable(walletA).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(walletA, pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
reflectionDebt = _amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
/*
* @notice Deposit reward token
* @dev Only call by owner. Needs to be for deposit of reward token when reflection token is same with reward token.
*/
function depositRewards(uint _amount) external onlyOwner nonReentrant {
require(_amount > 0, "invalid amount");
uint256 beforeAmt = earnedToken.balanceOf(address(this));
earnedToken.safeTransferFrom(msg.sender, address(this), _amount);
uint256 afterAmt = earnedToken.balanceOf(address(this));
totalEarned = totalEarned + afterAmt - beforeAmt;
}
/*
* @notice Withdraw reward token
* @dev Only callable by owner. Needs to be for emergency.
*/
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
require( block.number > bonusEndBlock, "Pool is running");
require(availableRewardTokens() >= _amount, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), _amount);
if (totalEarned > 0) {
if (_amount > totalEarned) {
totalEarned = 0;
} else {
totalEarned = totalEarned - _amount;
}
}
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(
_tokenAddress != address(earnedToken),
"Cannot be reward token"
);
if(_tokenAddress == address(stakingToken)) {
uint256 tokenBal = stakingToken.balanceOf(address(this));
require(_tokenAmount <= tokenBal - totalStaked, "Insufficient balance");
}
if(_tokenAddress == address(0x0)) {
payable(msg.sender).transfer(_tokenAmount);
} else {
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
}
emit AdminTokenRecovered(_tokenAddress, _tokenAmount);
}
function startReward() external onlyOwner {
require(startBlock == 0, "Pool was already started");
startBlock = block.number + 100;
bonusEndBlock = startBlock + duration * 6426;
for(uint256 i = 0; i < lockups.length; i++) {
lockups[i].lastRewardBlock = startBlock;
}
emit NewStartAndEndBlocks(startBlock, bonusEndBlock);
}
function stopReward() external onlyOwner {
bonusEndBlock = block.number;
emit RewardsStop(bonusEndBlock);
}
/*
* @notice Update pool limit per user
* @dev Only callable by owner.
* @param _hasUserLimit: whether the limit remains forced
* @param _poolLimitPerUser: new pool limit per user
*/
function updatePoolLimitPerUser( bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner {
if (_hasUserLimit) {
require(
_poolLimitPerUser > poolLimitPerUser,
"New limit must be higher"
);
poolLimitPerUser = _poolLimitPerUser;
} else {
poolLimitPerUser = 0;
}
hasUserLimit = _hasUserLimit;
emit UpdatePoolLimit(poolLimitPerUser, _hasUserLimit);
}
function updateLockup(uint8 _stakeType, uint256 _duration, uint256 _depositFee, uint256 _withdrawFee, uint256 _rate) external onlyOwner {
// require(block.number < startBlock, "Pool was already started");
require(_stakeType < lockups.length, "Lockup Not found");
require(_depositFee < 2000, "Invalid deposit fee");
require(_withdrawFee < 2000, "Invalid withdraw fee");
_updatePool(_stakeType);
Lockup storage _lockup = lockups[_stakeType];
_lockup.duration = _duration;
_lockup.depositFee = _depositFee;
_lockup.withdrawFee = _withdrawFee;
_lockup.rate = _rate;
emit LockupUpdated(_stakeType, _duration, _depositFee, _withdrawFee, _rate);
}
function addLockup(uint256 _duration, uint256 _depositFee, uint256 _withdrawFee, uint256 _rate) external onlyOwner {
require(_depositFee < 2000, "Invalid deposit fee");
require(_withdrawFee < 2000, "Invalid withdraw fee");
lockups.push();
Lockup storage _lockup = lockups[lockups.length - 1];
_lockup.duration = _duration;
_lockup.depositFee = _depositFee;
_lockup.withdrawFee = _withdrawFee;
_lockup.rate = _rate;
_lockup.lastRewardBlock = block.number;
emit LockupUpdated(uint8(lockups.length - 1), _duration, _depositFee, _withdrawFee, _rate);
}
function setServiceInfo(address _addr, uint256 _fee) external {
require(msg.sender == buyBackWallet, "setServiceInfo: FORBIDDEN");
require(_addr != address(0x0), "Invalid address");
require(_fee < 0.05 ether, "fee cannot exceed 0.05 ether");
buyBackWallet = _addr;
performanceFee = _fee;
emit ServiceInfoUpadted(_addr, _fee);
}
function setDuration(uint256 _duration) external onlyOwner {
require(startBlock == 0, "Pool was already started");
require(_duration >= 30, "lower limit reached");
duration = _duration;
emit DurationUpdated(_duration);
}
function setSettings(
uint256 _slippageFactor,
address _uniRouter,
address[] memory _earnedToStakedPath,
address[] memory _reflectionToStakedPath,
address _feeAddr
) external onlyOwner {
require(_slippageFactor <= slippageFactorUL, "_slippageFactor too high");
require(_feeAddr != address(0x0), "Invalid Address");
slippageFactor = _slippageFactor;
uniRouterAddress = _uniRouter;
reflectionToStakedPath = _reflectionToStakedPath;
earnedToStakedPath = _earnedToStakedPath;
walletA = _feeAddr;
emit SetSettings(_slippageFactor, _uniRouter, _earnedToStakedPath, _reflectionToStakedPath, _feeAddr);
}
/************************
** Internal Methods
*************************/
/*
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool(uint8 _stakeType) internal {
// calc reflection rate
if(totalStaked > 0) {
uint256 reflectionAmount = availableDividendTokens();
uint256 sTokenBal = stakingToken.balanceOf(address(this));
if(address(stakingToken) == dividendToken) {
sTokenBal = sTokenBal - reflectionAmount;
}
accDividendPerShare = accDividendPerShare + (
(reflectionAmount - totalReflections) * PRECISION_FACTOR_REFLECTION / sTokenBal
);
totalReflections = reflectionAmount;
}
Lockup storage lockup = lockups[_stakeType];
if (block.number <= lockup.lastRewardBlock || lockup.lastRewardBlock == 0) return;
if (lockup.totalStaked == 0) {
lockup.lastRewardBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(lockup.lastRewardBlock, block.number);
uint256 _reward = multiplier * lockup.rate;
lockup.accTokenPerShare = lockup.accTokenPerShare + (
_reward * PRECISION_FACTOR / lockup.totalStaked
);
lockup.lastRewardBlock = block.number;
}
/*
* @notice Return reward multiplier over the given _from to _to block.
* @param _from: block to start
* @param _to: block to finish
*/
function _getMultiplier(uint256 _from, uint256 _to)
internal
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to - _from;
} else if (_from >= bonusEndBlock) {
return 0;
} else {
return bonusEndBlock - _from;
}
}
function _safeSwap(
uint256 _amountIn,
address[] memory _path,
address _to
) internal {
uint256[] memory amounts = IUniRouter02(uniRouterAddress).getAmountsOut(_amountIn, _path);
uint256 amountOut = amounts[amounts.length - 1];
IERC20(_path[0]).safeApprove(uniRouterAddress, _amountIn);
IUniRouter02(uniRouterAddress).swapExactTokensForTokens(
_amountIn,
amountOut * slippageFactor / 1000,
_path,
_to,
block.timestamp + 600
);
}
receive() external payable {}
}
// 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 v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IUniRouter01.sol";
interface IUniRouter02 is IUniRouter01 {
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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniRouter01 {
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);
} | @notice Withdraw reward token @dev Only callable by owner. Needs to be for emergency./ | function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
require( block.number > bonusEndBlock, "Pool is running");
require(availableRewardTokens() >= _amount, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), _amount);
if (totalEarned > 0) {
if (_amount > totalEarned) {
totalEarned = 0;
totalEarned = totalEarned - _amount;
}
}
}
| 5,923,613 | [
1,
1190,
9446,
19890,
1147,
225,
5098,
4140,
635,
3410,
18,
29164,
358,
506,
364,
801,
24530,
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
] | [
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,
801,
24530,
17631,
1060,
1190,
9446,
12,
11890,
5034,
389,
8949,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
1203,
18,
2696,
405,
324,
22889,
1638,
1768,
16,
315,
2864,
353,
3549,
8863,
203,
3639,
2583,
12,
5699,
17631,
1060,
5157,
1435,
1545,
389,
8949,
16,
315,
5048,
11339,
19890,
2430,
8863,
203,
203,
3639,
425,
1303,
329,
1345,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
389,
8949,
1769,
203,
540,
203,
3639,
309,
261,
4963,
41,
1303,
329,
405,
374,
13,
288,
203,
5411,
309,
261,
67,
8949,
405,
2078,
41,
1303,
329,
13,
288,
203,
7734,
2078,
41,
1303,
329,
273,
374,
31,
203,
7734,
2078,
41,
1303,
329,
273,
2078,
41,
1303,
329,
300,
389,
8949,
31,
203,
5411,
289,
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
] |
./partial_match/97/0x9949ee47831901B6Cb17351963a6274dA6231305/sources/BunnyPool.sol | IBEP20 public constant stakingToken = IBEP20(0xC9849E6fdB743d08fAeE3E34dd2D1bc69EA11a51); bunny address private constant presaleContract = 0x641414e2a04c8f8EbBf49eD47cc87dccbA42BF07; IStrategyHelper public helper = IStrategyHelper(0xA84c09C1a2cF4918CaEf625682B429398b97A1a0); IPancakeRouter02 private constant ROUTER = IPancakeRouter02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); | contract BunnyPool is IStrategyLegacy, RewardsDistributionRecipient, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
IBEP20 public stakingToken;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 90 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => bool) private _stakePermission;
address private constant deadAddress = 0x000000000000000000000000000000000000dEaD;
address public presaleContract;
mapping(address => uint256) private _presaleBalance;
uint private constant timestamp2HoursAfterPresaleEnds = 1605585600 + (2 hours);
uint private constant timestamp90DaysAfterPresaleEnds = 1605585600 + (90 days);
IStrategyHelper public helper;
IPancakeRouter02 private ROUTER;
constructor(
IBEP20 _stakingToken,
address _presaleContract,
IStrategyHelper _helper,
IPancakeRouter02 _ROUTER
function deposit(uint _amount) external;
function depositAll() external;
function withdrawAll() external;
function harvest() external;
function balance() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function principalOf(address account) external view returns (uint);
function profitOf(address account) external view returns (uint _usd, uint _bunny, uint _bnb);
function apy() external view returns (uint _usd, uint _bunny, uint _bnb);
function info(address account) external view returns (UserInfo memory);
}
pragma solidity ^0.6.12;
}
) public {
stakingToken = _stakingToken;
presaleContract = _presaleContract;
helper = _helper;
ROUTER = _ROUTER;
rewardsDistribution = msg.sender;
_stakePermission[msg.sender] = true;
_stakePermission[presaleContract] = true;
stakingToken.safeApprove(address(ROUTER), uint(~0));
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balance() override external view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) override external view returns (uint256) {
return _balances[account];
}
function presaleBalanceOf(address account) external view returns(uint256) {
return _presaleBalance[account];
}
function principalOf(address account) override external view returns (uint256) {
return _balances[account];
}
function withdrawableBalanceOf(address account) override public view returns (uint) {
if (block.timestamp > timestamp90DaysAfterPresaleEnds) {
return _balances[account];
return _balances[account].sub(_presaleBalance[account]);
uint bunnySupply = stakingToken.totalSupply().sub(stakingToken.balanceOf(deadAddress));
if (soldInPresale >= bunnySupply) {
return _balances[account].sub(_presaleBalance[account]);
}
uint bunnyNewMint = bunnySupply.sub(soldInPresale);
if (bunnyNewMint >= soldInPresale) {
return _balances[account];
}
uint lockedRatio = (soldInPresale.sub(bunnyNewMint)).mul(1e18).div(soldInPresale);
uint lockedBalance = _presaleBalance[account].mul(lockedRatio).div(1e18);
return _balances[account].sub(lockedBalance);
}
}
function withdrawableBalanceOf(address account) override public view returns (uint) {
if (block.timestamp > timestamp90DaysAfterPresaleEnds) {
return _balances[account];
return _balances[account].sub(_presaleBalance[account]);
uint bunnySupply = stakingToken.totalSupply().sub(stakingToken.balanceOf(deadAddress));
if (soldInPresale >= bunnySupply) {
return _balances[account].sub(_presaleBalance[account]);
}
uint bunnyNewMint = bunnySupply.sub(soldInPresale);
if (bunnyNewMint >= soldInPresale) {
return _balances[account];
}
uint lockedRatio = (soldInPresale.sub(bunnyNewMint)).mul(1e18).div(soldInPresale);
uint lockedBalance = _presaleBalance[account].mul(lockedRatio).div(1e18);
return _balances[account].sub(lockedBalance);
}
}
} else if (block.timestamp < timestamp2HoursAfterPresaleEnds) {
} else {
function withdrawableBalanceOf(address account) override public view returns (uint) {
if (block.timestamp > timestamp90DaysAfterPresaleEnds) {
return _balances[account];
return _balances[account].sub(_presaleBalance[account]);
uint bunnySupply = stakingToken.totalSupply().sub(stakingToken.balanceOf(deadAddress));
if (soldInPresale >= bunnySupply) {
return _balances[account].sub(_presaleBalance[account]);
}
uint bunnyNewMint = bunnySupply.sub(soldInPresale);
if (bunnyNewMint >= soldInPresale) {
return _balances[account];
}
uint lockedRatio = (soldInPresale.sub(bunnyNewMint)).mul(1e18).div(soldInPresale);
uint lockedBalance = _presaleBalance[account].mul(lockedRatio).div(1e18);
return _balances[account].sub(lockedBalance);
}
}
function withdrawableBalanceOf(address account) override public view returns (uint) {
if (block.timestamp > timestamp90DaysAfterPresaleEnds) {
return _balances[account];
return _balances[account].sub(_presaleBalance[account]);
uint bunnySupply = stakingToken.totalSupply().sub(stakingToken.balanceOf(deadAddress));
if (soldInPresale >= bunnySupply) {
return _balances[account].sub(_presaleBalance[account]);
}
uint bunnyNewMint = bunnySupply.sub(soldInPresale);
if (bunnyNewMint >= soldInPresale) {
return _balances[account];
}
uint lockedRatio = (soldInPresale.sub(bunnyNewMint)).mul(1e18).div(soldInPresale);
uint lockedBalance = _presaleBalance[account].mul(lockedRatio).div(1e18);
return _balances[account].sub(lockedBalance);
}
}
function profitOf(address account) override public view returns (uint _usd, uint _bunny, uint _bnb) {
_usd = 0;
_bunny = 0;
_bnb = helper.tvlInBNB(address(rewardsToken), earned(account));
}
function tvl() override public view returns (uint) {
uint price = helper.tokenPriceInBNB(address(stakingToken));
return _totalSupply.mul(price).div(1e18);
}
function apy() override public view returns(uint _usd, uint _bunny, uint _bnb) {
uint tokenDecimals = 1e18;
uint __totalSupply = _totalSupply;
if (__totalSupply == 0) {
__totalSupply = tokenDecimals;
}
uint rewardPerTokenPerSecond = rewardRate.mul(tokenDecimals).div(__totalSupply);
uint bunnyPrice = helper.tokenPriceInBNB(address(stakingToken));
uint flipPrice = helper.tvlInBNB(address(rewardsToken), 1e18);
_usd = 0;
_bunny = 0;
_bnb = rewardPerTokenPerSecond.mul(365 days).mul(flipPrice).div(bunnyPrice);
}
function apy() override public view returns(uint _usd, uint _bunny, uint _bnb) {
uint tokenDecimals = 1e18;
uint __totalSupply = _totalSupply;
if (__totalSupply == 0) {
__totalSupply = tokenDecimals;
}
uint rewardPerTokenPerSecond = rewardRate.mul(tokenDecimals).div(__totalSupply);
uint bunnyPrice = helper.tokenPriceInBNB(address(stakingToken));
uint flipPrice = helper.tvlInBNB(address(rewardsToken), 1e18);
_usd = 0;
_bunny = 0;
_bnb = rewardPerTokenPerSecond.mul(365 days).mul(flipPrice).div(bunnyPrice);
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)
);
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
function _deposit(uint256 amount, address _to) private nonReentrant notPaused updateReward(_to) {
require(amount > 0, "amount");
_totalSupply = _totalSupply.add(amount);
_balances[_to] = _balances[_to].add(amount);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(_to, amount);
}
function deposit(uint256 amount) override public {
_deposit(amount, msg.sender);
}
function depositAll() override external {
deposit(stakingToken.balanceOf(msg.sender));
}
function withdraw(uint256 amount) override public nonReentrant updateReward(msg.sender) {
require(amount > 0, "amount");
require(amount <= withdrawableBalanceOf(msg.sender), "locked");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
function withdrawAll() override external {
uint _withdraw = withdrawableBalanceOf(msg.sender);
if (_withdraw > 0) {
withdraw(_withdraw);
}
getReward();
}
function withdrawAll() override external {
uint _withdraw = withdrawableBalanceOf(msg.sender);
if (_withdraw > 0) {
withdraw(_withdraw);
}
getReward();
}
function getReward() override public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
reward = _flipToWBNB(reward);
IBEP20(ROUTER.WETH()).safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function getReward() override public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
reward = _flipToWBNB(reward);
IBEP20(ROUTER.WETH()).safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function _flipToWBNB(uint amount) private returns(uint reward) {
address wbnb = ROUTER.WETH();
(uint rewardBunny,) = ROUTER.removeLiquidity(
address(stakingToken), wbnb,
amount, 0, 0, address(this), block.timestamp);
address[] memory path = new address[](2);
path[0] = address(stakingToken);
path[1] = wbnb;
ROUTER.swapExactTokensForTokens(rewardBunny, 0, path, address(this), block.timestamp);
reward = IBEP20(wbnb).balanceOf(address(this));
}
function harvest() override external {}
function info(address account) override external view returns(UserInfo memory) {
UserInfo memory userInfo;
userInfo.balance = _balances[account];
userInfo.principal = _balances[account];
userInfo.available = withdrawableBalanceOf(account);
Profit memory profit;
(uint usd, uint bunny, uint bnb) = profitOf(account);
profit.usd = usd;
profit.bunny = bunny;
profit.bnb = bnb;
userInfo.profit = profit;
userInfo.poolTVL = tvl();
APY memory poolAPY;
(usd, bunny, bnb) = apy();
poolAPY.usd = usd;
poolAPY.bunny = bunny;
poolAPY.bnb = bnb;
userInfo.poolAPY = poolAPY;
return userInfo;
}
function setRewardsToken(address _rewardsToken) external onlyOwner {
require(address(rewardsToken) == address(0), "set rewards token already");
rewardsToken = IBEP20(_rewardsToken);
IBEP20(_rewardsToken).safeApprove(address(ROUTER), uint(~0));
}
function setHelper(IStrategyHelper _helper) external onlyOwner {
require(address(_helper) != address(0), "zero address");
helper = _helper;
}
function setStakePermission(address _address, bool permission) external onlyOwner {
_stakePermission[_address] = permission;
}
function stakeTo(uint256 amount, address _to) external canStakeTo {
_deposit(amount, _to);
if (msg.sender == presaleContract) {
_presaleBalance[_to] = _presaleBalance[_to].add(amount);
}
}
function stakeTo(uint256 amount, address _to) external canStakeTo {
_deposit(amount, _to);
if (msg.sender == presaleContract) {
_presaleBalance[_to] = _presaleBalance[_to].add(amount);
}
}
function notifyRewardAmount(uint256 reward) override external onlyRewardsDistribution updateReward(address(0)) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
require(rewardRate <= _balance.div(rewardsDuration), "reward");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
function notifyRewardAmount(uint256 reward) override external onlyRewardsDistribution updateReward(address(0)) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
require(rewardRate <= _balance.div(rewardsDuration), "reward");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
} else {
uint _balance = rewardsToken.balanceOf(address(this));
function recoverBEP20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
require(tokenAddress != address(stakingToken) && tokenAddress != address(rewardsToken), "tokenAddress");
IBEP20(tokenAddress).safeTransfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
require(periodFinish == 0 || block.timestamp > periodFinish, "period");
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
modifier canStakeTo() {
require(_stakePermission[msg.sender], 'auth');
_;
}
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
} | 11,449,185 | [
1,
45,
5948,
52,
3462,
1071,
5381,
384,
6159,
1345,
273,
467,
5948,
52,
3462,
12,
20,
14626,
29,
5193,
29,
41,
26,
8313,
38,
21609,
72,
6840,
29534,
73,
41,
23,
41,
5026,
449,
22,
40,
21,
13459,
8148,
41,
37,
2499,
69,
10593,
1769,
565,
324,
318,
18538,
1758,
3238,
5381,
4075,
5349,
8924,
273,
374,
92,
1105,
3461,
3461,
73,
22,
69,
3028,
71,
28,
74,
28,
41,
70,
38,
74,
7616,
73,
40,
9462,
952,
11035,
72,
952,
70,
37,
9452,
15259,
8642,
31,
467,
4525,
2276,
1071,
4222,
273,
467,
4525,
2276,
12,
20,
21703,
5193,
71,
5908,
39,
21,
69,
22,
71,
42,
7616,
2643,
23508,
41,
74,
26,
5034,
11149,
38,
24,
5540,
5520,
28,
70,
10580,
37,
21,
69,
20,
1769,
2971,
19292,
911,
8259,
3103,
3238,
5381,
534,
5069,
654,
273,
2971,
19292,
911,
8259,
3103,
12,
20,
92,
6260,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
605,
318,
18538,
2864,
353,
467,
4525,
12235,
16,
534,
359,
14727,
9003,
18241,
16,
868,
8230,
12514,
16709,
16,
21800,
16665,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
5948,
52,
3462,
364,
467,
5948,
52,
3462,
31,
203,
203,
203,
565,
467,
5948,
52,
3462,
1071,
384,
6159,
1345,
31,
203,
565,
2254,
5034,
1071,
3879,
11641,
273,
374,
31,
203,
565,
2254,
5034,
1071,
19890,
4727,
273,
374,
31,
203,
565,
2254,
5034,
1071,
283,
6397,
5326,
273,
8566,
4681,
31,
203,
565,
2254,
5034,
1071,
1142,
1891,
950,
31,
203,
565,
2254,
5034,
1071,
19890,
2173,
1345,
18005,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
729,
17631,
1060,
2173,
1345,
16507,
350,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
283,
6397,
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,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
334,
911,
5041,
31,
203,
203,
565,
1758,
3238,
5381,
8363,
1887,
273,
374,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
31,
203,
565,
1758,
1071,
225,
4075,
5349,
8924,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
12202,
5349,
13937,
31,
203,
565,
2254,
3238,
5381,
2858,
22,
14910,
4436,
12236,
5349,
24980,
273,
25430,
2539,
28,
4313,
713,
397,
261,
22,
7507,
1769,
203,
565,
2254,
3238,
2
] |
pragma solidity ^0.4.18;
interface token {
function transfer(address _to, uint256 _value) external;
function transferFrom (address _from,address _to, uint256 _value) external returns (bool success);
}
contract Owner{
address public owner;
address public limitedAccesser;
bool paused;
constructor() public{
owner = msg.sender;
paused = false;
}
modifier onlyOwner(){
require(owner == msg.sender);
_;
}
modifier onlyLimitedAccesser(){
require(limitedAccesser == msg.sender);
_;
}
function setAccesser(address newAccesser) external onlyOwner{
limitedAccesser = newAccesser;
}
modifier whenNotPaused(){
require(!paused);
_;
}
modifier whenPaused(){
require(paused);
_;
}
/*disable contract setting funciton*/
function pause() external onlyOwner whenNotPaused {
paused = true;
}
/*enable contract setting funciton*/
function unpause() public onlyOwner whenPaused {
paused = false;
}
}
library SafeMath{
function add256(uint256 addend, uint256 augend) internal pure returns(uint256 result){
uint256 sum = addend + augend;
assert(sum >= addend);
return sum;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
}
contract TrinityContractData is Owner{
/*
* Define public data interface
* Mytoken: ERC20 standard token contract address
* trinityData: story channel status and balance, support multiple channel;
*/
using SafeMath for uint256;
uint8 constant INIT = 0;
uint8 constant OPEING = 1;
uint8 constant CLOSING = 2;
uint8 constant LOCKING = 3;
struct ChannelData{
address channelCloser; /* closer address that closed channel first */
address channelSettler;
address partner1;
address partner2;
uint256 channelTotalBalance; /*total balance that both participators deposit together*/
uint256 closingNonce; /* transaction nonce that channel closer */
uint256 expectedSettleBlock; /* the closing time for final settlement for RSMC */
uint256 closerSettleBalance; /* the balance that closer want to withdraw */
uint256 partnerSettleBalance; /* the balance that closer provided for partner can withdraw */
uint8 channelStatus; /* channel current status */
bool channelExist;
mapping(bytes32 => address) timeLockVerifier;
mapping(bytes32 => address) timeLockWithdrawer;
mapping(bytes32 => uint256) lockAmount;
mapping(bytes32 => uint256) lockTime;
mapping(bytes32 => bool) withdrawn_locks;
}
struct Data {
mapping(bytes32 => ChannelData)channelInfo;
uint256 channelNumber;
uint256 settleTimeout;
uint256 htlcSettlePeriod;
}
token public Mytoken;
Data public trinityData;
event SetToken(address tokenValue);
// constructor function
constructor(address _tokenAddress, uint256 _settelPeriod, uint256 _htlcSettlePeriod) payable public {
Mytoken = token(_tokenAddress);
trinityData.settleTimeout = _settelPeriod;
trinityData.htlcSettlePeriod = _htlcSettlePeriod;
}
function getChannelCount() external view returns (uint256){
return trinityData.channelNumber;
}
function getChannelStatus(bytes32 channelId) external view returns(uint8){
ChannelData memory channelInfo = trinityData.channelInfo[channelId];
return uint8(channelInfo.channelStatus);
}
function getChannelExist(bytes32 channelId) external view returns(bool){
ChannelData memory channelInfo = trinityData.channelInfo[channelId];
return channelInfo.channelExist;
}
function getChannelBalance(bytes32 channelId) external view returns (uint256){
ChannelData memory channelInfo = trinityData.channelInfo[channelId];
return channelInfo.channelTotalBalance;
}
function getChannelClosingSettler(bytes32 channelId) external view returns (address){
ChannelData memory channelInfo = trinityData.channelInfo[channelId];
return channelInfo.channelSettler;
}
function getClosingSettle(bytes32 channelId)external view returns (uint256,uint256,address,address,uint256,uint256){
ChannelData memory channelInfo = trinityData.channelInfo[channelId];
return(channelInfo.closingNonce,
channelInfo.expectedSettleBlock,
channelInfo.channelCloser,
channelInfo.channelSettler,
channelInfo.closerSettleBalance,
channelInfo.partnerSettleBalance);
}
function getTimeLock(bytes32 channelId, bytes32 lockHash) external view returns(address,address,uint256,uint256,bool){
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
return(channelInfo.timeLockVerifier[lockHash],
channelInfo.timeLockWithdrawer[lockHash],
channelInfo.lockAmount[lockHash],
channelInfo.lockTime[lockHash],
channelInfo.withdrawn_locks[lockHash]);
}
function getSettlingTimeoutBlock(bytes32 channelId) external view returns(uint256){
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
return(channelInfo.expectedSettleBlock);
}
function getHtlcPaymentBlock(bytes32 channelId, bytes32 lockHash) external view returns(uint256){
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
return(channelInfo.lockTime[lockHash]);
}
function getChannelPartners(bytes32 channelId) external view returns (address,address){
ChannelData memory channelInfo = trinityData.channelInfo[channelId];
return(channelInfo.partner1, channelInfo.partner2);
}
function getChannelById(bytes32 channelId)
external
view
returns(address channelCloser,
address channelSettler,
address partner1,
address partner2,
uint256 channelTotalBalance,
uint256 closingNonce,
uint256 expectedSettleBlock,
uint256 closerSettleBalance,
uint256 partnerSettleBalance,
uint8 channelStatus){
ChannelData memory channelInfo = trinityData.channelInfo[channelId];
channelCloser = channelInfo.channelCloser;
channelSettler = channelInfo.channelSettler;
partner1 = channelInfo.partner1;
partner2 = channelInfo.partner2;
channelTotalBalance = channelInfo.channelTotalBalance;
closingNonce = channelInfo.closingNonce;
expectedSettleBlock = channelInfo.expectedSettleBlock;
closerSettleBalance = channelInfo.closerSettleBalance;
partnerSettleBalance = channelInfo.partnerSettleBalance;
channelStatus = channelInfo.channelStatus;
}
/*
* Function: Set settle timeout value by contract owner only
*/
function setSettleTimeout(uint256 blockNumber) external onlyOwner{
trinityData.settleTimeout = blockNumber;
}
function setHtlcSettlePeriod(uint256 blockNumber) external onlyOwner{
trinityData.htlcSettlePeriod = blockNumber;
}
/*
* Function: Set asset token address by contract owner only
*/
function setToken(address tokenAddress) external onlyOwner{
Mytoken=token(tokenAddress);
}
function createChannel(bytes32 channelId,
address funderAddress,
uint256 funderAmount,
address partnerAddress,
uint256 partnerAmount) public onlyLimitedAccesser{
uint256 totalBalance = funderAmount.add256(partnerAmount);
trinityData.channelInfo[channelId] = ChannelData(address(0),
address(0),
funderAddress,
partnerAddress,
totalBalance,
0,
0,
0,
0,
OPEING,
true);
trinityData.channelNumber = (trinityData.channelNumber).add256(1);
}
/*
* Function: 1. Lock both participants assets to the contract
* 2. setup channel.
* Before lock assets,both participants must approve contract can spend special amout assets.
* Parameters:
* partnerA: partner that deployed on same channel;
* partnerB: partner that deployed on same channel;
* amountA : partnerA will lock assets amount;
* amountB : partnerB will lock assets amount;
* signedStringA: partnerA signature for this transaction;
* signedStringB: partnerB signature for this transaction;
* Return:
* Null;
*/
function depositData(bytes32 channelId,
address funderAddress,
uint256 funderAmount,
address partnerAddress,
uint256 partnerAmount) payable external {
//transfer both special assets to this contract.
require(Mytoken.transferFrom(funderAddress,this,funderAmount) == true, "deposit from funder");
require(Mytoken.transferFrom(partnerAddress,this,partnerAmount) == true, "deposit from partner");
createChannel(channelId,funderAddress,funderAmount,partnerAddress,partnerAmount);
}
function updateDeposit(bytes32 channelId,
address funderAddress,
uint256 funderAmount,
address partnerAddress,
uint256 partnerAmount) payable external onlyLimitedAccesser{
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
require(Mytoken.transferFrom(funderAddress,this,funderAmount) == true, "deposit from funder");
require(Mytoken.transferFrom(partnerAddress,this,partnerAmount) == true, "deposit from partner");
uint256 detlaBalance = funderAmount.add256(partnerAmount);
channelInfo.channelTotalBalance = detlaBalance.add256(channelInfo.channelTotalBalance);
}
function quickCloseChannel(bytes32 channelId,
address closer,
uint256 closerBalance,
address partner,
uint256 partnerBalance) payable external onlyLimitedAccesser{
Mytoken.transfer(closer, closerBalance);
Mytoken.transfer(partner, partnerBalance);
trinityData.channelNumber = (trinityData.channelNumber).sub256(1);
delete trinityData.channelInfo[channelId];
}
function closeChannel(bytes32 channelId,
uint256 nonce,
address closer,
uint256 closeBalance,
address partner,
uint256 partnerBalance) external onlyLimitedAccesser {
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
channelInfo.channelStatus = CLOSING;
channelInfo.channelCloser = closer;
channelInfo.closingNonce = nonce;
channelInfo.closerSettleBalance = closeBalance;
channelInfo.partnerSettleBalance = partnerBalance;
channelInfo.channelSettler = partner;
channelInfo.expectedSettleBlock = (block.number).add256(trinityData.settleTimeout);
}
function closingSettle(bytes32 channelId,
address partnerA,
uint256 updateBalanceA,
address partnerB,
uint256 updateBalanceB) payable external onlyLimitedAccesser{
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
channelInfo.channelStatus = INIT;
// settle period have over and partner didn't provide final transaction information, contract will withdraw closer assets
Mytoken.transfer(partnerA, updateBalanceA);
Mytoken.transfer(partnerB, updateBalanceB);
// delete channel
delete trinityData.channelInfo[channelId];
trinityData.channelNumber = (trinityData.channelNumber).sub256(1);
}
function withdrawLocks(bytes32 channelId,
bytes32 lockHash,
uint256 amount,
address verifier,
address withdrawer) external onlyLimitedAccesser{
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
channelInfo.lockAmount[lockHash] = amount;
channelInfo.lockTime[lockHash] = (block.number).add256(trinityData.htlcSettlePeriod);
channelInfo.timeLockVerifier[lockHash] = verifier;
channelInfo.timeLockWithdrawer[lockHash] = withdrawer;
channelInfo.withdrawn_locks[lockHash] = true;
}
function withdrawSettle(bytes32 channelId,
address receiver,
uint256 lockAmount,
uint256 totalBalance,
bytes32 lockHash) external onlyLimitedAccesser{
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
Mytoken.transfer(receiver, lockAmount);
channelInfo.channelTotalBalance = totalBalance;
channelInfo.timeLockVerifier[lockHash] = address(0);
channelInfo.timeLockWithdrawer[lockHash] = address(0);
channelInfo.lockAmount[lockHash] = 0;
channelInfo.lockTime[lockHash] = 0;
if(0 == totalBalance){
// delete channel
delete trinityData.channelInfo[channelId];
trinityData.channelNumber = (trinityData.channelNumber).sub256(1);
}
}
function withdrawBalance(bytes32 channelId,
address partnerA,
uint256 partnerABalance,
address partnerB,
uint256 partnerBBalance) payable external onlyLimitedAccesser{
uint256 updatedBalance = partnerABalance.add256(partnerBBalance);
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
channelInfo.channelTotalBalance = (channelInfo.channelTotalBalance).sub256(updatedBalance);
Mytoken.transfer(partnerA, partnerABalance);
Mytoken.transfer(partnerB, partnerBBalance);
}
function withdrawForPartner(bytes32 channelId,
address partner,
uint256 balance) payable external onlyLimitedAccesser{
ChannelData storage channelInfo = trinityData.channelInfo[channelId];
channelInfo.channelTotalBalance = channelInfo.channelTotalBalance.sub256(balance);
Mytoken.transfer(partner, balance);
}
function deleteChannel(bytes32 channelId) external onlyLimitedAccesser{
delete trinityData.channelInfo[channelId];
trinityData.channelNumber = (trinityData.channelNumber).sub256(1);
}
function () public { revert(); }
} | enable contract setting funciton*/ | function unpause() public onlyOwner whenPaused {
paused = false;
}
| 13,046,381 | [
1,
7589,
6835,
3637,
1326,
26949,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
640,
19476,
1435,
1071,
1338,
5541,
1347,
28590,
288,
203,
3639,
17781,
273,
629,
31,
203,
565,
289,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-28
*/
pragma solidity ^0.8.9;
// SPDX-License-Identifier: NONE
//
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (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);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
//
// OpenZeppelin Contracts v4.4.1 (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);
}
}
//
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.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 ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.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);
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.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 {}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
/**
* @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);
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
/**
* @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;
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
/**
* @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);
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/Arrays.sol)
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Snapshot.sol)
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it
* return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this
* function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
*
* Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient
* alternative consider {ERC20Votes}.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping(address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _getCurrentSnapshotId();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Get the current snapshotId
*/
function _getCurrentSnapshotId() internal view virtual returns (uint256) {
return _currentSnapshotId.current();
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view virtual returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// Update balance and/or total supply snapshots before the values are modified. This is implemented
// in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// mint
_updateAccountSnapshot(to);
_updateTotalSupplySnapshot();
} else if (to == address(0)) {
// burn
_updateAccountSnapshot(from);
_updateTotalSupplySnapshot();
} else {
// transfer
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
}
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) {
require(snapshotId > 0, "ERC20Snapshot: id is 0");
require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _getCurrentSnapshotId();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
//
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [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);
}
}
}
}
//
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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");
}
}
}
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;
}
//
// QuickFarm V1
// CREATED FOR MUSK GOLD BY QUICKFARM
contract MuskGoldFarmV1 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////
// USER DEPOSIT DEFINITION
//////////////////////////////////////////
struct UserDeposit {
uint256 balance; // THE DEPOSITED NUMBER OF TOKENS BY THE USER
uint256 unlockTime; // TIME WHEN THE USER CAN WITHDRAW FUNDS (BASED ON EPOCH)
uint256 lastPayout; // BLOCK NUMBER OF THE LAST PAYOUT FOR THIS USER IN THIS POOL
uint256 totalEarned; // TOTAL NUMBER OF TOKENS THIS USER HAS EARNED
}
//////////////////////////////////////////
// REWARD POOL DEFINITION
//////////////////////////////////////////
struct RewardPool {
IERC20 depositToken; // ADDRESS OF DEPOSITED TOKEN CONTRACT
bool active; // DETERMINES WHETHER OR NOT THIS POOL IS USABLE
bool hidden; // FLAG FOR WHETHER UI SHOULD RENDER THIS
bool uniV2Lp; // SIGNIFIES A IUNISWAPV2PAIR
bool selfStake; // SIGNIFIES IF THIS IS A 'SINGLE SIDED' SELF STAKE
bytes32 lpOrigin; // ORIGIN OF LP TOKEN BEING DEPOSITED E.G. SUSHI, UNISWAP, PANCAKE - NULL IF NOT N LP TOKEN
uint256 lockSeconds; // HOW LONG UNTIL AN LP DEPOSIT CAN BE REMOVED IN SECONDS
bool lockEnforced; // DETERMINES WHETER TIME LOCKS ARE ENFORCED
uint256 rewardPerBlock; // HOW MANY TOKENS TO REWARD PER BLOCK FOR THIS POOL
bytes32 label; // TEXT LABEL STRICTLY FOR READABILITY AND RENDERING
bytes32 order; // DISPLAY/PRESENTATION ORDER OF THE POOL
uint256 depositSum; // SUM OF ALL DEPOSITED TOKENS IN THIS POOL
}
//////////////////////////////////////////
// USER FARM STATE DEFINITION
//////////////////////////////////////////
struct UserFarmState {
RewardPool[] pools; // REWARD POOLS
uint256[] balance; // DEPOSITS BY POOL
uint256[] unlockTime; // UNLOCK TIME FOR EACH POOL DEPOSIT
uint256[] pending; // PENDING REWARDS BY POOL
uint256[] earnings; // EARNINGS BY POOL
uint256[] depTknBal; // USER BALANCE OF DEPOSIT TOKEN
uint256[] depTknSupply; // TOTAL SUPPLY OF DEPOSIT TOKEN
uint256[] reserve0; // RESERVE0 AMOUNT FOR LP TKN0
uint256[] reserve1; // RESERVE1 AMOUNT FOR LP TKN1
address[] token0; // ADDRESS OF LP TOKEN 0
address[] token1; // ADDRESS OF LP TOKEN 1
uint256 rewardTknBal; // CURRENT USER HOLDINGS OF THE REWARD TOKEN
uint256 pendingAllPools; // REWARDS PENDING FOR ALL POOLS
uint256 earningsAllPools; // REWARDS EARNED FOR ALL POOLS
}
//////////////////////////////////////////
// INIT CLASS VARIABLES
//////////////////////////////////////////
bytes32 public name; // POOL NAME, FOR DISPLAY ON BLOCK EXPLORER
IERC20 public rewardToken; // ADDRESS OF THE ERC20 REWARD TOKEN
address public rewardWallet; // WALLE THAT REWARD TOKENS ARE DRAWN FROM
uint256 public earliestRewards; // EARLIEST BLOCK REWARDS CAN BE GENERATED FROM (FOR FAIR LAUNCH)
uint256 public paidOut = 0; // TOTAL AMOUNT OF REWARDS THAT HAVE BEEN PAID OUT
RewardPool[] public rewardPools; // INFO OF EACH POOL
address[] public depositAddresses; // LIST OF ADDRESSES THAT CURRENTLY HAVE FUNDS DEPOSITED
mapping(uint256 => mapping(address => UserDeposit)) public userDeposits; // INFO OF EACH USER THAT STAKES LP TOKENS
//////////////////////////////////////////
// EVENTS
//////////////////////////////////////////
event Deposit(
address indexed from,
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Reward(address indexed user, uint256 indexed pid, uint256 amount);
event Restake(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
//////////////////////////////////////////
// CONSTRUCTOR
//////////////////////////////////////////
constructor(
IERC20 _rewardToken,
address _rewardWallet,
uint256 _earliestRewards
) {
name = "Musk Gold Farm";
rewardToken = _rewardToken;
rewardWallet = _rewardWallet;
earliestRewards = _earliestRewards;
}
//////////////////////////////////////////
// FARM FUNDING CONTROLS
//////////////////////////////////////////
// SETS ADDRESS THAT REWARDS ARE TO BE PAID FROM
function setRewardWallet(address _source) external onlyOwner {
rewardWallet = _source;
}
// FUND THE FARM (JUST DEPOSITS FUNDS INTO THE REWARD WALLET)
function fund(uint256 _amount) external {
require(msg.sender != rewardWallet, "Sender is reward wallet");
rewardToken.safeTransferFrom(
address(msg.sender),
rewardWallet,
_amount
);
}
//////////////////////////////////////////
// POOL CONTROLS
//////////////////////////////////////////
// ADD LP TOKEN REWARD POOL
function addPool(
IERC20 _depositToken,
bool _active,
bool _hidden,
bool _uniV2Lp,
bytes32 _lpOrigin,
uint256 _lockSeconds,
bool _lockEnforced,
uint256 _rewardPerBlock,
bytes32 _label,
bytes32 _order
) external onlyOwner {
// MAKE SURE THIS REWARD POOL FOR TOKEN + LOCK DOESN'T ALREADY EXIST
require(
poolExists(_depositToken, _lockSeconds) == false,
"Reward pool for token already exists"
);
// IF TOKEN BEING DEPOSITED IS THE SAME AS THE REWARD TOKEN MARK IT AS A SELF STAKE (SINGLE SIDED)
bool selfStake = false;
if (_depositToken == rewardToken) {
selfStake = true;
_uniV2Lp = false;
}
rewardPools.push(
RewardPool({
depositToken: _depositToken,
active: _active,
hidden: _hidden,
uniV2Lp: _uniV2Lp,
selfStake: selfStake, // MARKS IF A "SINGLED SIDED" STAKE OF THE REWARD TOKEN
lpOrigin: _lpOrigin,
lockSeconds: _lockSeconds,
lockEnforced: _lockEnforced,
rewardPerBlock: _rewardPerBlock,
label: _label,
order: _order,
depositSum: 0
})
);
}
function setPool(
// MODIFY AN EXISTING POOL
uint256 _pid,
bool _active,
bool _hidden,
bool _uniV2Lp,
bytes32 _lpOrigin,
uint256 _lockSeconds,
bool _lockEnforced,
uint256 _rewardPerBlock,
bytes32 _label,
bytes32 _order
) external onlyOwner {
rewardPools[_pid].active = _active;
rewardPools[_pid].hidden = _hidden;
rewardPools[_pid].uniV2Lp = _uniV2Lp;
rewardPools[_pid].lpOrigin = _lpOrigin;
rewardPools[_pid].lockSeconds = _lockSeconds;
rewardPools[_pid].lockEnforced = _lockEnforced;
rewardPools[_pid].rewardPerBlock = _rewardPerBlock;
rewardPools[_pid].label = _label;
rewardPools[_pid].order = _order;
}
// PAUSES/RESUMES DEPOSITS FOR ALL POOLS
function setFarmActive(bool _value) public onlyOwner {
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
RewardPool storage pool = rewardPools[pid];
pool.active = _value;
}
}
// SETS THE EARLIEST BLOCK FROM WHICH TO CALCULATE REWARDS
function setEarliestRewards(uint256 _value) external onlyOwner {
require(
_value >= block.number,
"Earliest reward block must be greater than the current block"
);
earliestRewards = _value;
}
//////////////////////////////////////////
// DEPOSIT/WITHDRAW METHODS
//////////////////////////////////////////
// SETS THE "LAST PAYOUT" FOR A USER TO ULTIMATELY DETERMINE HOW MANY REWARDS THEY ARE OWED
function setLastPayout(UserDeposit storage _deposit) private {
_deposit.lastPayout = block.number;
if (_deposit.lastPayout < earliestRewards)
_deposit.lastPayout = earliestRewards; // FAIR LAUNCH ACCOMODATION
}
// DEPOSIT TOKENS (LP OR SIMPLE ERC20) FOR A GIVEN TARGET (USER) WALLET
function deposit(
uint256 _pid,
address _user,
uint256 _amount
) public nonReentrant {
RewardPool storage pool = rewardPools[_pid];
require(_amount > 0, "Amount must be greater than zero");
require(pool.active == true, "This reward pool is inactive");
UserDeposit storage userDeposit = userDeposits[_pid][_user];
// SET INITIAL LAST PAYOUT
if (userDeposit.lastPayout == 0) {
userDeposit.lastPayout = block.number;
if (userDeposit.lastPayout < earliestRewards)
userDeposit.lastPayout = earliestRewards; // FAIR LAUNCH ACCOMODATION
}
// COLLECT REWARD ONLY IF ADDRESS DEPOSITING IS THE OWNER OF THE DEPOSIT
if (userDeposit.balance > 0 && msg.sender == _user) {
payReward(_pid, _user);
}
pool.depositToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
); // DO THE ACTUAL DEPOSIT
userDeposit.balance = userDeposit.balance.add(_amount); // ADD THE TRANSFERRED AMOUNT TO THE DEPOSIT VALUE
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // UPDATE THE UNLOCK TIME
pool.depositSum = pool.depositSum.add(_amount); // KEEP TRACK OF TOTAL DEPOSITS IN THE POOL
recordAddress(_user); // RECORD THE USER ADDRESS IN THE LIST
emit Deposit(msg.sender, _user, _pid, _amount);
}
// PRIVATE METHOD TO PAY OUT USER REWARDS
function payReward(uint256 _pid, address _user) private {
UserDeposit storage userDeposit = userDeposits[_pid][_user]; // FETCH THE DEPOSIT
uint256 rewardsDue = userPendingPool(_pid, _user); // GET PENDING REWARDS
if (rewardsDue <= 0) return; // BAIL OUT IF NO REWARD IS DUE
rewardToken.transferFrom(rewardWallet, _user, rewardsDue);
emit Reward(_user, _pid, rewardsDue);
userDeposit.totalEarned = userDeposit.totalEarned.add(rewardsDue); // ADD THE PAYOUT AMOUNT TO TOTAL EARNINGS
paidOut = paidOut.add(rewardsDue); // ADD AMOUNT TO TOTAL PAIDOUT FOR THE WHOLE FARM
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
}
// EXTERNAL METHOD FOR USER'S TO COLLECT REWARDS
function collectReward(uint256 _pid) external nonReentrant {
payReward(_pid, msg.sender);
}
// RESTAKE REWARDS INTO SINGLE-SIDED POOLS
function restake(uint256 _pid) external nonReentrant {
RewardPool storage pool = rewardPools[_pid]; // GET THE POOL
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; // FETCH THE DEPOSIT
require(
pool.depositToken == rewardToken,
"Restake is only available on single-sided staking"
);
uint256 rewardsDue = userPendingPool(_pid, msg.sender); // GET PENDING REWARD AMOUNT
if (rewardsDue <= 0) return; // BAIL OUT IF NO REWARDS ARE TO BE PAID
pool.depositToken.safeTransferFrom(
rewardWallet,
address(this),
rewardsDue
); // MOVE FUNDS FROM THE REWARDS TO THIS CONTRACT
pool.depositSum = pool.depositSum.add(rewardsDue);
userDeposit.balance = userDeposit.balance.add(rewardsDue); // ADD THE FUNDS MOVED TO THE USER'S BALANCE
userDeposit.totalEarned = userDeposit.totalEarned.add(rewardsDue); // ADD FUNDS MOVED TO USER'S TOTAL EARNINGS FOR POOL
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
paidOut = paidOut.add(rewardsDue); // ADD TO THE TOTAL PAID OUT FOR THE FARM
emit Restake(msg.sender, _pid, rewardsDue);
}
// WITHDRAW LP TOKENS FROM FARM.
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant {
RewardPool storage pool = rewardPools[_pid];
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender];
if (pool.lockEnforced)
require(
userDeposit.unlockTime <= block.timestamp,
"withdraw: time lock has not passed"
);
require(
userDeposit.balance >= _amount,
"withdraw: can't withdraw more than deposit"
);
payReward(_pid, msg.sender); // PAY OUT ANY REWARDS ACCUMULATED UP TO THIS POINT
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // RESET THE UNLOCK TIME
userDeposit.balance = userDeposit.balance.sub(_amount); // SUBTRACT THE AMOUNT DEBITED FROM THE BALANCE
pool.depositToken.safeTransfer(address(msg.sender), _amount); // TRANSFER THE WITHDRAWN AMOUNT BACK TO THE USER
emit Withdraw(msg.sender, _pid, _amount);
pool.depositSum = pool.depositSum.sub(_amount); // SUBTRACT THE WITHDRAWN AMOUNT FROM THE POOL DEPOSIT TOTAL
cleanupAddress(msg.sender);
}
// APPEND ADDRESSES THAT HAVE FUNDS DEPOSITED FOR EASY RETRIEVAL
function recordAddress(address _address) private {
for (uint256 i = 0; i < depositAddresses.length; i++) {
address curAddress = depositAddresses[i];
if (_address == curAddress) return;
}
depositAddresses.push(_address);
}
// CLEAN ANY ADDRESSES THAT DON'T HAVE ACTIVE DEPOSITS
function cleanupAddress(address _address) private {
// CHECK TO SEE IF THE ADDRESS HAS ANY DEPOSITS
uint256 deposits = 0;
for (uint256 pid = 0; pid < rewardPools.length; pid++) {
deposits = deposits.add(userDeposits[pid][_address].balance);
}
if (deposits > 0) return; // BAIL OUT IF USER STILL HAS DEPOSITS
for (uint256 i = 0; i < depositAddresses.length; i++) {
address curAddress = depositAddresses[i];
if (_address == curAddress) delete depositAddresses[i]; // REMOVE ADDRESS FROM ARRAY
}
}
//////////////////////////////////////////
// INFORMATION METHODS
//////////////////////////////////////////
// RETURNS THE ARRAY OF POOLS
function getPools() public view returns (RewardPool[] memory) {
return rewardPools;
}
// RETURNS REWARD TOKENS REMAINING
function rewardsRemaining() public view returns (uint256) {
return rewardToken.balanceOf(rewardWallet);
}
// RETURNS COUNT OF ADDRESSES WITH DEPOSITS
function addressCount() external view returns (uint256) {
return depositAddresses.length;
}
// CHECK IF A GIVEN DEPOSIT TOKEN + TIMELOCK COMBINATION ALREADY EXISTS
function poolExists(IERC20 _depositToken, uint256 _lockSeconds)
private
view
returns (bool)
{
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
RewardPool storage pool = rewardPools[pid];
if (
pool.depositToken == _depositToken &&
pool.lockSeconds == _lockSeconds
) return true;
}
return false;
}
// RETURNS COUNT OF LP POOLS
function poolLength() external view returns (uint256) {
return rewardPools.length;
}
// RETURNS SUM OF DEPOSITS IN X POOL
function poolDepositSum(uint256 _pid) external view returns (uint256) {
return rewardPools[_pid].depositSum;
}
// VIEW FUNCTION TO SEE PENDING REWARDS FOR A USER
function userPendingPool(uint256 _pid, address _user)
public
view
returns (uint256)
{
RewardPool storage pool = rewardPools[_pid];
UserDeposit storage userDeposit = userDeposits[_pid][_user];
if (userDeposit.balance == 0) return 0;
if (earliestRewards > block.number) return 0;
uint256 precision = 1e36;
uint256 blocksElapsed = 0;
if (block.number > userDeposit.lastPayout)
blocksElapsed = block.number.sub(userDeposit.lastPayout);
uint256 poolOwnership = userDeposit.balance.mul(precision).div(
pool.depositSum
);
uint256 rewardsDue = blocksElapsed
.mul(pool.rewardPerBlock)
.mul(poolOwnership)
.div(precision);
return rewardsDue;
}
// GETS PENDING REWARDS FOR A GIVEN USER IN ALL POOLS
function userPendingAll(address _user) public view returns (uint256) {
uint256 totalReward = 0;
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
uint256 pending = userPendingPool(pid, _user);
totalReward = totalReward.add(pending);
}
return totalReward;
}
// RETURNS TOTAL PAID OUT TO A USER FOR A GIVEN POOL
function userEarnedPool(uint256 _pid, address _user)
public
view
returns (uint256)
{
return userDeposits[_pid][_user].totalEarned;
}
// RETURNS USER EARNINGS FOR ALL POOLS
function userEarnedAll(address _user) public view returns (uint256) {
uint256 totalEarned = 0;
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
totalEarned = totalEarned.add(userDeposits[pid][_user].totalEarned);
}
return totalEarned;
}
// VIEW FUNCTION FOR TOTAL REWARDS THE FARM HAS YET TO PAY OUT
function farmTotalPending() external view returns (uint256) {
uint256 pending = 0;
for (uint256 i = 0; i < depositAddresses.length; ++i) {
uint256 userPending = userPendingAll(depositAddresses[i]);
pending = pending.add(userPending);
}
return pending;
}
// RETURNS A GIVEN USER'S STATE IN THE FARM IN A SINGLE CALL
function getUserState(address _user)
external
view
returns (UserFarmState memory)
{
uint256[] memory balance = new uint256[](rewardPools.length);
uint256[] memory pending = new uint256[](rewardPools.length);
uint256[] memory earned = new uint256[](rewardPools.length);
uint256[] memory depTknBal = new uint256[](rewardPools.length);
uint256[] memory depTknSupply = new uint256[](rewardPools.length);
uint256[] memory depTknReserve0 = new uint256[](rewardPools.length);
uint256[] memory depTknReserve1 = new uint256[](rewardPools.length);
address[] memory depTknResTkn0 = new address[](rewardPools.length);
address[] memory depTknResTkn1 = new address[](rewardPools.length);
uint256[] memory unlockTime = new uint256[](rewardPools.length);
for (uint256 pid = 0; pid < rewardPools.length; ++pid) {
balance[pid] = userDeposits[pid][_user].balance;
pending[pid] = userPendingPool(pid, _user);
earned[pid] = userEarnedPool(pid, _user);
depTknBal[pid] = rewardPools[pid].depositToken.balanceOf(_user);
depTknSupply[pid] = rewardPools[pid].depositToken.totalSupply();
unlockTime[pid] = userDeposits[pid][_user].unlockTime;
if (
rewardPools[pid].uniV2Lp == true &&
rewardPools[pid].selfStake == false
) {
IUniswapV2Pair pair = IUniswapV2Pair(
address(rewardPools[pid].depositToken)
);
(uint256 res0, uint256 res1, uint256 timestamp) = pair
.getReserves();
depTknReserve0[pid] = res0;
depTknReserve1[pid] = res1;
depTknResTkn0[pid] = pair.token0();
depTknResTkn1[pid] = pair.token1();
}
}
return
UserFarmState(
rewardPools, // POOLS
balance, // DEPOSITS BY POOL
unlockTime, // UNLOCK TIME FOR EACH DEPOSITED POOL
pending, // PENDING REWARDS BY POOL
earned, // EARNINGS BY POOL
depTknBal, // USER BALANCE OF DEPOSIT TOKEN
depTknSupply, // TOTAL SUPPLY OF DEPOSIT TOKEN
depTknReserve0, // RESERVE0 AMOUNT FOR LP TKN0
depTknReserve1, // RESERVE1 AMOUNT FOR LP TKN1
depTknResTkn0, // ADDRESS OF LP TOKEN 0
depTknResTkn1, // ADDRESS OF LP TOKEN 1
rewardToken.balanceOf(_user), // CURRENT USER HOLDINGS OF THE REWARD TOKEN
userPendingAll(_user), // REWARDS PENDING FOR ALL POOLS
userEarnedAll(_user) // REWARDS EARNED FOR ALL POOLS
);
}
//////////////////////////////////////////
// EMERGENCY CONTROLS
//////////////////////////////////////////
// WITHDRAW WITHOUT CARING ABOUT REWARDS. EMERGENCY ONLY.
// THIS WILL WIPE OUT ANY PENDING REWARDS FOR A USER
function emergencyWithdraw(uint256 _pid) external nonReentrant {
RewardPool storage pool = rewardPools[_pid]; // GET THE POOL
UserDeposit storage userDeposit = userDeposits[_pid][msg.sender]; //GET THE DEPOSIT
pool.depositToken.safeTransfer(
address(msg.sender),
userDeposit.balance
); // TRANSFER THE DEPOSIT BACK TO THE USER
pool.depositSum = pool.depositSum.sub(userDeposit.balance); // DECREMENT THE POOL'S OVERALL DEPOSIT SUM
userDeposit.unlockTime = block.timestamp.add(pool.lockSeconds); // RESET THE UNLOCK TIME
userDeposit.balance = 0; // SET THE BALANCE TO ZERO AFTER WIRTHDRAWAL
setLastPayout(userDeposit); // UPDATE THE LAST PAYOUT
emit EmergencyWithdraw(msg.sender, _pid, userDeposit.balance);
}
} | RETURNS REWARD TOKENS REMAINING | function rewardsRemaining() public view returns (uint256) {
return rewardToken.balanceOf(rewardWallet);
}
| 7,938,620 | [
1,
19392,
3156,
2438,
21343,
14275,
55,
2438,
19803,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
283,
6397,
11429,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
19890,
1345,
18,
12296,
951,
12,
266,
2913,
16936,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
//Interface
import { ITokenERC20 } from "../interfaces/token/ITokenERC20.sol";
// Token
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol";
// Security
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
// Signature utils
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol";
// Meta transactions
import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol";
// Utils
import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import "../lib/CurrencyTransferLib.sol";
import "../lib/FeeType.sol";
// Thirdweb top-level
import "../interfaces/ITWFee.sol";
contract TokenERC20 is
Initializable,
ReentrancyGuardUpgradeable,
ERC2771ContextUpgradeable,
MulticallUpgradeable,
ERC20BurnableUpgradeable,
ERC20PausableUpgradeable,
ERC20VotesUpgradeable,
ITokenERC20,
AccessControlEnumerableUpgradeable
{
using ECDSAUpgradeable for bytes32;
bytes32 private constant MODULE_TYPE = bytes32("TokenERC20");
uint256 private constant VERSION = 1;
bytes32 private constant TYPEHASH =
keccak256(
"MintRequest(address to,address primarySaleRecipient,uint256 quantity,uint256 price,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)"
);
bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 internal constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 internal constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev The thirdweb contract with fee related information.
ITWFee internal immutable thirdwebFee;
/// @dev Returns the URI for the storefront-level metadata of the contract.
string public contractURI;
/// @dev Max bps in the thirdweb system
uint128 internal constant MAX_BPS = 10_000;
/// @dev The % of primary sales collected by the contract as fees.
uint128 internal platformFeeBps;
/// @dev The adress that receives all primary sales value.
address internal platformFeeRecipient;
/// @dev The adress that receives all primary sales value.
address public primarySaleRecipient;
/// @dev Mapping from mint request UID => whether the mint request is processed.
mapping(bytes32 => bool) private minted;
constructor(address _thirdwebFee) initializer {
thirdwebFee = ITWFee(_thirdwebFee);
}
/// @dev Initiliazes the contract, like a constructor.
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _primarySaleRecipient,
address _platformFeeRecipient,
uint256 _platformFeeBps
) external initializer {
__ERC2771Context_init_unchained(_trustedForwarders);
__ERC20Permit_init(_name);
__ERC20_init_unchained(_name, _symbol);
contractURI = _contractURI;
primarySaleRecipient = _primarySaleRecipient;
platformFeeRecipient = _platformFeeRecipient;
platformFeeBps = uint128(_platformFeeBps);
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, _defaultAdmin);
_setupRole(MINTER_ROLE, _defaultAdmin);
_setupRole(PAUSER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, address(0));
}
/// @dev Returns the module type of the contract.
function contractType() external pure virtual returns (bytes32) {
return MODULE_TYPE;
}
/// @dev Returns the version of the contract.
function contractVersion() external pure virtual returns (uint8) {
return uint8(VERSION);
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._afterTokenTransfer(from, to, amount);
}
/// @dev Runs on every transfer.
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) {
require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "transfers restricted.");
}
}
function _mint(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._mint(account, amount);
}
function _burn(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20VotesUpgradeable) {
super._burn(account, amount);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "not minter.");
_mintTo(to, amount);
}
/// @dev Verifies that a mint request is signed by an account holding MINTER_ROLE (at the time of the function call).
function verify(MintRequest calldata _req, bytes calldata _signature) public view returns (bool, address) {
address signer = recoverAddress(_req, _signature);
return (!minted[_req.uid] && hasRole(MINTER_ROLE, signer), signer);
}
/// @dev Mints tokens according to the provided mint request.
function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant {
address signer = verifyRequest(_req, _signature);
address receiver = _req.to == address(0) ? _msgSender() : _req.to;
address saleRecipient = _req.primarySaleRecipient == address(0)
? primarySaleRecipient
: _req.primarySaleRecipient;
collectPrice(saleRecipient, _req.currency, _req.price);
_mintTo(receiver, _req.quantity);
emit TokensMintedWithSignature(signer, receiver, _req);
}
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
primarySaleRecipient = _saleRecipient;
emit PrimarySaleRecipientUpdated(_saleRecipient);
}
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_platformFeeBps <= MAX_BPS, "bps <= 10000.");
platformFeeBps = uint64(_platformFeeBps);
platformFeeRecipient = _platformFeeRecipient;
emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps);
}
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address, uint16) {
return (platformFeeRecipient, uint16(platformFeeBps));
}
/// @dev Collects and distributes the primary sale value of tokens being claimed.
function collectPrice(
address _primarySaleRecipient,
address _currency,
uint256 _price
) internal {
if (_price == 0) {
return;
}
uint256 platformFees = (_price * platformFeeBps) / MAX_BPS;
(address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE);
uint256 twFee = (_price * twFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == _price, "must send total price.");
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee);
CurrencyTransferLib.transferCurrency(
_currency,
_msgSender(),
_primarySaleRecipient,
_price - platformFees - twFee
);
}
/// @dev Mints `amount` of tokens to `to`
function _mintTo(address _to, uint256 _amount) internal {
_mint(_to, _amount);
emit TokensMinted(_to, _amount);
}
/// @dev Verifies that a mint request is valid.
function verifyRequest(MintRequest calldata _req, bytes calldata _signature) internal returns (address) {
(bool success, address signer) = verify(_req, _signature);
require(success, "invalid signature");
require(
_req.validityStartTimestamp <= block.timestamp && _req.validityEndTimestamp >= block.timestamp,
"request expired"
);
minted[_req.uid] = true;
return signer;
}
/// @dev Returns the address of the signer of the mint request.
function recoverAddress(MintRequest calldata _req, bytes calldata _signature) internal view returns (address) {
return _hashTypedDataV4(keccak256(_encodeRequest(_req))).recover(_signature);
}
/// @dev Resolves 'stack too deep' error in `recoverAddress`.
function _encodeRequest(MintRequest calldata _req) internal pure returns (bytes memory) {
return
abi.encode(
TYPEHASH,
_req.to,
_req.primarySaleRecipient,
_req.quantity,
_req.price,
_req.currency,
_req.validityStartTimestamp,
_req.validityEndTimestamp,
_req.uid
);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser.");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "not pauser.");
_unpause();
}
/// @dev Sets contract URI for the storefront-level metadata of the contract.
function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) {
contractURI = _uri;
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../IThirdwebContract.sol";
import "../IThirdwebPlatformFee.sol";
import "../IThirdwebPrimarySale.sol";
interface ITokenERC20 is IThirdwebContract, IThirdwebPrimarySale, IThirdwebPlatformFee, IERC20Upgradeable {
/**
* @notice The body of a request to mint tokens.
*
* @param to The receiver of the tokens to mint.
* @param primarySaleRecipient The receiver of the primary sale funds from the mint.
* @param quantity The quantity of tpkens to mint.
* @param price Price to pay for minting with the signature.
* @param currency The currency in which the price per token must be paid.
* @param validityStartTimestamp The unix timestamp after which the request is valid.
* @param validityEndTimestamp The unix timestamp after which the request expires.
* @param uid A unique identifier for the request.
*/
struct MintRequest {
address to;
address primarySaleRecipient;
uint256 quantity;
uint256 price;
address currency;
uint128 validityStartTimestamp;
uint128 validityEndTimestamp;
bytes32 uid;
}
/// @dev Emitted when an account with MINTER_ROLE mints an NFT.
event TokensMinted(address indexed mintedTo, uint256 quantityMinted);
/// @dev Emitted when tokens are minted.
event TokensMintedWithSignature(address indexed signer, address indexed mintedTo, MintRequest mintRequest);
/// @dev Emitted when a new sale recipient is set.
event PrimarySaleRecipientUpdated(address indexed recipient);
/// @dev Emitted when fee on primary sales is updated.
event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps);
/**
* @notice Verifies that a mint request is signed by an account holding
* MINTER_ROLE (at the time of the function call).
*
* @param req The mint request.
* @param signature The signature produced by an account signing the mint request.
*
* returns (success, signer) Result of verification and the recovered address.
*/
function verify(MintRequest calldata req, bytes calldata signature)
external
view
returns (bool success, address signer);
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) external;
/**
* @notice Mints an NFT according to the provided mint request.
*
* @param req The mint request.
* @param signature he signature produced by an account signing the mint request.
*/
function mintWithSignature(MintRequest calldata req, bytes calldata signature) external payable;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal onlyInitializing {
}
function __ERC20Burnable_init_unchained() internal onlyInitializing {
}
/**
* @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 {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
/**
* @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 (token/ERC20/extensions/ERC20Pausable.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../../../security/PausableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
/**
* @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) (token/ERC20/extensions/ERC20Votes.sol)
pragma solidity ^0.8.0;
import "./draft-ERC20PermitUpgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol";
import "../../../governance/utils/IVotesUpgradeable.sol";
import "../../../utils/math/SafeCastUpgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
*
* _Available since v4.2._
*/
abstract contract ERC20VotesUpgradeable is Initializable, IVotesUpgradeable, ERC20PermitUpgradeable {
function __ERC20Votes_init() internal onlyInitializing {
}
function __ERC20Votes_init_unchained() internal onlyInitializing {
}
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCastUpgradeable.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual override returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view virtual override returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual override {
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSAUpgradeable.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
/**
* @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[47] private __gap;
}
// 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 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/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
/**
* @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.0 (metatx/ERC2771Context.sol)
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
mapping(address => bool) private _trustedForwarder;
function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing {
for (uint256 i = 0; i < trustedForwarder.length; i++) {
_trustedForwarder[trustedForwarder[i]] = true;
}
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return _trustedForwarder[forwarder];
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract MulticallUpgradeable is Initializable {
function __Multicall_init() internal onlyInitializing {
}
function __Multicall_init_unchained() internal onlyInitializing {
}
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = _functionDelegateCall(address(this), data[i]);
}
return results;
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// Helper interfaces
import { IWETH } from "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
library CurrencyTransferLib {
/// @dev The address interpreted as native token of the chain.
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Transfers a given amount of currency.
function transferCurrency(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
safeTransferNativeToken(_to, _amount);
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Transfers a given amount of currency. (With native token wrapping)
function transferCurrencyWithWrapperAndBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount,
address _nativeTokenWrapper
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
// withdraw from weth then transfer withdrawn native token to recipient
IWETH(_nativeTokenWrapper).withdraw(_amount);
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
} else if (_to == address(this)) {
// store native currency in weth
require(_amount == msg.value, "msg.value != amount");
IWETH(_nativeTokenWrapper).deposit{ value: _amount }();
} else {
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
}
} else {
safeTransferERC20WithBalanceCheck(_currency, _from, _to, _amount);
}
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
bool success = _from == address(this)
? IERC20Upgradeable(_currency).transfer(_to, _amount)
: IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount);
require(success, "currency transfer failed.");
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20WithBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
uint256 balBefore = IERC20Upgradeable(_currency).balanceOf(_to);
bool success = _from == address(this)
? IERC20Upgradeable(_currency).transfer(_to, _amount)
: IERC20Upgradeable(_currency).transferFrom(_from, _to, _amount);
uint256 balAfter = IERC20Upgradeable(_currency).balanceOf(_to);
require(success && (balAfter == balBefore + _amount), "currency transfer failed.");
}
/// @dev Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
require(success, "native token transfer failed");
}
/// @dev Transfers `amount` of native token to `to`. (With native token wrapping)
function safeTransferNativeTokenWithWrapper(
address to,
uint256 value,
address _nativeTokenWrapper
) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
if (!success) {
IWETH(_nativeTokenWrapper).deposit{ value: value }();
require(IERC20Upgradeable(_nativeTokenWrapper).transfer(to, value), "transfer failed");
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
library FeeType {
uint256 internal constant PRIMARY_SALE = 0;
uint256 internal constant MARKET_SALE = 1;
uint256 internal constant SPLIT = 2;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface ITWFee {
function getFeeInfo(address _proxy, uint256 _type) external view returns (address recipient, uint256 bps);
}
// 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);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebContract {
/// @dev Returns the module type of the contract.
function contractType() external pure returns (bytes32);
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8);
/// @dev Returns the metadata URI of the contract.
function contractURI() external view returns (string memory);
/**
* @dev Sets contract URI for the storefront-level metadata of the contract.
* Only module admin can call this function.
*/
function setContractURI(string calldata _uri) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPlatformFee {
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address platformFeeRecipient, uint16 platformFeeBps);
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPrimarySale {
/// @dev The adress that receives all primary sales value.
function primarySaleRecipient() external view returns (address);
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_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 {}
/**
* @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[45] private __gap;
}
// 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 (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 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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 (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 (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 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
/**
* @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/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*
* _Available since v4.5._
*/
interface IVotesUpgradeable {
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
*/
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// 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 IERC20PermitUpgradeable {
/**
* @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 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 (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 (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 (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 (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/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: Apache-2.0
pragma solidity ^0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 value) external returns (bool);
} | @dev Transfers a given amount of currency. (With native token wrapping) withdraw from weth then transfer withdrawn native token to recipient store native currency in weth | function transferCurrencyWithWrapperAndBalanceCheck(
address _currency,
address _from,
address _to,
uint256 _amount,
address _nativeTokenWrapper
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
IWETH(_nativeTokenWrapper).withdraw(_amount);
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
require(_amount == msg.value, "msg.value != amount");
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
}
safeTransferERC20WithBalanceCheck(_currency, _from, _to, _amount);
}
}
| 409,583 | [
1,
1429,
18881,
279,
864,
3844,
434,
5462,
18,
261,
1190,
6448,
1147,
14702,
13,
598,
9446,
628,
341,
546,
1508,
7412,
598,
9446,
82,
6448,
1147,
358,
8027,
1707,
6448,
5462,
316,
341,
546,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
565,
445,
7412,
7623,
1190,
3611,
1876,
13937,
1564,
12,
203,
3639,
1758,
389,
7095,
16,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
1758,
389,
13635,
1345,
3611,
203,
565,
262,
2713,
288,
203,
3639,
309,
261,
67,
8949,
422,
374,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
7095,
422,
423,
12992,
67,
8412,
13,
288,
203,
5411,
309,
261,
67,
2080,
422,
1758,
12,
2211,
3719,
288,
203,
7734,
467,
59,
1584,
44,
24899,
13635,
1345,
3611,
2934,
1918,
9446,
24899,
8949,
1769,
203,
7734,
4183,
5912,
9220,
1345,
1190,
3611,
24899,
869,
16,
389,
8949,
16,
389,
13635,
1345,
3611,
1769,
203,
7734,
2583,
24899,
8949,
422,
1234,
18,
1132,
16,
315,
3576,
18,
1132,
480,
3844,
8863,
203,
7734,
4183,
5912,
9220,
1345,
1190,
3611,
24899,
869,
16,
389,
8949,
16,
389,
13635,
1345,
3611,
1769,
203,
5411,
289,
203,
5411,
4183,
5912,
654,
39,
3462,
1190,
13937,
1564,
24899,
7095,
16,
389,
2080,
16,
389,
869,
16,
389,
8949,
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
] |
./partial_match/1/0x8cde0Bc03Dc1c9d35bFaCee75C250eD6f1Cc0E13/sources/Cross.sol | ETH Uniswap Mainnet % Testnet
| router = 0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008; | 4,054,437 | [
1,
1584,
44,
1351,
291,
91,
438,
12740,
2758,
738,
7766,
2758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
4633,
273,
374,
14626,
25,
1578,
69,
5608,
5034,
40,
23,
4331,
9452,
40,
20,
38,
74,
27,
69,
3028,
713,
74,
26897,
4331,
361,
6669,
11290,
713,
28,
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
] |
// SPDX-License-Identifier: GNU General Public License
pragma solidity 0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title An implementation of an online marketplace using Ethereum
/// @author Rodrigo Ortega
/// @notice You can use this contract for actions related to the online marketplace (listing items, buying items, etc.)
contract OnlineMarketplace is Ownable {
event StoreCreated(string newStoreName, address owner, uint storeID);
event StoreUpdated(address indexed seller, uint _storeID, string _name, string _description, string _website, string _email);
event ProductCreated(string newProductName, uint price, uint SKU, uint quantity, uint uniqueID, address seller, uint storeID);
event ProductUpdated(string newProductName, uint price, uint SKU, uint quantity, uint uniqueID, address seller, uint storeID);
event ProductSold(uint orderID, uint indexed productID, address indexed buyer, address indexed seller, uint price, string email);
event ProductShipped(uint orderID, uint productID, uint trackingNumber, address indexed seller, address indexed buyer);
event UserRegistered(address indexed user, string email);
/// @dev incremented by 1 to assign unique IDs to stores and products
uint internal ID;
/// @dev holds contract balance
uint public balance;
/// @notice bool for circuit breaker used in function modifier requireIsActive()
/// @dev value can be toggled using toggleCircuitBreaker() function by contract owner
bool public isActive = true;
/// @dev struct for properties of a store object
struct Stores {
string name;
address owner;
uint storeID;
string description;
string website;
string email;
}
/// @dev struct for properties of a product object
struct Products {
string name;
string description;
uint price;
uint SKU;
uint quantity;
uint uniqueID;
bool shipped;
uint trackingNumber;
address buyer;
address payable seller;
uint storeID;
uint orderID;
}
/// @dev array used for listing all stores on front page of user-interface (store directory)
Stores[] public storesArray;
/// @dev mapping of unique ID to Products
mapping (uint => Products) public productsMapping;
/// @dev mapping of unique ID to Stores
mapping (uint => Stores) public storesMapping;
/// @dev mapping of address to array of Stores owned by address
mapping (address => Stores[]) public stores;
/// @dev mapping of Store ID to array of Products available at that store
mapping (uint => Products[]) public products;
/// @dev mapping of address to string for contact email
mapping (address => string) public emails;
/// @dev mapping of order ID to product sold
mapping (uint => mapping (uint => Products)) public orders;
/// @notice modifier placed in functions for circuit breaker
/// @dev isActive default value is true; toggle using toggleCircuitBreaker()
modifier requireIsActive() {
require(isActive == true);
_;
}
/// @notice function increments ID variable to generate unique IDs
/// @dev increments variable uint ID by 1 to generate unique IDs for products and stores
function getID() public returns (uint) {
return ++ID;
}
/// @notice getter function for array length of Stores array
/// @dev called externally, used for displaying list of all stores in front-end
/// @return length of Stores array
function getArrayLength() external view returns (uint length) {
return storesArray.length;
}
/// @notice getter function for array length of Stores array in mapping (address key)
/// @dev called externally, used for displaying list of stores owned by specific address in front-end
/// @return length of Stores array in mapping (address key)
function getStoresMALength() external view returns (uint) {
return stores[msg.sender].length;
}
/// @notice getter function for array length of Products array in mapping (store ID key)
/// @dev called externally, used for displaying list of products owned by specific store ID in front-end
/// @param _storeID The unique store ID generated by getID() called during creation of newStore
/// @return length of Products array in mapping (store ID key)
function getProductsMALength(uint _storeID) external view returns (uint) {
return products[_storeID].length;
}
/// @notice getter function for Products struct values in mapping (unique ID key) - split into A and B functions
/// @dev used in testing for retrieving values of Products struct by product ID
/// @param _uniqueID The unique product ID generated by getID() called during creation of newProduct
function getProductA (uint _uniqueID) external view returns (string memory name, string memory description, uint price, uint SKU, uint quantity, uint uniqueID) {
return (productsMapping[_uniqueID].name, productsMapping[_uniqueID].description, productsMapping[_uniqueID].price, productsMapping[_uniqueID].SKU, productsMapping[_uniqueID].quantity, productsMapping[_uniqueID].uniqueID);
}
/// @notice getter function for Products struct values in mapping (unique ID key)- split into A and B functions
/// @dev used in testing for retrieving values of Products struct by product ID
/// @param _uniqueID The unique product ID generated by getID() called during creation of newProduct
function getProductB (uint _uniqueID) external view returns (bool shipped, uint trackingNumber, address buyer, address seller, uint storeID, uint orderID) {
return (productsMapping[_uniqueID].shipped, productsMapping[_uniqueID].trackingNumber, productsMapping[_uniqueID].buyer, productsMapping[_uniqueID].seller, productsMapping[_uniqueID].storeID, productsMapping[_uniqueID].orderID);
}
/// @notice getter function for mapping of array of Product structs (store ID key)
/// @dev called externally, used for retrieving products by store ID in front-end
/// @param _storeID The unique store ID
/// @param _index The index value for the location of the Product struct in the array
/// @return name of the product
function getProductsMA(uint _storeID, uint _index) external view returns (string memory) {
return products[_storeID][_index].name;
}
/// @notice getter function for Stores struct in mapping (store ID key)
/// @dev returns Stores struct values from mapping (store ID key) in front-end
/// @param _storeID The unique store ID
/// @return name of the store
function getStore(uint _storeID) external view returns (string memory) {
return storesMapping[_storeID].name;
}
/// @notice getter function for mapping of email addresses (address key)
/// @dev called externally, used for retrieving a person's email address using thee associated Ethereum public address in front-end
/// @param _address The person's Ethereum public address
/// @return email address
function getEmail(address _address) external view returns (string memory email, address buyer) {
return (emails[_address], _address);
}
/// @notice getter function for contract's current balance
/// @dev called externally, used for retrieving contract's current balance in front-end
/// @return current balance of this contract
function getContractBalance() external view returns (uint) {
return address(this).balance;
}
/// @notice function for creating a new store
/// @dev built in circuit-breaker; called externally, used for creating a new Store object
/// @param _name The store's name
/// @param _description The store's description
/// @param _website The store's website
/// @param _email The store's contact email address
function newStore(string calldata _name, string calldata _description, string calldata _website, string calldata _email) external payable requireIsActive {
require (msg.value == .005 ether);
balance += msg.value;
Stores memory a;
a.name = _name;
a.owner = msg.sender;
a.storeID = getID();
a.description = _description;
a.website = _website;
a.email = _email;
insertStore(a, a.storeID);
emit StoreCreated(_name, msg.sender, a.storeID);
}
/// @dev private function, called during previous function to add new Store object to storage variables
function insertStore(Stores memory a, uint _storeID) private {
stores[msg.sender].push(a);
storesMapping[_storeID] = a;
storesArray.push(a);
}
/// @notice function for creating a new product
/// @dev built-in circuit breaker; called externally, used for creating a new Product object
/// @param _name The product's name
/// @param _description The product's description
/// @param _price The product's price
/// @param _SKU The product's SKU
/// @param _quantity The product's quantity
/// @param _storeID The unique ID of the product's associated store
function newProduct(string calldata _name, string calldata _description, uint _price, uint _SKU, uint _quantity, uint _storeID) external payable requireIsActive {
require (msg.value == .001 ether);
balance += msg.value;
Products memory c;
c.name = _name;
c.description = _description;
c.price = _price;
c.SKU = _SKU;
c.quantity = _quantity;
uint abc = getID();
c.uniqueID = abc;
c.seller = msg.sender;
c.storeID = _storeID;
insertProduct(c, _storeID, abc);
emit ProductCreated(_name, _price, _SKU, _quantity, abc, msg.sender, c.storeID);
}
/// @dev private function, called during previous function to add new Product object to storage variables
function insertProduct(Products memory c, uint storeID, uint _uniqueID) private {
products[storeID].push(c);
productsMapping[_uniqueID] = c;
}
/// @notice function for editing an existing product
/// @dev built-in circuit breaker; called externally, used for editing an existing, listed Product
/// @param _index The product's index # in the products array
/// @param _name The product's name
/// @param _description The product's description
/// @param _price The product's price
/// @param _SKU The product's SKU
/// @param _quantity The product's quantity
/// @param _storeID The unique ID of the product's associated store
/// @param _uniqueID The product's unique ID
function editProduct(uint _index, string calldata _name, string calldata _description, uint _price, uint _SKU, uint _quantity, uint _storeID, uint _uniqueID) external requireIsActive {
products[_storeID][_index].name = _name;
products[_storeID][_index].description = _description;
products[_storeID][_index].price = _price;
products[_storeID][_index].SKU = _SKU;
products[_storeID][_index].quantity = _quantity;
productsMapping[_uniqueID].name = _name;
productsMapping[_uniqueID].description = _description;
productsMapping[_uniqueID].price = _price;
productsMapping[_uniqueID].SKU = _SKU;
productsMapping[_uniqueID].quantity = _quantity;
emit ProductUpdated(_name, _price, _SKU, _quantity, _uniqueID, msg.sender, _storeID);
}
/// @notice function for editing an existing store
/// @dev built-in circuit breaker; called externally, used for editing an existing, listed store
/// @param _index The store's index # in the stores array
/// @param _storeID The unique ID of the store
/// @param _name The store's name
/// @param _description The store's description
/// @param _website The store's website
/// @param _email The store's email
function editStore(uint _index, uint _storeID, string calldata _name, string calldata _description, string calldata _website, string calldata _email) external requireIsActive {
require(storesMapping[_storeID].owner == msg.sender);
stores[msg.sender][_index].name = _name;
stores[msg.sender][_index].description = _description;
stores[msg.sender][_index].website = _website;
stores[msg.sender][_index].email = _email;
storesMapping[_storeID].name = _name;
storesMapping[_storeID].description = _description;
storesMapping[_storeID].website = _website;
storesMapping[_storeID].email = _email;
emit StoreUpdated(msg.sender, _storeID, _name, _description, _website, _email);
}
/// @notice function executed when purchasing a product
/// @dev called externally, checks for the product price to be equal to tx value sent and that product is in stock, then sets "sold" property to true and sends value to seller
/// @param _productID The product's unique ID
function buyItem(uint _productID) external payable requireIsActive {
require (msg.value == productsMapping[_productID].price);
require (productsMapping[_productID].quantity > 0);
require (bytes(emails[msg.sender]).length > 0, "You need to register an email address before purchasing an item.");
productsMapping[_productID].seller.transfer(msg.value);
productsMapping[_productID].quantity -= 1;
uint orderID = getID();
orders[orderID][_productID] = productsMapping[_productID];
orders[orderID][_productID].buyer = msg.sender;
orders[orderID][_productID].orderID = orderID;
emit ProductSold(orderID,_productID, msg.sender, productsMapping[_productID].seller, productsMapping[_productID].price, emails[msg.sender]);
}
/// @notice setter function for updating trackingNumber once product is shipped
/// @dev called externally by seller, used for updating trackingNumber and shipped values in mapping of Products (_uniqueID key)
/// @param _orderID The order ID associated with the product being shipped
/// @param _productID The product's unique ID
/// @param _trackingNumber The product's tracking number when shipped
function itemShipped(uint _orderID, uint _productID, uint _trackingNumber) external {
require(orders[_orderID][_productID].seller == msg.sender);
orders[_orderID][_productID].trackingNumber = _trackingNumber;
orders[_orderID][_productID].shipped = true;
emit ProductShipped(_orderID, _productID, _trackingNumber, productsMapping[_productID].seller, orders[_orderID][_productID].buyer);
}
/// @notice function to register an email address
/// @dev updates mapping of email addresses using msg.sender as key (address key)
/// @param _email email address of the person calling the function
function register(string calldata _email) external requireIsActive {
emails[msg.sender] = _email;
emit UserRegistered(msg.sender, _email);
}
/// @notice getter function for retrieving the contract's current balance
/// @dev called externally, used for updating the contract's current balance in the front-end
/// @return balance, The contract's current balance
function getBalance() external view returns (uint) {
return address(this).balance;
}
/// @notice function to withdraw all funds from the contract
/// @dev built-in circuit breaker; called externally by contract owner, used for withdrawing all available funds in the contract
function withdrawAll() external onlyOwner requireIsActive {
uint toTransfer = balance;
balance = 0;
msg.sender.transfer(toTransfer);
}
/// @notice function to initiate the contract's circuit breaker (freeze certain contract functions)
/// @dev called externally by contract's owner, toggles isActive bool variable to enable or disable circuit breaker
function toggleCircuitBreaker() external onlyOwner {
isActive = !isActive;
}
}
| @notice function to register an email address @dev updates mapping of email addresses using msg.sender as key (address key) @param _email email address of the person calling the function | function register(string calldata _email) external requireIsActive {
emails[msg.sender] = _email;
emit UserRegistered(msg.sender, _email);
}
| 15,821,308 | [
1,
915,
358,
1744,
392,
2699,
1758,
225,
4533,
2874,
434,
2699,
6138,
1450,
1234,
18,
15330,
487,
498,
261,
2867,
498,
13,
225,
389,
3652,
2699,
1758,
434,
326,
6175,
4440,
326,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1744,
12,
1080,
745,
892,
389,
3652,
13,
3903,
2583,
2520,
3896,
288,
203,
3639,
14255,
63,
3576,
18,
15330,
65,
273,
389,
3652,
31,
203,
3639,
3626,
2177,
10868,
12,
3576,
18,
15330,
16,
389,
3652,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.2;
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
contract ERC1155SingleBoxWrapper {
using SafeMath for uint256;
struct Token {
uint256 id;
uint8 status;
address creator;
string uri;
uint256 supply;
}
mapping(uint256 => Token) public tokens;
uint256 internal current;
event AddToken(uint256 tokenId, address creator, string uri, uint256 supply);
event UpdateSupply(uint256 tokenId, uint256 supply);
event MintToken(address indexed to, uint256 tokenId, uint256 amount);
/// @dev Explain to a developer any extra details
/// @param uri the token uri.
/// @return tokenId the id of the token.
function _addToken(
address creator_,
string memory uri,
uint256 supply_
) internal returns (uint256 tokenId) {
require(supply_ > 0, 'ERC1155SingleBoxWrapper: invalid creator.');
require(creator_ != address(0), 'ERC1155SingleBoxWrapper: invalid creator.');
tokenId = current++;
tokens[tokenId].creator = creator_;
tokens[tokenId].uri = uri;
tokens[tokenId].supply = supply_;
emit AddToken(tokenId, creator_, uri, supply_);
}
function _mintToken(
address receiver,
uint256 tokenId,
uint256 amount
) internal {
require(_tokenExists(tokenId), 'ERC1155SingleBoxWrapper: nonexistent token.');
require(_supply(tokenId) >= amount, 'ERC1155SingleBoxWrapper: supply is not enough.');
tokens[tokenId].status = 1;
tokens[tokenId].supply = tokens[tokenId].supply.sub(amount);
emit MintToken(receiver, tokenId, amount);
}
function _updateSupply(uint256 tokenId, uint256 supply_) internal {
require(_tokenExists(tokenId), 'ERC1155SingleBoxWrapper: nonexistent token.');
tokens[tokenId].supply = supply_;
emit UpdateSupply(tokenId, supply_);
}
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
require(_tokenExists(tokenId), 'ERC1155SingleBoxWrapper: nonexistent token.');
return tokens[tokenId].uri;
}
function _creator(uint256 tokenId) internal view returns (address) {
require(_tokenExists(tokenId), 'ERC1155SingleBoxWrapper: nonexistent token.');
return tokens[tokenId].creator;
}
function _supply(uint256 tokenId) internal view returns (uint256) {
return tokens[tokenId].supply;
}
function _status(uint256 tokenId) internal view returns (uint8) {
require(_tokenExists(tokenId), 'ERC1155SingleBoxWrapper: nonexistent token.');
return tokens[tokenId].status;
}
function _tokenExists(uint256 tokenId) internal view returns (bool) {
return tokens[tokenId].creator != address(0);
}
}
| @dev Explain to a developer any extra details @param uri the token uri. @return tokenId the id of the token. | function _addToken(
address creator_,
string memory uri,
uint256 supply_
) internal returns (uint256 tokenId) {
require(supply_ > 0, 'ERC1155SingleBoxWrapper: invalid creator.');
require(creator_ != address(0), 'ERC1155SingleBoxWrapper: invalid creator.');
tokenId = current++;
tokens[tokenId].creator = creator_;
tokens[tokenId].uri = uri;
tokens[tokenId].supply = supply_;
emit AddToken(tokenId, creator_, uri, supply_);
}
| 6,439,915 | [
1,
424,
7446,
358,
279,
8751,
1281,
2870,
3189,
225,
2003,
326,
1147,
2003,
18,
327,
1147,
548,
225,
326,
612,
434,
326,
1147,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
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,
202,
915,
389,
1289,
1345,
12,
203,
202,
202,
2867,
11784,
67,
16,
203,
202,
202,
1080,
3778,
2003,
16,
203,
202,
202,
11890,
5034,
14467,
67,
203,
202,
13,
2713,
1135,
261,
11890,
5034,
1147,
548,
13,
288,
203,
202,
202,
6528,
12,
2859,
1283,
67,
405,
374,
16,
296,
654,
39,
2499,
2539,
5281,
3514,
3611,
30,
2057,
11784,
1093,
1769,
203,
202,
202,
6528,
12,
20394,
67,
480,
1758,
12,
20,
3631,
296,
654,
39,
2499,
2539,
5281,
3514,
3611,
30,
2057,
11784,
1093,
1769,
203,
202,
202,
2316,
548,
273,
783,
9904,
31,
203,
202,
202,
7860,
63,
2316,
548,
8009,
20394,
273,
11784,
67,
31,
203,
202,
202,
7860,
63,
2316,
548,
8009,
1650,
273,
2003,
31,
203,
202,
202,
7860,
63,
2316,
548,
8009,
2859,
1283,
273,
14467,
67,
31,
203,
203,
202,
202,
18356,
1436,
1345,
12,
2316,
548,
16,
11784,
67,
16,
2003,
16,
14467,
67,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
interface IAuthoriser {
function isAuthorised(address _sender, address _spender, address _to, bytes calldata _data) external view returns (bool);
function areAuthorised(
address _spender,
address[] calldata _spenders,
address[] calldata _to,
bytes[] calldata _data
)
external
view
returns (bool);
}
// Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.4 <0.9.0;
/**
* @title IModuleRegistry
* @notice Interface for the registry of authorised modules.
*/
interface IModuleRegistry {
function registerModule(address _module, bytes32 _name) external;
function deregisterModule(address _module) external;
function registerUpgrader(address _upgrader, bytes32 _name) external;
function deregisterUpgrader(address _upgrader) external;
function recoverToken(address _token) external;
function moduleInfo(address _module) external view returns (bytes32);
function upgraderInfo(address _upgrader) external view returns (bytes32);
function isRegisteredModule(address _module) external view returns (bool);
function isRegisteredModule(address[] calldata _modules) external view returns (bool);
function isRegisteredUpgrader(address _upgrader) external view returns (bool);
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.4 <0.9.0;
interface IGuardianStorage {
/**
* @notice Lets an authorised module add a guardian to a wallet.
* @param _wallet The target wallet.
* @param _guardian The guardian to add.
*/
function addGuardian(address _wallet, address _guardian) external;
/**
* @notice Lets an authorised module revoke a guardian from a wallet.
* @param _wallet The target wallet.
* @param _guardian The guardian to revoke.
*/
function revokeGuardian(address _wallet, address _guardian) external;
/**
* @notice Checks if an account is a guardian for a wallet.
* @param _wallet The target wallet.
* @param _guardian The account.
* @return true if the account is a guardian for a wallet.
*/
function isGuardian(address _wallet, address _guardian) external view returns (bool);
function isLocked(address _wallet) external view returns (bool);
function getLock(address _wallet) external view returns (uint256);
function getLocker(address _wallet) external view returns (address);
function setLock(address _wallet, uint256 _releaseAfter) external;
function getGuardians(address _wallet) external view returns (address[] memory);
function guardianCount(address _wallet) external view returns (uint256);
}
// Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.4 <0.9.0;
/**
* @title ITransferStorage
* @notice TransferStorage interface
*/
interface ITransferStorage {
function setWhitelist(address _wallet, address _target, uint256 _value) external;
function getWhitelist(address _wallet, address _target) external view returns (uint256);
}
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "./common/Utils.sol";
import "./common/BaseModule.sol";
import "./RelayerManager.sol";
import "./SecurityManager.sol";
import "./TransactionManager.sol";
/**
* @title ArgentModule
* @notice Single module for the Argent wallet.
* @author Julien Niset - <[email protected]>
*/
contract ArgentModule is BaseModule, RelayerManager, SecurityManager, TransactionManager {
bytes32 constant public NAME = "ArgentModule";
constructor (
IModuleRegistry _registry,
IGuardianStorage _guardianStorage,
ITransferStorage _userWhitelist,
IAuthoriser _authoriser,
address _uniswapRouter,
uint256 _securityPeriod,
uint256 _securityWindow,
uint256 _recoveryPeriod,
uint256 _lockPeriod
)
BaseModule(_registry, _guardianStorage, _userWhitelist, _authoriser, NAME)
SecurityManager(_recoveryPeriod, _securityPeriod, _securityWindow, _lockPeriod)
TransactionManager(_securityPeriod)
RelayerManager(_uniswapRouter)
{
}
/**
* @inheritdoc IModule
*/
function init(address _wallet) external override onlyWallet(_wallet) {
enableDefaultStaticCalls(_wallet);
}
/**
* @inheritdoc IModule
*/
function addModule(address _wallet, address _module) external override onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
require(registry.isRegisteredModule(_module), "AM: module is not registered");
IWallet(_wallet).authoriseModule(_module, true);
}
/**
* @inheritdoc RelayerManager
*/
function getRequiredSignatures(address _wallet, bytes calldata _data) public view override returns (uint256, OwnerSignature) {
bytes4 methodId = Utils.functionPrefix(_data);
if (methodId == TransactionManager.multiCall.selector ||
methodId == TransactionManager.addToWhitelist.selector ||
methodId == TransactionManager.removeFromWhitelist.selector ||
methodId == TransactionManager.enableERC1155TokenReceiver.selector ||
methodId == TransactionManager.clearSession.selector ||
methodId == ArgentModule.addModule.selector ||
methodId == SecurityManager.addGuardian.selector ||
methodId == SecurityManager.revokeGuardian.selector ||
methodId == SecurityManager.cancelGuardianAddition.selector ||
methodId == SecurityManager.cancelGuardianRevokation.selector)
{
// owner
return (1, OwnerSignature.Required);
}
if (methodId == TransactionManager.multiCallWithSession.selector) {
return (1, OwnerSignature.Session);
}
if (methodId == SecurityManager.executeRecovery.selector) {
// majority of guardians
uint numberOfSignaturesRequired = _majorityOfGuardians(_wallet);
require(numberOfSignaturesRequired > 0, "AM: no guardians set on wallet");
return (numberOfSignaturesRequired, OwnerSignature.Disallowed);
}
if (methodId == SecurityManager.cancelRecovery.selector) {
// majority of (owner + guardians)
uint numberOfSignaturesRequired = Utils.ceil(recoveryConfigs[_wallet].guardianCount + 1, 2);
return (numberOfSignaturesRequired, OwnerSignature.Optional);
}
if (methodId == TransactionManager.multiCallWithGuardians.selector ||
methodId == TransactionManager.multiCallWithGuardiansAndStartSession.selector ||
methodId == SecurityManager.transferOwnership.selector)
{
// owner + majority of guardians
uint majorityGuardians = _majorityOfGuardians(_wallet);
uint numberOfSignaturesRequired = majorityGuardians + 1;
return (numberOfSignaturesRequired, OwnerSignature.Required);
}
if (methodId == SecurityManager.finalizeRecovery.selector ||
methodId == SecurityManager.confirmGuardianAddition.selector ||
methodId == SecurityManager.confirmGuardianRevokation.selector)
{
// anyone
return (0, OwnerSignature.Anyone);
}
if (methodId == SecurityManager.lock.selector || methodId == SecurityManager.unlock.selector) {
// any guardian
return (1, OwnerSignature.Disallowed);
}
revert("SM: unknown method");
}
function _majorityOfGuardians(address _wallet) internal view returns (uint) {
return Utils.ceil(guardianStorage.guardianCount(_wallet), 2);
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./common/Utils.sol";
import "./common/BaseModule.sol";
import "./common/SimpleOracle.sol";
import "../infrastructure/storage/IGuardianStorage.sol";
/**
* @title RelayerManager
* @notice Abstract Module to execute transactions signed by ETH-less accounts and sent by a relayer.
* @author Julien Niset <[email protected]>, Olivier VDB <[email protected]>
*/
abstract contract RelayerManager is BaseModule, SimpleOracle {
uint256 constant internal BLOCKBOUND = 10000;
mapping (address => RelayerConfig) internal relayer;
struct RelayerConfig {
uint256 nonce;
mapping (bytes32 => bool) executedTx;
}
// Used to avoid stack too deep error
struct StackExtension {
uint256 requiredSignatures;
OwnerSignature ownerSignatureRequirement;
bytes32 signHash;
bool success;
bytes returnData;
}
event TransactionExecuted(address indexed wallet, bool indexed success, bytes returnData, bytes32 signedHash);
event Refund(address indexed wallet, address indexed refundAddress, address refundToken, uint256 refundAmount);
// *************** Constructor ************************ //
constructor(address _uniswapRouter) SimpleOracle(_uniswapRouter) {
}
/* ***************** External methods ************************* */
/**
* @notice Gets the number of valid signatures that must be provided to execute a
* specific relayed transaction.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @return The number of required signatures and the wallet owner signature requirement.
*/
function getRequiredSignatures(address _wallet, bytes calldata _data) public view virtual returns (uint256, OwnerSignature);
/**
* @notice Executes a relayed transaction.
* @param _wallet The target wallet.
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _signatures The signatures as a concatenated byte array.
* @param _gasPrice The max gas price (in token) to use for the gas refund.
* @param _gasLimit The max gas limit to use for the gas refund.
* @param _refundToken The token to use for the gas refund.
* @param _refundAddress The address refunded to prevent front-running.
*/
function execute(
address _wallet,
bytes calldata _data,
uint256 _nonce,
bytes calldata _signatures,
uint256 _gasPrice,
uint256 _gasLimit,
address _refundToken,
address _refundAddress
)
external
returns (bool)
{
// initial gas = 21k + non_zero_bytes * 16 + zero_bytes * 4
// ~= 21k + calldata.length * [1/3 * 16 + 2/3 * 4]
uint256 startGas = gasleft() + 21000 + msg.data.length * 8;
require(startGas >= _gasLimit, "RM: not enough gas provided");
require(verifyData(_wallet, _data), "RM: Target of _data != _wallet");
require(!_isLocked(_wallet) || _gasPrice == 0, "RM: Locked wallet refund");
StackExtension memory stack;
(stack.requiredSignatures, stack.ownerSignatureRequirement) = getRequiredSignatures(_wallet, _data);
require(stack.requiredSignatures > 0 || stack.ownerSignatureRequirement == OwnerSignature.Anyone, "RM: Wrong signature requirement");
require(stack.requiredSignatures * 65 == _signatures.length, "RM: Wrong number of signatures");
stack.signHash = getSignHash(
address(this),
0,
_data,
_nonce,
_gasPrice,
_gasLimit,
_refundToken,
_refundAddress);
require(checkAndUpdateUniqueness(
_wallet,
_nonce,
stack.signHash,
stack.requiredSignatures,
stack.ownerSignatureRequirement), "RM: Duplicate request");
if (stack.ownerSignatureRequirement == OwnerSignature.Session) {
require(validateSession(_wallet, stack.signHash, _signatures), "RM: Invalid session");
} else {
require(validateSignatures(_wallet, stack.signHash, _signatures, stack.ownerSignatureRequirement), "RM: Invalid signatures");
}
(stack.success, stack.returnData) = address(this).call(_data);
refund(
_wallet,
startGas,
_gasPrice,
_gasLimit,
_refundToken,
_refundAddress,
stack.requiredSignatures,
stack.ownerSignatureRequirement);
emit TransactionExecuted(_wallet, stack.success, stack.returnData, stack.signHash);
return stack.success;
}
/**
* @notice Gets the current nonce for a wallet.
* @param _wallet The target wallet.
*/
function getNonce(address _wallet) external view returns (uint256 nonce) {
return relayer[_wallet].nonce;
}
/**
* @notice Checks if a transaction identified by its sign hash has already been executed.
* @param _wallet The target wallet.
* @param _signHash The sign hash of the transaction.
*/
function isExecutedTx(address _wallet, bytes32 _signHash) external view returns (bool executed) {
return relayer[_wallet].executedTx[_signHash];
}
/**
* @notice Gets the last stored session for a wallet.
* @param _wallet The target wallet.
*/
function getSession(address _wallet) external view returns (address key, uint64 expires) {
return (sessions[_wallet].key, sessions[_wallet].expires);
}
/* ***************** Internal & Private methods ************************* */
/**
* @notice Generates the signed hash of a relayed transaction according to ERC 1077.
* @param _from The starting address for the relayed transaction (should be the relayer module)
* @param _value The value for the relayed transaction.
* @param _data The data for the relayed transaction which includes the wallet address.
* @param _nonce The nonce used to prevent replay attacks.
* @param _gasPrice The max gas price (in token) to use for the gas refund.
* @param _gasLimit The max gas limit to use for the gas refund.
* @param _refundToken The token to use for the gas refund.
* @param _refundAddress The address refunded to prevent front-running.
*/
function getSignHash(
address _from,
uint256 _value,
bytes memory _data,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit,
address _refundToken,
address _refundAddress
)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(
bytes1(0x19),
bytes1(0),
_from,
_value,
_data,
block.chainid,
_nonce,
_gasPrice,
_gasLimit,
_refundToken,
_refundAddress))
));
}
/**
* @notice Checks if the relayed transaction is unique. If yes the state is updated.
* For actions requiring 1 signature by the owner or a session key we use the incremental nonce.
* For all other actions we check/store the signHash in a mapping.
* @param _wallet The target wallet.
* @param _nonce The nonce.
* @param _signHash The signed hash of the transaction.
* @param requiredSignatures The number of signatures required.
* @param ownerSignatureRequirement The wallet owner signature requirement.
* @return true if the transaction is unique.
*/
function checkAndUpdateUniqueness(
address _wallet,
uint256 _nonce,
bytes32 _signHash,
uint256 requiredSignatures,
OwnerSignature ownerSignatureRequirement
)
internal
returns (bool)
{
if (requiredSignatures == 1 &&
(ownerSignatureRequirement == OwnerSignature.Required || ownerSignatureRequirement == OwnerSignature.Session)) {
// use the incremental nonce
if (_nonce <= relayer[_wallet].nonce) {
return false;
}
uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128;
if (nonceBlock > block.number + BLOCKBOUND) {
return false;
}
relayer[_wallet].nonce = _nonce;
return true;
} else {
// use the txHash map
if (relayer[_wallet].executedTx[_signHash] == true) {
return false;
}
relayer[_wallet].executedTx[_signHash] = true;
return true;
}
}
/**
* @notice Validates the signatures provided with a relayed transaction.
* @param _wallet The target wallet.
* @param _signHash The signed hash representing the relayed transaction.
* @param _signatures The signatures as a concatenated bytes array.
* @param _option An OwnerSignature enum indicating whether the owner is required, optional or disallowed.
* @return A boolean indicating whether the signatures are valid.
*/
function validateSignatures(address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option) internal view returns (bool)
{
if (_signatures.length == 0) {
return true;
}
address lastSigner = address(0);
address[] memory guardians;
if (_option != OwnerSignature.Required || _signatures.length > 65) {
guardians = guardianStorage.getGuardians(_wallet); // guardians are only read if they may be needed
}
bool isGuardian;
for (uint256 i = 0; i < _signatures.length / 65; i++) {
address signer = Utils.recoverSigner(_signHash, _signatures, i);
if (i == 0) {
if (_option == OwnerSignature.Required) {
// First signer must be owner
if (_isOwner(_wallet, signer)) {
continue;
}
return false;
} else if (_option == OwnerSignature.Optional) {
// First signer can be owner
if (_isOwner(_wallet, signer)) {
continue;
}
}
}
if (signer <= lastSigner) {
return false; // Signers must be different
}
lastSigner = signer;
(isGuardian, guardians) = Utils.isGuardianOrGuardianSigner(guardians, signer);
if (!isGuardian) {
return false;
}
}
return true;
}
/**
* @notice Validates the signature provided when a session key was used.
* @param _wallet The target wallet.
* @param _signHash The signed hash representing the relayed transaction.
* @param _signatures The signatures as a concatenated bytes array.
* @return A boolean indicating whether the signature is valid.
*/
function validateSession(address _wallet, bytes32 _signHash, bytes calldata _signatures) internal view returns (bool) {
Session memory session = sessions[_wallet];
address signer = Utils.recoverSigner(_signHash, _signatures, 0);
return (signer == session.key && session.expires >= block.timestamp);
}
/**
* @notice Refunds the gas used to the Relayer.
* @param _wallet The target wallet.
* @param _startGas The gas provided at the start of the execution.
* @param _gasPrice The max gas price (in token) for the refund.
* @param _gasLimit The max gas limit for the refund.
* @param _refundToken The token to use for the gas refund.
* @param _refundAddress The address refunded to prevent front-running.
* @param _requiredSignatures The number of signatures required.
* @param _option An OwnerSignature enum indicating the signature requirement.
*/
function refund(
address _wallet,
uint _startGas,
uint _gasPrice,
uint _gasLimit,
address _refundToken,
address _refundAddress,
uint256 _requiredSignatures,
OwnerSignature _option
)
internal
{
// Only refund when the owner is one of the signers or a session key was used
if (_gasPrice > 0 && (_option == OwnerSignature.Required || _option == OwnerSignature.Session)) {
address refundAddress = _refundAddress == address(0) ? msg.sender : _refundAddress;
if (_requiredSignatures == 1 && _option == OwnerSignature.Required) {
// refundAddress must be whitelisted/authorised
if (!authoriser.isAuthorised(_wallet, refundAddress, address(0), EMPTY_BYTES)) {
uint whitelistAfter = userWhitelist.getWhitelist(_wallet, refundAddress);
require(whitelistAfter > 0 && whitelistAfter < block.timestamp, "RM: refund not authorised");
}
}
uint256 refundAmount;
if (_refundToken == ETH_TOKEN) {
// 23k as an upper bound to cover the rest of refund logic
uint256 gasConsumed = _startGas - gasleft() + 23000;
refundAmount = Math.min(gasConsumed, _gasLimit) * (Math.min(_gasPrice, tx.gasprice));
invokeWallet(_wallet, refundAddress, refundAmount, EMPTY_BYTES);
} else {
// 37.5k as an upper bound to cover the rest of refund logic
uint256 gasConsumed = _startGas - gasleft() + 37500;
uint256 tokenGasPrice = inToken(_refundToken, tx.gasprice);
refundAmount = Math.min(gasConsumed, _gasLimit) * (Math.min(_gasPrice, tokenGasPrice));
bytes memory methodData = abi.encodeWithSelector(ERC20.transfer.selector, refundAddress, refundAmount);
bytes memory transferSuccessBytes = invokeWallet(_wallet, _refundToken, 0, methodData);
// Check token refund is successful, when `transfer` returns a success bool result
if (transferSuccessBytes.length > 0) {
require(abi.decode(transferSuccessBytes, (bool)), "RM: Refund transfer failed");
}
}
emit Refund(_wallet, refundAddress, _refundToken, refundAmount);
}
}
/**
* @notice Checks that the wallet address provided as the first parameter of _data matches _wallet
* @return false if the addresses are different.
*/
function verifyData(address _wallet, bytes calldata _data) internal pure returns (bool) {
require(_data.length >= 36, "RM: Invalid dataWallet");
address dataWallet = abi.decode(_data[4:], (address));
return dataWallet == _wallet;
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./common/Utils.sol";
import "./common/BaseModule.sol";
import "../wallet/IWallet.sol";
/**
* @title SecurityManager
* @notice Abstract module implementing the key security features of the wallet: guardians, lock and recovery.
* @author Julien Niset - <[email protected]>
* @author Olivier Van Den Biggelaar - <[email protected]>
*/
abstract contract SecurityManager is BaseModule {
struct RecoveryConfig {
address recovery;
uint64 executeAfter;
uint32 guardianCount;
}
struct GuardianManagerConfig {
// The time at which a guardian addition or revokation will be confirmable by the owner
mapping (bytes32 => uint256) pending;
}
// Wallet specific storage for recovery
mapping (address => RecoveryConfig) internal recoveryConfigs;
// Wallet specific storage for pending guardian addition/revokation
mapping (address => GuardianManagerConfig) internal guardianConfigs;
// Recovery period
uint256 internal immutable recoveryPeriod;
// Lock period
uint256 internal immutable lockPeriod;
// The security period to add/remove guardians
uint256 internal immutable securityPeriod;
// The security window
uint256 internal immutable securityWindow;
// *************** Events *************************** //
event RecoveryExecuted(address indexed wallet, address indexed _recovery, uint64 executeAfter);
event RecoveryFinalized(address indexed wallet, address indexed _recovery);
event RecoveryCanceled(address indexed wallet, address indexed _recovery);
event OwnershipTransfered(address indexed wallet, address indexed _newOwner);
event Locked(address indexed wallet, uint64 releaseAfter);
event Unlocked(address indexed wallet);
event GuardianAdditionRequested(address indexed wallet, address indexed guardian, uint256 executeAfter);
event GuardianRevokationRequested(address indexed wallet, address indexed guardian, uint256 executeAfter);
event GuardianAdditionCancelled(address indexed wallet, address indexed guardian);
event GuardianRevokationCancelled(address indexed wallet, address indexed guardian);
event GuardianAdded(address indexed wallet, address indexed guardian);
event GuardianRevoked(address indexed wallet, address indexed guardian);
// *************** Modifiers ************************ //
/**
* @notice Throws if there is no ongoing recovery procedure.
*/
modifier onlyWhenRecovery(address _wallet) {
require(recoveryConfigs[_wallet].executeAfter > 0, "SM: no ongoing recovery");
_;
}
/**
* @notice Throws if there is an ongoing recovery procedure.
*/
modifier notWhenRecovery(address _wallet) {
require(recoveryConfigs[_wallet].executeAfter == 0, "SM: ongoing recovery");
_;
}
/**
* @notice Throws if the caller is not a guardian for the wallet or the module itself.
*/
modifier onlyGuardianOrSelf(address _wallet) {
require(_isSelf(msg.sender) || isGuardian(_wallet, msg.sender), "SM: must be guardian/self");
_;
}
// *************** Constructor ************************ //
constructor(
uint256 _recoveryPeriod,
uint256 _securityPeriod,
uint256 _securityWindow,
uint256 _lockPeriod
) {
// For the wallet to be secure we must have recoveryPeriod >= securityPeriod + securityWindow
// where securityPeriod and securityWindow are the security parameters of adding/removing guardians.
require(_lockPeriod >= _recoveryPeriod, "SM: insecure lock period");
require(_recoveryPeriod >= _securityPeriod + _securityWindow, "SM: insecure security periods");
recoveryPeriod = _recoveryPeriod;
lockPeriod = _lockPeriod;
securityWindow = _securityWindow;
securityPeriod = _securityPeriod;
}
// *************** External functions ************************ //
// *************** Recovery functions ************************ //
/**
* @notice Lets the guardians start the execution of the recovery procedure.
* Once triggered the recovery is pending for the security period before it can be finalised.
* Must be confirmed by N guardians, where N = ceil(Nb Guardians / 2).
* @param _wallet The target wallet.
* @param _recovery The address to which ownership should be transferred.
*/
function executeRecovery(address _wallet, address _recovery) external onlySelf() notWhenRecovery(_wallet) {
validateNewOwner(_wallet, _recovery);
uint64 executeAfter = uint64(block.timestamp + recoveryPeriod);
recoveryConfigs[_wallet] = RecoveryConfig(_recovery, executeAfter, uint32(guardianStorage.guardianCount(_wallet)));
_setLock(_wallet, block.timestamp + lockPeriod, SecurityManager.executeRecovery.selector);
emit RecoveryExecuted(_wallet, _recovery, executeAfter);
}
/**
* @notice Finalizes an ongoing recovery procedure if the security period is over.
* The method is public and callable by anyone to enable orchestration.
* @param _wallet The target wallet.
*/
function finalizeRecovery(address _wallet) external onlyWhenRecovery(_wallet) {
RecoveryConfig storage config = recoveryConfigs[_wallet];
require(uint64(block.timestamp) > config.executeAfter, "SM: ongoing recovery period");
address recoveryOwner = config.recovery;
delete recoveryConfigs[_wallet];
_clearSession(_wallet);
IWallet(_wallet).setOwner(recoveryOwner);
_setLock(_wallet, 0, bytes4(0));
emit RecoveryFinalized(_wallet, recoveryOwner);
}
/**
* @notice Lets the owner cancel an ongoing recovery procedure.
* Must be confirmed by N guardians, where N = ceil(Nb Guardian at executeRecovery + 1) / 2) - 1.
* @param _wallet The target wallet.
*/
function cancelRecovery(address _wallet) external onlySelf() onlyWhenRecovery(_wallet) {
address recoveryOwner = recoveryConfigs[_wallet].recovery;
delete recoveryConfigs[_wallet];
_setLock(_wallet, 0, bytes4(0));
emit RecoveryCanceled(_wallet, recoveryOwner);
}
/**
* @notice Lets the owner transfer the wallet ownership. This is executed immediately.
* @param _wallet The target wallet.
* @param _newOwner The address to which ownership should be transferred.
*/
function transferOwnership(address _wallet, address _newOwner) external onlySelf() onlyWhenUnlocked(_wallet) {
validateNewOwner(_wallet, _newOwner);
IWallet(_wallet).setOwner(_newOwner);
emit OwnershipTransfered(_wallet, _newOwner);
}
/**
* @notice Gets the details of the ongoing recovery procedure if any.
* @param _wallet The target wallet.
*/
function getRecovery(address _wallet) external view returns(address _address, uint64 _executeAfter, uint32 _guardianCount) {
RecoveryConfig storage config = recoveryConfigs[_wallet];
return (config.recovery, config.executeAfter, config.guardianCount);
}
// *************** Lock functions ************************ //
/**
* @notice Lets a guardian lock a wallet.
* @param _wallet The target wallet.
*/
function lock(address _wallet) external onlyGuardianOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
_setLock(_wallet, block.timestamp + lockPeriod, SecurityManager.lock.selector);
emit Locked(_wallet, uint64(block.timestamp + lockPeriod));
}
/**
* @notice Lets a guardian unlock a locked wallet.
* @param _wallet The target wallet.
*/
function unlock(address _wallet) external onlyGuardianOrSelf(_wallet) onlyWhenLocked(_wallet) {
require(locks[_wallet].locker == SecurityManager.lock.selector, "SM: cannot unlock");
_setLock(_wallet, 0, bytes4(0));
emit Unlocked(_wallet);
}
/**
* @notice Returns the release time of a wallet lock or 0 if the wallet is unlocked.
* @param _wallet The target wallet.
* @return _releaseAfter The epoch time at which the lock will release (in seconds).
*/
function getLock(address _wallet) external view returns(uint64 _releaseAfter) {
return _isLocked(_wallet) ? locks[_wallet].release : 0;
}
/**
* @notice Checks if a wallet is locked.
* @param _wallet The target wallet.
* @return _isLocked `true` if the wallet is locked otherwise `false`.
*/
function isLocked(address _wallet) external view returns (bool) {
return _isLocked(_wallet);
}
// *************** Guardian functions ************************ //
/**
* @notice Lets the owner add a guardian to its wallet.
* The first guardian is added immediately. All following additions must be confirmed
* by calling the confirmGuardianAddition() method.
* @param _wallet The target wallet.
* @param _guardian The guardian to add.
*/
function addGuardian(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
require(!_isOwner(_wallet, _guardian), "SM: guardian cannot be owner");
require(!isGuardian(_wallet, _guardian), "SM: duplicate guardian");
// Guardians must either be an EOA or a contract with an owner()
// method that returns an address with a 25000 gas stipend.
// Note that this test is not meant to be strict and can be bypassed by custom malicious contracts.
(bool success,) = _guardian.call{gas: 25000}(abi.encodeWithSignature("owner()"));
require(success, "SM: must be EOA/Argent wallet");
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(
config.pending[id] == 0 || block.timestamp > config.pending[id] + securityWindow,
"SM: duplicate pending addition");
config.pending[id] = block.timestamp + securityPeriod;
emit GuardianAdditionRequested(_wallet, _guardian, block.timestamp + securityPeriod);
}
/**
* @notice Confirms the pending addition of a guardian to a wallet.
* The method must be called during the confirmation window and can be called by anyone to enable orchestration.
* @param _wallet The target wallet.
* @param _guardian The guardian.
*/
function confirmGuardianAddition(address _wallet, address _guardian) external onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending addition");
require(config.pending[id] < block.timestamp, "SM: pending addition not over");
require(block.timestamp < config.pending[id] + securityWindow, "SM: pending addition expired");
guardianStorage.addGuardian(_wallet, _guardian);
emit GuardianAdded(_wallet, _guardian);
delete config.pending[id];
}
/**
* @notice Lets the owner cancel a pending guardian addition.
* @param _wallet The target wallet.
* @param _guardian The guardian.
*/
function cancelGuardianAddition(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending addition");
delete config.pending[id];
emit GuardianAdditionCancelled(_wallet, _guardian);
}
/**
* @notice Lets the owner revoke a guardian from its wallet.
* @dev Revokation must be confirmed by calling the confirmGuardianRevokation() method.
* @param _wallet The target wallet.
* @param _guardian The guardian to revoke.
*/
function revokeGuardian(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) {
require(isGuardian(_wallet, _guardian), "SM: must be existing guardian");
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(
config.pending[id] == 0 || block.timestamp > config.pending[id] + securityWindow,
"SM: duplicate pending revoke"); // TODO need to allow if confirmation window passed
config.pending[id] = block.timestamp + securityPeriod;
emit GuardianRevokationRequested(_wallet, _guardian, block.timestamp + securityPeriod);
}
/**
* @notice Confirms the pending revokation of a guardian to a wallet.
* The method must be called during the confirmation window and can be called by anyone to enable orchestration.
* @param _wallet The target wallet.
* @param _guardian The guardian.
*/
function confirmGuardianRevokation(address _wallet, address _guardian) external {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending revoke");
require(config.pending[id] < block.timestamp, "SM: pending revoke not over");
require(block.timestamp < config.pending[id] + securityWindow, "SM: pending revoke expired");
guardianStorage.revokeGuardian(_wallet, _guardian);
emit GuardianRevoked(_wallet, _guardian);
delete config.pending[id];
}
/**
* @notice Lets the owner cancel a pending guardian revokation.
* @param _wallet The target wallet.
* @param _guardian The guardian.
*/
function cancelGuardianRevokation(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending revoke");
delete config.pending[id];
emit GuardianRevokationCancelled(_wallet, _guardian);
}
/**
* @notice Checks if an address is a guardian for a wallet.
* @param _wallet The target wallet.
* @param _guardian The address to check.
* @return _isGuardian `true` if the address is a guardian for the wallet otherwise `false`.
*/
function isGuardian(address _wallet, address _guardian) public view returns (bool _isGuardian) {
return guardianStorage.isGuardian(_wallet, _guardian);
}
/**
* @notice Checks if an address is a guardian or an account authorised to sign on behalf of a smart-contract guardian.
* @param _wallet The target wallet.
* @param _guardian the address to test
* @return _isGuardian `true` if the address is a guardian for the wallet otherwise `false`.
*/
function isGuardianOrGuardianSigner(address _wallet, address _guardian) external view returns (bool _isGuardian) {
(_isGuardian, ) = Utils.isGuardianOrGuardianSigner(guardianStorage.getGuardians(_wallet), _guardian);
}
/**
* @notice Counts the number of active guardians for a wallet.
* @param _wallet The target wallet.
* @return _count The number of active guardians for a wallet.
*/
function guardianCount(address _wallet) external view returns (uint256 _count) {
return guardianStorage.guardianCount(_wallet);
}
/**
* @notice Get the active guardians for a wallet.
* @param _wallet The target wallet.
* @return _guardians the active guardians for a wallet.
*/
function getGuardians(address _wallet) external view returns (address[] memory _guardians) {
return guardianStorage.getGuardians(_wallet);
}
// *************** Internal Functions ********************* //
function validateNewOwner(address _wallet, address _newOwner) internal view {
require(_newOwner != address(0), "SM: new owner cannot be null");
require(!isGuardian(_wallet, _newOwner), "SM: new owner cannot be guardian");
}
function _setLock(address _wallet, uint256 _releaseAfter, bytes4 _locker) internal {
locks[_wallet] = Lock(SafeCast.toUint64(_releaseAfter), _locker);
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./common/Utils.sol";
import "./common/BaseModule.sol";
import "../../lib_0.5/other/ERC20.sol";
/**
* @title TransactionManager
* @notice Module to execute transactions in sequence to e.g. transfer tokens (ETH, ERC20, ERC721, ERC1155) or call third-party contracts.
* @author Julien Niset - <[email protected]>
*/
abstract contract TransactionManager is BaseModule {
// Static calls
bytes4 private constant ERC1271_IS_VALID_SIGNATURE = bytes4(keccak256("isValidSignature(bytes32,bytes)"));
bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
bytes4 private constant ERC1155_RECEIVED = bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
bytes4 private constant ERC1155_BATCH_RECEIVED = bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));
bytes4 private constant ERC165_INTERFACE = bytes4(keccak256("supportsInterface(bytes4)"));
struct Call {
address to;
uint256 value;
bytes data;
}
// The time delay for adding a trusted contact
uint256 internal immutable whitelistPeriod;
// *************** Events *************************** //
event AddedToWhitelist(address indexed wallet, address indexed target, uint64 whitelistAfter);
event RemovedFromWhitelist(address indexed wallet, address indexed target);
event SessionCreated(address indexed wallet, address sessionKey, uint64 expires);
event SessionCleared(address indexed wallet, address sessionKey);
// *************** Constructor ************************ //
constructor(uint256 _whitelistPeriod) {
whitelistPeriod = _whitelistPeriod;
}
// *************** External functions ************************ //
/**
* @notice Makes the target wallet execute a sequence of transactions authorised by the wallet owner.
* The method reverts if any of the inner transactions reverts.
* The method reverts if any of the inner transaction is not to a trusted contact or an authorised dapp.
* @param _wallet The target wallet.
* @param _transactions The sequence of transactions.
*/
function multiCall(
address _wallet,
Call[] calldata _transactions
)
external
onlySelf()
onlyWhenUnlocked(_wallet)
returns (bytes[] memory)
{
bytes[] memory results = new bytes[](_transactions.length);
for(uint i = 0; i < _transactions.length; i++) {
address spender = Utils.recoverSpender(_transactions[i].to, _transactions[i].data);
require(
(_transactions[i].value == 0 || spender == _transactions[i].to) &&
(isWhitelisted(_wallet, spender) || authoriser.isAuthorised(_wallet, spender, _transactions[i].to, _transactions[i].data)),
"TM: call not authorised");
results[i] = invokeWallet(_wallet, _transactions[i].to, _transactions[i].value, _transactions[i].data);
}
return results;
}
/**
* @notice Makes the target wallet execute a sequence of transactions authorised by a session key.
* The method reverts if any of the inner transactions reverts.
* @param _wallet The target wallet.
* @param _transactions The sequence of transactions.
*/
function multiCallWithSession(
address _wallet,
Call[] calldata _transactions
)
external
onlySelf()
onlyWhenUnlocked(_wallet)
returns (bytes[] memory)
{
return multiCallWithApproval(_wallet, _transactions);
}
/**
* @notice Makes the target wallet execute a sequence of transactions approved by a majority of guardians.
* The method reverts if any of the inner transactions reverts.
* @param _wallet The target wallet.
* @param _transactions The sequence of transactions.
*/
function multiCallWithGuardians(
address _wallet,
Call[] calldata _transactions
)
external
onlySelf()
onlyWhenUnlocked(_wallet)
returns (bytes[] memory)
{
return multiCallWithApproval(_wallet, _transactions);
}
/**
* @notice Makes the target wallet execute a sequence of transactions approved by a majority of guardians.
* The method reverts if any of the inner transactions reverts.
* Upon success a new session is started.
* @param _wallet The target wallet.
* @param _transactions The sequence of transactions.
*/
function multiCallWithGuardiansAndStartSession(
address _wallet,
Call[] calldata _transactions,
address _sessionUser,
uint64 _duration
)
external
onlySelf()
onlyWhenUnlocked(_wallet)
returns (bytes[] memory)
{
startSession(_wallet, _sessionUser, _duration);
return multiCallWithApproval(_wallet, _transactions);
}
/**
* @notice Clears the active session of a wallet if any.
* @param _wallet The target wallet.
*/
function clearSession(address _wallet) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
emit SessionCleared(_wallet, sessions[_wallet].key);
_clearSession(_wallet);
}
/**
* @notice Adds an address to the list of trusted contacts.
* @param _wallet The target wallet.
* @param _target The address to add.
*/
function addToWhitelist(address _wallet, address _target) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
require(_target != _wallet, "TM: Cannot whitelist wallet");
require(!registry.isRegisteredModule(_target), "TM: Cannot whitelist module");
require(!isWhitelisted(_wallet, _target), "TM: target already whitelisted");
uint256 whitelistAfter = block.timestamp + whitelistPeriod;
setWhitelist(_wallet, _target, whitelistAfter);
emit AddedToWhitelist(_wallet, _target, uint64(whitelistAfter));
}
/**
* @notice Removes an address from the list of trusted contacts.
* @param _wallet The target wallet.
* @param _target The address to remove.
*/
function removeFromWhitelist(address _wallet, address _target) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
setWhitelist(_wallet, _target, 0);
emit RemovedFromWhitelist(_wallet, _target);
}
/**
* @notice Checks if an address is a trusted contact for a wallet.
* @param _wallet The target wallet.
* @param _target The address.
* @return _isWhitelisted true if the address is a trusted contact.
*/
function isWhitelisted(address _wallet, address _target) public view returns (bool _isWhitelisted) {
uint whitelistAfter = userWhitelist.getWhitelist(_wallet, _target);
return whitelistAfter > 0 && whitelistAfter < block.timestamp;
}
/*
* @notice Enable the static calls required to make the wallet compatible with the ERC1155TokenReceiver
* interface (see https://eips.ethereum.org/EIPS/eip-1155#erc-1155-token-receiver). This method only
* needs to be called for wallets deployed in version lower or equal to 2.4.0 as the ERC1155 static calls
* are not available by default for these versions of BaseWallet
* @param _wallet The target wallet.
*/
function enableERC1155TokenReceiver(address _wallet) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
IWallet(_wallet).enableStaticCall(address(this), ERC165_INTERFACE);
IWallet(_wallet).enableStaticCall(address(this), ERC1155_RECEIVED);
IWallet(_wallet).enableStaticCall(address(this), ERC1155_BATCH_RECEIVED);
}
/**
* @inheritdoc IModule
*/
function supportsStaticCall(bytes4 _methodId) external pure override returns (bool _isSupported) {
return _methodId == ERC1271_IS_VALID_SIGNATURE ||
_methodId == ERC721_RECEIVED ||
_methodId == ERC165_INTERFACE ||
_methodId == ERC1155_RECEIVED ||
_methodId == ERC1155_BATCH_RECEIVED;
}
/** ******************* Callbacks ************************** */
/**
* @notice Returns true if this contract implements the interface defined by
* `interfaceId` (see https://eips.ethereum.org/EIPS/eip-165).
*/
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return _interfaceID == ERC165_INTERFACE || _interfaceID == (ERC1155_RECEIVED ^ ERC1155_BATCH_RECEIVED);
}
/**
* @notice Implementation of EIP 1271.
* Should return whether the signature provided is valid for the provided data.
* @param _msgHash Hash of a message signed on the behalf of address(this)
* @param _signature Signature byte array associated with _msgHash
*/
function isValidSignature(bytes32 _msgHash, bytes memory _signature) external view returns (bytes4) {
require(_signature.length == 65, "TM: invalid signature length");
address signer = Utils.recoverSigner(_msgHash, _signature, 0);
require(_isOwner(msg.sender, signer), "TM: Invalid signer");
return ERC1271_IS_VALID_SIGNATURE;
}
fallback() external {
bytes4 methodId = Utils.functionPrefix(msg.data);
if(methodId == ERC721_RECEIVED || methodId == ERC1155_RECEIVED || methodId == ERC1155_BATCH_RECEIVED) {
// solhint-disable-next-line no-inline-assembly
assembly {
calldatacopy(0, 0, 0x04)
return (0, 0x20)
}
}
}
// *************** Internal Functions ********************* //
function enableDefaultStaticCalls(address _wallet) internal {
// setup the static calls that are available for free for all wallets
IWallet(_wallet).enableStaticCall(address(this), ERC1271_IS_VALID_SIGNATURE);
IWallet(_wallet).enableStaticCall(address(this), ERC721_RECEIVED);
}
function multiCallWithApproval(address _wallet, Call[] calldata _transactions) internal returns (bytes[] memory) {
bytes[] memory results = new bytes[](_transactions.length);
for(uint i = 0; i < _transactions.length; i++) {
results[i] = invokeWallet(_wallet, _transactions[i].to, _transactions[i].value, _transactions[i].data);
}
return results;
}
function startSession(address _wallet, address _sessionUser, uint64 _duration) internal {
require(_sessionUser != address(0), "TM: Invalid session user");
require(_duration > 0, "TM: Invalid session duration");
uint64 expiry = SafeCast.toUint64(block.timestamp + _duration);
sessions[_wallet] = Session(_sessionUser, expiry);
emit SessionCreated(_wallet, _sessionUser, expiry);
}
function setWhitelist(address _wallet, address _target, uint256 _whitelistAfter) internal {
userWhitelist.setWhitelist(_wallet, _target, _whitelistAfter);
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "../../wallet/IWallet.sol";
import "../../infrastructure/IModuleRegistry.sol";
import "../../infrastructure/storage/IGuardianStorage.sol";
import "../../infrastructure/IAuthoriser.sol";
import "../../infrastructure/storage/ITransferStorage.sol";
import "./IModule.sol";
import "../../../lib_0.5/other/ERC20.sol";
/**
* @title BaseModule
* @notice Base Module contract that contains methods common to all Modules.
* @author Julien Niset - <[email protected]>, Olivier VDB - <[email protected]>
*/
abstract contract BaseModule is IModule {
// Empty calldata
bytes constant internal EMPTY_BYTES = "";
// Mock token address for ETH
address constant internal ETH_TOKEN = address(0);
// The module registry
IModuleRegistry internal immutable registry;
// The guardians storage
IGuardianStorage internal immutable guardianStorage;
// The trusted contacts storage
ITransferStorage internal immutable userWhitelist;
// The authoriser
IAuthoriser internal immutable authoriser;
event ModuleCreated(bytes32 name);
enum OwnerSignature {
Anyone, // Anyone
Required, // Owner required
Optional, // Owner and/or guardians
Disallowed, // Guardians only
Session // Session only
}
struct Session {
address key;
uint64 expires;
}
// Maps wallet to session
mapping (address => Session) internal sessions;
struct Lock {
// the lock's release timestamp
uint64 release;
// the signature of the method that set the last lock
bytes4 locker;
}
// Wallet specific lock storage
mapping (address => Lock) internal locks;
/**
* @notice Throws if the wallet is not locked.
*/
modifier onlyWhenLocked(address _wallet) {
require(_isLocked(_wallet), "BM: wallet must be locked");
_;
}
/**
* @notice Throws if the wallet is locked.
*/
modifier onlyWhenUnlocked(address _wallet) {
require(!_isLocked(_wallet), "BM: wallet locked");
_;
}
/**
* @notice Throws if the sender is not the module itself.
*/
modifier onlySelf() {
require(_isSelf(msg.sender), "BM: must be module");
_;
}
/**
* @notice Throws if the sender is not the module itself or the owner of the target wallet.
*/
modifier onlyWalletOwnerOrSelf(address _wallet) {
require(_isSelf(msg.sender) || _isOwner(_wallet, msg.sender), "BM: must be wallet owner/self");
_;
}
/**
* @dev Throws if the sender is not the target wallet of the call.
*/
modifier onlyWallet(address _wallet) {
require(msg.sender == _wallet, "BM: caller must be wallet");
_;
}
constructor(
IModuleRegistry _registry,
IGuardianStorage _guardianStorage,
ITransferStorage _userWhitelist,
IAuthoriser _authoriser,
bytes32 _name
) {
registry = _registry;
guardianStorage = _guardianStorage;
userWhitelist = _userWhitelist;
authoriser = _authoriser;
emit ModuleCreated(_name);
}
/**
* @notice Moves tokens that have been sent to the module by mistake.
* @param _token The target token.
*/
function recoverToken(address _token) external {
uint total = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(address(registry), total);
}
function _clearSession(address _wallet) internal {
delete sessions[_wallet];
}
/**
* @notice Helper method to check if an address is the owner of a target wallet.
* @param _wallet The target wallet.
* @param _addr The address.
*/
function _isOwner(address _wallet, address _addr) internal view returns (bool) {
return IWallet(_wallet).owner() == _addr;
}
/**
* @notice Helper method to check if a wallet is locked.
* @param _wallet The target wallet.
*/
function _isLocked(address _wallet) internal view returns (bool) {
return locks[_wallet].release > uint64(block.timestamp);
}
/**
* @notice Helper method to check if an address is the module itself.
* @param _addr The target address.
*/
function _isSelf(address _addr) internal view returns (bool) {
return _addr == address(this);
}
/**
* @notice Helper method to invoke a wallet.
* @param _wallet The target wallet.
* @param _to The target address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) {
bool success;
(success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data));
if (success && _res.length > 0) { //_res is empty if _wallet is an "old" BaseWallet that can't return output values
(_res) = abi.decode(_res, (bytes));
} else if (_res.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
} else if (!success) {
revert("BM: wallet invoke reverted");
}
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
/**
* @title IModule
* @notice Interface for a Module.
* @author Julien Niset - <[email protected]>, Olivier VDB - <[email protected]>
*/
interface IModule {
/**
* @notice Adds a module to a wallet. Cannot execute when wallet is locked (or under recovery)
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(address _wallet, address _module) external;
/**
* @notice Inits a Module for a wallet by e.g. setting some wallet specific parameters in storage.
* @param _wallet The wallet.
*/
function init(address _wallet) external;
/**
* @notice Returns whether the module implements a callback for a given static call method.
* @param _methodId The method id.
*/
function supportsStaticCall(bytes4 _methodId) external view returns (bool _isSupported);
}
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
contract SimpleOracle {
address internal immutable weth;
address internal immutable uniswapV2Factory;
constructor(address _uniswapRouter) {
weth = IUniswapV2Router01(_uniswapRouter).WETH();
uniswapV2Factory = IUniswapV2Router01(_uniswapRouter).factory();
}
function inToken(address _token, uint256 _ethAmount) internal view returns (uint256) {
(uint256 wethReserve, uint256 tokenReserve) = getReservesForTokenPool(_token);
return _ethAmount * tokenReserve / wethReserve;
}
function getReservesForTokenPool(address _token) internal view returns (uint256 wethReserve, uint256 tokenReserve) {
if (weth < _token) {
address pair = getPairForSorted(weth, _token);
(wethReserve, tokenReserve,) = IUniswapV2Pair(pair).getReserves();
} else {
address pair = getPairForSorted(_token, weth);
(tokenReserve, wethReserve,) = IUniswapV2Pair(pair).getReserves();
}
require(wethReserve != 0 && tokenReserve != 0, "SO: no liquidity");
}
function getPairForSorted(address tokenA, address tokenB) internal virtual view returns (address pair) {
pair = address(uint160(uint256(keccak256(abi.encodePacked(
hex'ff',
uniswapV2Factory,
keccak256(abi.encodePacked(tokenA, tokenB)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
)))));
}
}
// Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
/**
* @title Utils
* @notice Common utility methods used by modules.
*/
library Utils {
// ERC20, ERC721 & ERC1155 transfers & approvals
bytes4 private constant ERC20_TRANSFER = bytes4(keccak256("transfer(address,uint256)"));
bytes4 private constant ERC20_APPROVE = bytes4(keccak256("approve(address,uint256)"));
bytes4 private constant ERC721_SET_APPROVAL_FOR_ALL = bytes4(keccak256("setApprovalForAll(address,bool)"));
bytes4 private constant ERC721_TRANSFER_FROM = bytes4(keccak256("transferFrom(address,address,uint256)"));
bytes4 private constant ERC721_SAFE_TRANSFER_FROM = bytes4(keccak256("safeTransferFrom(address,address,uint256)"));
bytes4 private constant ERC721_SAFE_TRANSFER_FROM_BYTES = bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)"));
bytes4 private constant ERC1155_SAFE_TRANSFER_FROM = bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)"));
bytes4 private constant OWNER_SIG = 0x8da5cb5b;
/**
* @notice Helper method to recover the signer at a given position from a list of concatenated signatures.
* @param _signedHash The signed hash
* @param _signatures The concatenated signatures.
* @param _index The index of the signature to recover.
*/
function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(_signatures, add(0x20,mul(0x41,_index))))
s := mload(add(_signatures, add(0x40,mul(0x41,_index))))
v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)
}
require(v == 27 || v == 28, "Utils: bad v value in signature");
address recoveredAddress = ecrecover(_signedHash, v, r, s);
require(recoveredAddress != address(0), "Utils: ecrecover returned 0");
return recoveredAddress;
}
/**
* @notice Helper method to recover the spender from a contract call.
* The method returns the contract unless the call is to a standard method of a ERC20/ERC721/ERC1155 token
* in which case the spender is recovered from the data.
* @param _to The target contract.
* @param _data The data payload.
*/
function recoverSpender(address _to, bytes memory _data) internal pure returns (address spender) {
if(_data.length >= 68) {
bytes4 methodId;
// solhint-disable-next-line no-inline-assembly
assembly {
methodId := mload(add(_data, 0x20))
}
if(
methodId == ERC20_TRANSFER ||
methodId == ERC20_APPROVE ||
methodId == ERC721_SET_APPROVAL_FOR_ALL)
{
// solhint-disable-next-line no-inline-assembly
assembly {
spender := mload(add(_data, 0x24))
}
return spender;
}
if(
methodId == ERC721_TRANSFER_FROM ||
methodId == ERC721_SAFE_TRANSFER_FROM ||
methodId == ERC721_SAFE_TRANSFER_FROM_BYTES ||
methodId == ERC1155_SAFE_TRANSFER_FROM)
{
// solhint-disable-next-line no-inline-assembly
assembly {
spender := mload(add(_data, 0x44))
}
return spender;
}
}
spender = _to;
}
/**
* @notice Helper method to parse data and extract the method signature.
*/
function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) {
require(_data.length >= 4, "Utils: Invalid functionPrefix");
// solhint-disable-next-line no-inline-assembly
assembly {
prefix := mload(add(_data, 0x20))
}
}
/**
* @notice Checks if an address is a contract.
* @param _addr The address.
*/
function isContract(address _addr) internal view returns (bool) {
uint32 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
/**
* @notice Checks if an address is a guardian or an account authorised to sign on behalf of a smart-contract guardian
* given a list of guardians.
* @param _guardians the list of guardians
* @param _guardian the address to test
* @return true and the list of guardians minus the found guardian upon success, false and the original list of guardians if not found.
*/
function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) {
if (_guardians.length == 0 || _guardian == address(0)) {
return (false, _guardians);
}
bool isFound = false;
address[] memory updatedGuardians = new address[](_guardians.length - 1);
uint256 index = 0;
for (uint256 i = 0; i < _guardians.length; i++) {
if (!isFound) {
// check if _guardian is an account guardian
if (_guardian == _guardians[i]) {
isFound = true;
continue;
}
// check if _guardian is the owner of a smart contract guardian
if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) {
isFound = true;
continue;
}
}
if (index < updatedGuardians.length) {
updatedGuardians[index] = _guardians[i];
index++;
}
}
return isFound ? (true, updatedGuardians) : (false, _guardians);
}
/**
* @notice Checks if an address is the owner of a guardian contract.
* The method does not revert if the call to the owner() method consumes more then 25000 gas.
* @param _guardian The guardian contract
* @param _owner The owner to verify.
*/
function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) {
address owner = address(0);
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr,OWNER_SIG)
let result := staticcall(25000, _guardian, ptr, 0x20, ptr, 0x20)
if eq(result, 1) {
owner := mload(ptr)
}
}
return owner == _owner;
}
/**
* @notice Returns ceil(a / b).
*/
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if (a % b == 0) {
return c;
} else {
return c + 1;
}
}
}
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.5.4 <0.9.0;
/**
* @title IWallet
* @notice Interface for the BaseWallet
*/
interface IWallet {
/**
* @notice Returns the wallet owner.
* @return The wallet owner address.
*/
function owner() external view returns (address);
/**
* @notice Returns the number of authorised modules.
* @return The number of authorised modules.
*/
function modules() external view returns (uint);
/**
* @notice Sets a new owner for the wallet.
* @param _newOwner The new owner.
*/
function setOwner(address _newOwner) external;
/**
* @notice Checks if a module is authorised on the wallet.
* @param _module The module address to check.
* @return `true` if the module is authorised, otherwise `false`.
*/
function authorised(address _module) external view returns (bool);
/**
* @notice Returns the module responsible for a static call redirection.
* @param _sig The signature of the static call.
* @return the module doing the redirection
*/
function enabled(bytes4 _sig) external view returns (address);
/**
* @notice Enables/Disables a module.
* @param _module The target module.
* @param _value Set to `true` to authorise the module.
*/
function authoriseModule(address _module, bool _value) external;
/**
* @notice Enables a static method by specifying the target module to which the call must be delegated.
* @param _module The target module.
* @param _method The static method signature.
*/
function enableStaticCall(address _module, bytes4 _method) external;
}
pragma solidity >=0.5.4 <0.9.0;
/**
* ERC20 contract interface.
*/
interface ERC20 {
function totalSupply() external view returns (uint);
function decimals() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
}
// SPDX-License-Identifier: MIT
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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted 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 < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(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 < 2**64, "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 < 2**32, "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 < 2**16, "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 < 2**8, "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 >= -2**127 && value < 2**127, "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 >= -2**63 && value < 2**63, "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 >= -2**31 && value < 2**31, "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 >= -2**15 && value < 2**15, "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 >= -2**7 && value < 2**7, "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) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
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;
}
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);
}
| * @notice Lets the owner cancel a pending guardian addition. @param _wallet The target wallet. @param _guardian The guardian./ | function cancelGuardianAddition(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) {
bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition"));
GuardianManagerConfig storage config = guardianConfigs[_wallet];
require(config.pending[id] > 0, "SM: unknown pending addition");
delete config.pending[id];
emit GuardianAdditionCancelled(_wallet, _guardian);
}
| 2,524,188 | [
1,
48,
2413,
326,
3410,
3755,
279,
4634,
11026,
2779,
2719,
18,
225,
389,
19177,
1021,
1018,
9230,
18,
225,
389,
24594,
2779,
1021,
11026,
2779,
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,
3755,
16709,
2779,
30296,
12,
2867,
389,
19177,
16,
1758,
389,
24594,
2779,
13,
3903,
1338,
16936,
5541,
1162,
10084,
24899,
19177,
13,
1338,
9434,
7087,
329,
24899,
19177,
13,
288,
203,
3639,
1731,
1578,
612,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
19177,
16,
389,
24594,
2779,
16,
315,
1289,
608,
7923,
1769,
203,
3639,
22809,
2779,
1318,
809,
2502,
642,
273,
11026,
2779,
8062,
63,
67,
19177,
15533,
203,
3639,
2583,
12,
1425,
18,
9561,
63,
350,
65,
405,
374,
16,
315,
7303,
30,
5917,
4634,
2719,
8863,
203,
3639,
1430,
642,
18,
9561,
63,
350,
15533,
203,
3639,
3626,
22809,
2779,
30296,
21890,
24899,
19177,
16,
389,
24594,
2779,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-05
*/
// File: contracts/interfaces/ILayerZeroUserApplicationConfig.sol
pragma solidity >=0.5.0;
interface ILayerZeroUserApplicationConfig {
// @notice set the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _configType - type of configuration. every messaging library has its own convention.
// @param _config - configuration in the bytes. can encode arbitrary content.
function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
// @notice set the send() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setSendVersion(uint16 _version) external;
// @notice set the lzReceive() LayerZero messaging library version to _version
// @param _version - new messaging library version
function setReceiveVersion(uint16 _version) external;
// @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
// @param _srcChainId - the chainId of the source chain
// @param _srcAddress - the contract address of the source contract at the source chain
function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
}
// File: contracts/interfaces/ILayerZeroEndpoint.sol
pragma solidity >=0.5.0;
interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
// @notice send a LayerZero message to the specified address at a LayerZero endpoint.
// @param _dstChainId - the destination chain identifier
// @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
// @param _payload - a custom bytes payload to send to the destination contract
// @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
// @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
// @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
// @notice used by the messaging library to publish verified payload
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source contract (as bytes) at the source chain
// @param _dstAddress - the address on destination chain
// @param _nonce - the unbound message ordering nonce
// @param _gasLimit - the gas limit for external contract execution
// @param _payload - verified payload to send to the destination contract
function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
// @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
// @notice get the outboundNonce from this source chain which, consequently, is always an EVM
// @param _srcAddress - the source chain contract address
function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
// @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
// @param _dstChainId - the destination chain identifier
// @param _userApplication - the user app address on this EVM chain
// @param _payload - the custom message to send over LayerZero
// @param _payInZRO - if false, user app pays the protocol fee in native token
// @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
// @notice get this Endpoint's immutable source identifier
function getChainId() external view returns (uint16);
// @notice the interface to retry failed message on this Endpoint destination
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
// @param _payload - the payload to be retried
function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
// @notice query if any STORED payload (message blocking) at the endpoint.
// @param _srcChainId - the source chain identifier
// @param _srcAddress - the source chain contract address
function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
// @notice query if the _libraryAddress is valid for sending msgs.
// @param _userApplication - the user app address on this EVM chain
function getSendLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the _libraryAddress is valid for receiving msgs.
// @param _userApplication - the user app address on this EVM chain
function getReceiveLibraryAddress(address _userApplication) external view returns (address);
// @notice query if the non-reentrancy guard for send() is on
// @return true if the guard is on. false otherwise
function isSendingPayload() external view returns (bool);
// @notice query if the non-reentrancy guard for receive() is on
// @return true if the guard is on. false otherwise
function isReceivingPayload() external view returns (bool);
// @notice get the configuration of the LayerZero messaging library of the specified version
// @param _version - messaging library version
// @param _chainId - the chainId for the pending config change
// @param _userApplication - the contract address of the user application
// @param _configType - type of configuration. every messaging library has its own convention.
function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
// @notice get the send() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getSendVersion(address _userApplication) external view returns (uint16);
// @notice get the lzReceive() LayerZero messaging library version
// @param _userApplication - the contract address of the user application
function getReceiveVersion(address _userApplication) external view returns (uint16);
}
// File: contracts/interfaces/ILayerZeroReceiver.sol
pragma solidity >=0.5.0;
interface ILayerZeroReceiver {
// @notice LayerZero endpoint will invoke this function to deliver the message on the destination
// @param _srcChainId - the source endpoint identifier
// @param _srcAddress - the source sending contract address from the source chain
// @param _nonce - the ordered message nonce
// @param _payload - the signed payload is the UA bytes has encoded to be sent
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), '.json')) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/NonblockingReceiver.sol
pragma solidity ^0.8.6;
abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver {
ILayerZeroEndpoint internal endpoint;
struct FailedMessages {
uint payloadLength;
bytes32 payloadHash;
}
mapping(uint16 => mapping(bytes => mapping(uint => FailedMessages))) public failedMessages;
mapping(uint16 => bytes) public trustedRemoteLookup;
event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload);
function lzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) external override {
require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security
require(_srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]),
"NonblockingReceiver: invalid source sending contract");
// try-catch all errors/exceptions
// having failed messages does not block messages passing
try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) {
// do nothing
} catch {
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages(_payload.length, keccak256(_payload));
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
}
}
function onLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) public {
// only internal transaction
require(msg.sender == address(this), "NonblockingReceiver: caller must be Bridge.");
// handle incoming message
_LzReceive( _srcChainId, _srcAddress, _nonce, _payload);
}
// abstract function
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) virtual internal;
function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam) internal {
endpoint.send{value: msg.value}(_dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam);
}
function retryMessage(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload) external payable {
// assert there is message to retry
FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce];
require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message");
require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload");
// clear the stored message
failedMsg.payloadLength = 0;
failedMsg.payloadHash = bytes32(0);
// execute the message. revert if it fails again
this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
}
function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner {
trustedRemoteLookup[_chainId] = _trustedRemote;
}
}
// File: contracts/BETA.sol
pragma solidity ^0.8.7;
// XXXXXXXXXXXXXXXXXXXXXXXKc cKXXXXXXXKc cKXX0: :0XXXXXXXX0: :0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXXXKKKKKKKKKKKKK0c. cKXXXXXXXKl. c0KK0: c0XXXXXXXX0c :0KKKKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXKd,''''''''''''':dddxOKXXXXXXXXOxdddc''''cdddxOKXXXXXXXXKOxdddc''',oKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXKc :0XXXXXXXXXXXXXXXXXKc cKXXXXXXXXXXXXXXXXXXKc cKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// XXXXOddddc''''''''.. :0XXXXXXXKOxdddOKXXKc cKXXXXXXXKOxxddxOXXXKc cKXXXOdddddddddddddxOXXXXXXXXXXXXXXXXXXXXXXXX
// XXXK: :0KKKKKKK0; :0XXXXXXX0: :0XXKc cKXXXXXXXKc. .lKXXKc cKXXK: .lKXXXXXXXXXXXXXXXXXXXXXXX
// KKK0: :0XXXKKKK0: :0KKKKXXX0: :0KK0: c0KKKKXXXKc. .c0KK0c :0KK0: cKKKKXXXXXXKKKKKKKKKXXXXX
// ''',codddOKXXKd,,,,coddoc,,,,dKXXKOdddoc,,,'. .',,,oKXXKOxdddo:,,,,;clll:,,',codddddddo' .''',oKXXKd,''''',,,oKXXX
// cKXXXXXXXKc cKXXKc cKXXXXXXXKc :0XXXXXXXX0: ,kOOk; cKXXXXXXXKc :KXXKc :KXXX
// cKXXXXXXXKd;,,;dKXXKc 'loooooooo, ..''.. 'looooooooo:'''';cccc:,,,;dKXXXXXXXKd;,,'. 'looo:,,,,,,,,,:oooo
// cKXXXXXXXXXKKKKXXXXKc ;kOOx, :kkkk: c0KKKXXXXXXXXXXKKKK0: c0KKKKKKKKc
// cKKKKXXXXXXXXXXXKKKKc ;kkOx, :kOOk: cKXXXXKKKKKXXXXXXXX0: cKXXXXXXXKl.
// oooo:,,,;dKXXXXXXXKd;,,,:cccc. ,ooooooooo:'''';ccccccccccccccldOOOk: cKXXKd;,,;dKXXXXXXX0: 'loodOKXXXXXXXXOdooo
// XXX0: :0XXXXXXX0: ,kOOk; lKXXXXXXXKc :kOOOOOOOOOOOOOOOOOOk: cKXX0: :KXXXXXXX0: :0XXXXXXXXXXXXXXXXXX
// XXXKo,',,:odddddddo:'..';cllc:,'';dKXXXXXXXKd,'',:cllldkOOkdlllllllllc;'..':oddo:,'',oKXXXOdddo' :0XXKOddddOXXXXXXXXX
// XXXXXKKKKc :kkkk: c0KKKXXXXXXXXXXKKKK0: ;kOOk;. ,xkkx; c0KKKKXXXKc :0XXKc .lKXXXXXXXX
// XXXXXXXXKl. :xkkx; cKXXXXXXXXKKKKKKXXX0: ,xkkx;. ;xkkx; c0KKKKKKK0: :OKK0c .lKXXXKKKKK
// XXXXXXXXXOxdddddddo:..... :KXXXXXXXKd,'',dKXX0: ....:oddddddddd:'...;llll;'''''''''. 'llll:''',cdddxOXXXKd,'''
// XXXXXXXXXXXXXXXXXXK: cKXXXXXXXKc cKXX0: c0KXXXXXXXKc ;kOOk, :kOOk: cKXXXXXXXKl
// XXXXXXXXXOxdddddddd:''''. ,oddxOXXXKd,'',cdddo' ..'',o0KXXXXXXXKd,''':lllc. ..'''''''':lllc' ,oddddddddc,'''
// XXXXXXXXKl. c0KK0c .lKXXXKKKK0c ;OKKKKXXXXXXXXXXKKKK0c ;OKKKKKKKO: :0KKK
// XXXXXKKKKc cKKKKc c0KKKKKKK0c :0XXXXXXXXXKKKKKKXXXKc :0KKKKXXX0: :KXXX
// XXXKo,,,,:odddddddo:,'''. .cllc:,,',,,,,,:cllc. :0XXXXXXXXKo,,,,oKXXKc ,oddoc,,,,dKXXKOdddo, ,oddddddddOXXXX
// XXXK: :0XXXXXXX0: ;kOOk, ;kOOk, :0XXXXXXXX0: :0XXKc cKXXKl cKXXXXXXXKc cKXXXXXXXXXXXXX
// oooo:,,,;oKXXKkdooo:,,,,. ;kOOkc'''''''''lkOOkc'''':ooodOKKXXKd;,,,coool' cKXXKx;,,;dKXXXXXXXKc cKXXXXXXXXXXXXX
// cKKKKXXXXKc cKKKKc ;kOOOOOkkkOkkOOOOOOOOkkOk: c0KXXXXKKKKc cKXXXXKKKKXXXXXXXXXKc cKXXXXXXXXXXXXX
// cKXXXXXXXKc .lKXXKl ;kOOOOOOOOOOOOOOOOOOOOOOk: cO0KKKKKKKKc cKKKKXXXXXXXXXXXKKKKc cKXKXXXXXXXXXXX
// lKXXXXXXXKOdoodOXXXKc ;kOOOOOOOOOOOOOOOOOOOOOOOdlccc:,,,,,,,,,,;ccccccccc:,,,;dKXXXXXXXKd;,,,:cccc:,,,;dXXXXXXXXX
// lKXXXXXXXXXXXXXXXXXKc ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; ,kOOOOOOOk, :0XXXXXXX0: ,kOOk; cKXXXXXXXX
// '',,codddOKXXXXXXXKkdddo:'..'lkOOOOOOOOOOOOOOOOOOOOOOOOOOOkl,'.......'ckOOOOOOOkc'..':odddddddo:'..'ckOOk; cKXXXXXXXX
// KKK0: :0XXXXXXX0: ,xkkkOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOkkkkkkkkkkkOOOOOOOOOOkkkk: :kkkkOOOOk; cKXXXXXXXX
// XXXK: :OKKKKKKKO: ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOOkkkkkkkkkkkkOOOOOOOOOOOOOOOOOOk: :kOOOkkkkx; .lKXXXXXXXX
// XXXXOddddc''''''''':lllldOOOOOOOOOOOOOOOOOOOOOOOOOOOOOl'........'lOOOOOOOOOOOOOOOOOOOxlllllllloxOOOkl'...:dddxOXXXXXXXXX
// XXXXXXXXKc :kOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO: :OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk: cKXXXXXXXXXXXXX
// XXXXXXXXKd,'''''''':llllllllldOOOkdlllldkOOOOOOOkdllll' 'lllldkOOOOOOOOOOOOOOOOOOdlllllllll' cKXXXXXXXXXXXXX
// XXXXXXXXXXKKKKKKKK0: ;kOOk; ;kOOOOOOOk; ;kOOOOOOOOOOOOOOOOOk; cKXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXK: ;xkkx, ,xkkkkkkkx, ,xkkkkOOOOOOOOOOOOOk; :0KKKXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXK: .cllc;'..',,,,,''......... ....'lkOOOOOOOOOOOOOdlllllllllllllc;,'',dKXXXXXXXX
// XXXXXXXXXXXXXXXXXX0: ,kOOk; 'cllc' ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXKo,,,,;cccc,....;cllc;.............. ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc 'clllllllllcllcclllcccllc' ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc .cllclllllllllllllllllllc' ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc .........,clllllllllllll:,,,,. ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc .clllllllllllllllllc. ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc .........'',,,,,,,,,,,,,,:lllc,..... ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc ;xkkkkkkkk; .cllllccccc. ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc ;kOOOOOOOk: .:cccccccc:. ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc ;kOOOOOOOOxllllllllc. .......... .cllldOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXKc ;kOOOOOOOOOOOOOOOOOk, ,kOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXd,''';llllxOOOOOOOOOOOOOkc..... .....ckOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXKKK0: :kOOOOOOOOOOOOOkkkkk; ;kkkkkOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXKc :kkkkkkkkkOOOOOOOOOk: :kOOOOOOOOOOOOOOOOOOOOOOOOkkkkkkkkkkkkkx; lKXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXOdddo:'.'.....'lkOOOOOOOOxllllllllllxOOOOOOOOOOOOOOOOOOOOOOOkl'............':odddOXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXK: ;kOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXKd,,,,,,,,,:cccldOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; .,,,,,,,,;dKXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXKXXXXXK: :kOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXKc :kOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXKc :kOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXKc :kOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXKc :kOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk; cKXXXXXXXXXXXXXXXXXXXXXXX
contract BETA is Ownable, ERC721, NonblockingReceiver {
address public _owner;
string private baseURI;
uint256 nextTokenId = 0;
uint256 nextReserveTokenId = 2700;
uint256 MAX_PUBLIC_MINT = 2700;
uint256 MAX_MINT_ETHEREUM = 3000;
uint gasForDestinationLzReceive = 350000;
constructor(string memory baseURI_, address _layerZeroEndpoint) ERC721("BETA", "BETA") {
_owner = msg.sender;
endpoint = ILayerZeroEndpoint(_layerZeroEndpoint);
baseURI = baseURI_;
}
// owner reserve function
function reserve(address _receiverAddress, uint8 numTokens) external onlyOwner {
require(nextReserveTokenId + numTokens <= MAX_MINT_ETHEREUM, "Greedy devs trying to take more than available!");
for (uint j = 0; j < numTokens; j++) {
_safeMint(_receiverAddress, ++nextReserveTokenId);
}
}
// mint function
// you can choose to mint 1 or 2
// mint is free, but payments are accepted
function mint(uint8 numTokens) external payable {
require(numTokens < 3, "BETA: Max 2 NFTs per transaction");
require(nextTokenId + numTokens <= MAX_PUBLIC_MINT, "BETA: Mint exceeds supply");
_safeMint(msg.sender, ++nextTokenId);
if (numTokens == 2) {
_safeMint(msg.sender, ++nextTokenId);
}
}
// This function transfers the nft from your address on the
// source chain to the same address on the destination chain
function traverseChains(uint16 _chainId, uint tokenId) public payable {
require(msg.sender == ownerOf(tokenId), "You must own the token to traverse");
require(trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel");
// burn NFT, eliminating it from circulation on src chain
_burn(tokenId);
// abi.encode() the payload with the values to send
bytes memory payload = abi.encode(msg.sender, tokenId);
// encode adapterParams to specify more gas for the destination
uint16 version = 1;
bytes memory adapterParams = abi.encodePacked(version, gasForDestinationLzReceive);
// get the fees we need to pay to LayerZero + Relayer to cover message delivery
// you will be refunded for extra gas paid
(uint messageFee, ) = endpoint.estimateFees(_chainId, address(this), payload, false, adapterParams);
require(msg.value >= messageFee, "BETA: msg.value not enough to cover messageFee. Send gas for message fees");
endpoint.send{value: msg.value}(
_chainId, // destination chainId
trustedRemoteLookup[_chainId], // destination address of nft contract
payload, // abi.encoded()'ed bytes
payable(msg.sender), // refund address
address(0x0), // 'zroPaymentAddress' unused for this
adapterParams // txParameters
);
}
function setBaseURI(string memory URI) external onlyOwner {
baseURI = URI;
}
function donate() external payable {
// thank you
}
function withdrawAll() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
// This allows the devs to receive kind donations
function withdrawAmount(uint amt) external onlyOwner {
(bool sent, ) = payable(_owner).call{value: amt}("");
require(sent, "META: Failed to withdraw Ether");
}
// just in case this fixed variable limits us from future integrations
function setGasForDestinationLzReceive(uint newVal) external onlyOwner {
gasForDestinationLzReceive = newVal;
}
// ------------------
// Internal Functions
// ------------------
function _LzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) override internal {
// decode
(address toAddr, uint tokenId) = abi.decode(_payload, (address, uint));
// mint the tokens back into existence on destination chain
_safeMint(toAddr, tokenId);
}
function _baseURI() override internal view returns (string memory) {
return baseURI;
}
} | This allows the devs to receive kind donations | function withdrawAmount(uint amt) external onlyOwner {
require(sent, "META: Failed to withdraw Ether");
}
| 6,708,052 | [
1,
2503,
5360,
326,
4461,
87,
358,
6798,
3846,
2727,
1012,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
6275,
12,
11890,
25123,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
7569,
16,
315,
19294,
30,
11175,
358,
598,
9446,
512,
1136,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x729F4E044Ed74fC0Ec95Df4D0bCE7Ae247058404/sources/Investment.sol | cerca che il nuovo investitore non sia un debitoreinserisce il nuovo investirore nella mappa(lista) degli investirori inizialiazza ongoing inv a false perche non ha mai investito | function createEvaluator(string name) public{
require(balances[msg.sender] >= 10 ether, 'Minimum amount to evaluate prject => 10 ether');
Evaluator storage evaluator = evaluator;
evaluator.name = name;
evaluator.evaluator_public_key = msg.sender;
evaluator.EXISTS = true;
evaluators[msg.sender] = evaluator;
hasOngoingEvaluate[msg.sender] = false;
}
| 8,942,546 | [
1,
2750,
5353,
19315,
14254,
9244,
1527,
83,
2198,
395,
305,
479,
1661,
272,
1155,
640,
443,
3682,
479,
267,
550,
291,
311,
14254,
9244,
1527,
83,
2198,
395,
11373,
266,
290,
1165,
69,
852,
8774,
12,
1098,
69,
13,
5843,
549,
2198,
395,
481,
280,
77,
316,
452,
649,
1155,
6378,
69,
30542,
2198,
279,
629,
1534,
18706,
1661,
10677,
312,
10658,
2198,
395,
11250,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
752,
15876,
12,
1080,
508,
13,
1071,
95,
203,
3639,
2583,
12,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
1728,
225,
2437,
16,
296,
13042,
3844,
358,
5956,
846,
937,
516,
1728,
225,
2437,
8284,
203,
3639,
31956,
2502,
18256,
273,
18256,
31,
203,
3639,
18256,
18,
529,
273,
508,
31,
203,
3639,
18256,
18,
14168,
639,
67,
482,
67,
856,
273,
1234,
18,
15330,
31,
203,
3639,
18256,
18,
21205,
273,
638,
31,
203,
3639,
3765,
3062,
63,
3576,
18,
15330,
65,
273,
18256,
31,
203,
3639,
711,
1398,
8162,
15369,
63,
3576,
18,
15330,
65,
273,
629,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
// BottlenoseToken with Governance.
contract NarwhalToken is ERC20, Ownable, ERC20Burnable {
using SafeMath for uint256;
// Burn address
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
uint256 private _cap;
// Max transfer amount rate in basis points. (default is 1% of total supply)
uint16 public maxTransferAmountRate = 100;
// Min value of the max transfer amount rate. (0.5%)
uint16 public constant maxTransferMinRate = 50;
// Addresses that excluded from antiWhale
mapping(address => bool) private _excludedFromAntiWhale;
// Is the transfer enabled? (False by default)
bool public isTransactionEnabled = false;
// Blacklisted addresses
mapping(address => bool) private blackList;
// anti-bot end block
uint256 public antiBotBlock;
// The duration that the anti-bot function last: 200 blocks ~ 10mins (from launch)
uint256 public constant ANTI_BOT_TIME = 200;
// Events
event OperatorTransferred(address indexed previousOperator, address indexed newOperator);
event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
modifier antiWhale(address sender, address recipient, uint256 amount) {
if (maxTransferAmount() > 0) {
if (_excludedFromAntiWhale[sender] == false && _excludedFromAntiWhale[recipient] == false) {
require(amount <= maxTransferAmount(), "TOKEN::antiWhale: Transfer amount exceeds the maxTransferAmount");
}
}
_;
}
/**
* @dev Blocks transaction before launch, so can inject liquidity before launch
*/
modifier blockTransaction(address sender) {
if (isTransactionEnabled == false) {
require(sender == owner(), "TOKEN::blockTransaction: Transfers can only be done by operator.");
}
_;
}
modifier antiBot(address recipient) {
if (isTransactionEnabled && block.number <= antiBotBlock) {
require(balanceOf(recipient) <= maxTransferAmount(), "TOKEN:: antiBot: Suspected bot activity");
}
_;
}
/**
* @notice Constructs the BottlenoseToken contract.
*/
constructor(uint256 nCap) public ERC20("Narwhal Token", "NAR") {
require(nCap > 0, "GovernanceToken: cap is 0");
_cap = nCap;
_excludedFromAntiWhale[msg.sender] = true;
_excludedFromAntiWhale[address(0)] = true;
_excludedFromAntiWhale[address(this)] = true;
_excludedFromAntiWhale[BURN_ADDRESS] = true;
// Setup LP pools wtih 10,000 tokens @ $2k for 0.2
_mint(msg.sender, 10000000000000000000000);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
require(ERC20.totalSupply() + _amount <= cap(), "GovernanceToken: cap exceeded");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/// @dev overrides transfer function to meet tokenomics of BTN
function _transfer(address sender, address recipient, uint256 amount) internal virtual override
blockTransaction(sender) antiWhale(sender, recipient, amount) antiBot(recipient) {
require(blackList[sender] == false,"TOKEN::transfer: You're blacklisted");
super._transfer(sender, recipient, amount);
}
/**
* @dev Returns the max transfer amount.
*/
function maxTransferAmount() public view returns (uint256) {
return totalSupply().mul(maxTransferAmountRate).div(10000);
}
/**
* @dev Returns the address is excluded from antiWhale or not.
*/
function isExcludedFromAntiWhale(address _account) public view returns (bool) {
return _excludedFromAntiWhale[_account];
}
/**
* @dev Update the max transfer amount rate.
* Can only be called by the current operator.
*/
function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOwner {
require(_maxTransferAmountRate <= 10000, "TOKEN::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
require(_maxTransferAmountRate >= maxTransferMinRate,"TOKEN::updateMaxTransferAmountRate: Max transfer amount rate must be grater than min rate");
emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
maxTransferAmountRate = _maxTransferAmountRate;
}
/**
* @dev Exclude or include an address from antiWhale.
* Can only be called by the current operator.
*/
function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOwner {
_excludedFromAntiWhale[_account] = _excluded;
}
/**
* @dev Enable transactions.
* Can only be called once by the current operator.
*/
function enableTransaction() public onlyOwner {
require(isTransactionEnabled == false,"TOKEN::enableTransaction: This meothod can only be called once");
isTransactionEnabled = true;
antiBotBlock = block.number.add(ANTI_BOT_TIME);
}
/**
* @dev Exclude or include an address from blackList.
*/
function addToBlackList(address _account, bool _excluded) public onlyOwner {
blackList[_account] = _excluded;
}
/**
* @dev Returns the address is excluded from blackList or not.
*/
function isBlackListed(address _account) public view returns (bool) {
return blackList[_account];
}
// 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
/// @dev 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 => uint256) 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, uint256 previousBalance, uint256 newBalance);
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @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,
uint256 nonce,
uint256 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), "TOKEN::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TOKEN::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "TOKEN::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, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BTNs (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, "TOKEN::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
} | * @dev Enable transactions. Can only be called once by the current operator./ | function enableTransaction() public onlyOwner {
require(isTransactionEnabled == false,"TOKEN::enableTransaction: This meothod can only be called once");
isTransactionEnabled = true;
antiBotBlock = block.number.add(ANTI_BOT_TIME);
}
| 12,787,097 | [
1,
8317,
8938,
18,
4480,
1338,
506,
2566,
3647,
635,
326,
783,
3726,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4237,
3342,
1435,
1071,
1338,
5541,
288,
203,
202,
202,
6528,
12,
291,
3342,
1526,
422,
629,
10837,
8412,
2866,
7589,
3342,
30,
1220,
1791,
10370,
369,
848,
1338,
506,
2566,
3647,
8863,
203,
3639,
353,
3342,
1526,
273,
638,
31,
203,
202,
202,
970,
77,
6522,
1768,
273,
1203,
18,
2696,
18,
1289,
12,
6856,
45,
67,
38,
1974,
67,
4684,
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
] |
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "./NFTBond.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
/**
* @title ERC20NFTBond
* @dev Contains functions related to buying and liquidating bonds,
* and borrowing and returning funds when the principal is ERC20 token
* @author Ethichub
*/
contract ERC20NFTBond is NFTBond {
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable private principalToken;
IERC20Upgradeable private collateralToken;
struct NFTParams {
string name;
string symbol;
string baseUri;
}
function initialize(
address _principalToken,
address _collateralToken,
NFTParams calldata _nftParams,
address _accessManager,
uint256[] calldata _interests,
uint256[] calldata _maturities
)
external initializer {
principalToken = IERC20Upgradeable(_principalToken);
collateralToken = IERC20Upgradeable(_collateralToken);
__NFTBond_init(_nftParams.name, _nftParams.symbol, _nftParams.baseUri);
__CollateralizedBondGranter_init(_collateralToken);
__InterestParameters_init(_interests, _maturities);
__AccessManaged_init(_accessManager);
}
/**
* @dev External function to buy a bond and returns the tokenId of the bond
* when the contract is active
* @param tokenUri string
* @param beneficiary address
* @param maturity uint256
* @param principal uint256
* @param nftHash bytes32
* @param setApprove bool
* @param nonce uint256
* @param signature bytes
*/
function buyBond(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal,
bytes32 nftHash,
bool setApprove,
uint256 nonce,
bytes memory signature
)
external whenNotPaused returns (uint256) {
return super._buyBond(tokenUri, beneficiary, maturity, principal, nftHash, setApprove, nonce, signature);
}
/**
* @dev External function to redeem a bond and returns the amount of the bond
*/
function redeemBond(uint256 tokenId) external returns (uint256) {
return super._redeemBond(tokenId);
}
function principalTokenAddress() external view returns (address) {
return address(principalToken);
}
function pause() external onlyRole(PAUSER) {
_pause();
}
function unpause() external onlyRole(PAUSER) {
_unpause();
}
/**
* @dev Transfers from the buyer to this contract the principal token amount
*/
function _beforeBondPurchased(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal
)
internal override {
super._beforeBondPurchased(tokenUri, beneficiary, maturity, principal);
principalToken.safeTransferFrom(beneficiary, address(this), principal);
}
/**
* @dev Transfers to the owner of the bond the amount of the bond when the contract has
* liquidity, if not will send the correspondent amount of collateral
*/
function _afterBondRedeemed(
uint256 tokenId,
uint256 amount,
address beneficiary
)
internal override {
Bond memory bond = bonds[tokenId];
super._afterBondRedeemed(tokenId, amount, beneficiary);
if (principalToken.balanceOf(address(this)) < amount) {
uint256 porcentageOfCollateral = 100 - (principalToken.balanceOf(address(this)) * 100 / amount);
uint256 amountOfCollateral = (bond.principal * porcentageOfCollateral / 100) * collateralMultiplier;
principalToken.safeTransfer(beneficiary, principalToken.balanceOf(address(this)));
if (collateralToken.balanceOf(address(this)) < amountOfCollateral) {
collateralToken.safeTransfer(beneficiary, collateralToken.balanceOf(address(this)));
} else {
collateralToken.safeTransfer(beneficiary, amountOfCollateral);
}
} else {
principalToken.safeTransfer(beneficiary, amount);
}
}
/**
* @dev Transfers to the recipient the amount of liquidity available in this contract
*/
function _beforeRequestLiquidity(address destination, uint256 amount) internal override {
principalToken.safeTransfer(destination, amount);
super._beforeRequestLiquidity(destination, amount);
}
/**
* @dev Transfers from the borrower the amount of liquidity borrowed
*/
function _afterReturnLiquidity(address origin, uint256 amount) internal override {
super._afterReturnLiquidity(origin, amount);
principalToken.safeTransferFrom(origin, address(this), amount);
}
function _pause() internal override {
super._pause();
}
function _unpause() internal override {
super._unpause();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "../token/NFT.sol";
import "../bond/CollateralizedBondGranter.sol";
import "../borrowing/LiquidityRequester.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
/**
* @title NFTBond
* @dev Contains functions related to buying and liquidating bonds, and borrowing and returning funds
* @author Ethichub
*/
abstract contract NFTBond is NFT, CollateralizedBondGranter, LiquidityRequester, PausableUpgradeable {
function __NFTBond_init(
string calldata _name,
string calldata _symbol,
string calldata _baseUri
)
internal initializer {
__NFT_init(_name, _symbol, _baseUri);
}
/**
* @dev Returns updated totalBorrowed
* @param origin address of sender
* @param amount uint256 in wei
*/
function returnLiquidity(address origin, uint256 amount) public payable virtual override returns (uint256) {
_beforeReturnLiquidity(origin);
super.returnLiquidity(origin, amount);
_afterReturnLiquidity(origin, amount);
return totalBorrowed;
}
/**
* @dev Requests totalBorrowed
* @param destination address of recipient
* @param amount uint256 in wei
*/
function requestLiquidity(address destination, uint256 amount) public override whenNotPaused returns (uint256) {
_beforeRequestLiquidity(destination, amount);
super.requestLiquidity(destination, amount);
return totalBorrowed;
}
/**
* @dev Returns assigned tokenId of the bond
*/
function _buyBond(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal,
bytes32 nftHash,
bool setApprove,
uint256 nonce,
bytes memory signature
)
internal returns (uint256) {
require(msg.sender == beneficiary, "NFTBond::Beneficiary != sender");
_beforeBondPurchased(tokenUri, beneficiary, maturity, principal);
uint256 tokenId = _safeMintBySig(tokenUri, beneficiary, nftHash, setApprove, nonce, signature);
super._issueBond(tokenId, maturity, principal);
_afterBondPurchased(tokenUri, beneficiary, maturity, principal, tokenId);
return tokenId;
}
/**
* @dev Returns the amunt that corresponds to the bond
*/
function _redeemBond(uint256 tokenId) internal virtual override returns (uint256) {
uint256 amount = super._redeemBond(tokenId);
address beneficiary = ownerOf(tokenId);
_afterBondRedeemed(tokenId, amount, beneficiary);
return amount;
}
function _beforeBondPurchased(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal
) internal virtual {}
function _afterBondPurchased(
string calldata tokenUri,
address beneficiary,
uint256 maturity,
uint256 principal,
uint256 tokenId
) internal virtual {}
function _beforeBondRedeemed(uint256 tokenId, uint256 value) internal virtual {}
function _afterBondRedeemed(uint256 tokenId, uint256 value, address beneficiary) internal virtual {}
function _beforeRequestLiquidity(address destination, uint256 amount) internal virtual {}
function _afterRequestLiquidity(address destination) internal virtual {}
function _beforeReturnLiquidity(address origin) internal virtual {}
function _afterReturnLiquidity(address origin, uint256 amount) internal virtual {}
uint256[49] private __gap;
}
// 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);
}
// 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: AGPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "../access/AccessManagedUpgradeable.sol";
abstract contract NFT is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable, AccessManagedUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _tokenIdCounter;
string private _baseTokenURI;
mapping(uint256 => bool) private _nonces;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function __NFT_init(
string calldata _name,
string calldata _symbol,
string calldata _baseUri
)
internal initializer {
__ERC721_init(_name, _symbol);
__ERC721Enumerable_init();
__ERC721URIStorage_init();
__ERC721Burnable_init();
__UUPSUpgradeable_init();
_setBaseURI(_baseUri);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function _safeMint(address to, string calldata uri) internal returns (uint256) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_setTokenURI(tokenId, uri);
return tokenId;
}
function _safeMintBySig (string calldata uri, address to, bytes32 nftHash, bool setApprove, uint256 nonce, bytes memory signature) internal returns (uint256) {
bytes32 messageHash = keccak256(abi.encode(uri, to, nftHash, address(this), setApprove, nonce, block.chainid));
bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash));
(bytes32 r, bytes32 s, uint8 v) = _splitSignature(signature);
address miningSigner = ecrecover(ethSignedMessageHash, v, r, s);
require(_hasRole(MINTER, miningSigner), "NFT::Invalid Signature");
return _safeMint(to, uri);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER)
override
{}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
{
super._burn(tokenId);
}
function _setBaseURI(string calldata _baseUri) private {
_baseTokenURI = _baseUri;
}
function _splitSignature(bytes memory _sig) private pure returns (bytes32 r, bytes32 s, uint8 v) {
require(_sig.length == 65, "Invalid Signature length");
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./BondGranter.sol";
/**
* @title CollateralizedBondGranter
* @dev This contract contains functions related to the emission or withdrawal of
* the bonds with collateral
* @author Ethichub
*/
abstract contract CollateralizedBondGranter is BondGranter {
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable private _collateralToken;
uint256 public collateralMultiplier;
uint256 public totalCollateralizedAmount;
mapping(uint256 => uint256) public collaterals;
event CollateralMultiplierUpdated(uint256 collateralMultiplier);
event CollateralAssigned(uint256 tokenId, uint256 collateralAmount);
event CollateralReleased(uint256 tokenId, uint256 collateralAmount);
event CollateralExcessRemoved(address indexed destination);
function __CollateralizedBondGranter_init(
address collateralToken
)
internal initializer {
collateralMultiplier = 5;
_collateralToken = IERC20Upgradeable(collateralToken);
}
function collateralTokenAddress() external view returns (address) {
return address(_collateralToken);
}
/**
* @dev Sets the number by which the amount of the collateral must be multiplied.
* In this version will be 5
* @param multiplierIndex uint256
*/
function setCollateralMultiplier(uint256 multiplierIndex) external onlyRole(COLLATERAL_BOND_SETTER) {
require(multiplierIndex > 0, "CollateralizedBondGranter::multiplierIndex is 0");
collateralMultiplier = multiplierIndex;
emit CollateralMultiplierUpdated(collateralMultiplier);
}
/**
* @dev Function to withdraw the rest of the collateral that remains in the contract
* to a specified address
* @param destination address
*/
function removeExcessOfCollateral(address destination) external onlyRole(COLLATERAL_BOND_SETTER) {
uint256 excessAmount = _collateralToken.balanceOf(address(this)) - totalCollateralizedAmount;
_collateralToken.safeTransfer(destination, excessAmount);
emit CollateralExcessRemoved(destination);
}
/**
* @dev Issues a bond with calculated collateral
* @param tokenId uint256
* @param maturity uint256 seconds
* @param principal uint256 in wei
*
* Requirement:
*
* - The contract must have enough collateral
*/
function _issueBond(
uint256 tokenId,
uint256 maturity,
uint256 principal
) internal override {
require(_hasCollateral(principal), "CBG::Not enough collateral");
super._issueBond(tokenId, maturity, principal);
uint256 collateralAmount = _calculateCollateralBondAmount(principal);
totalCollateralizedAmount = totalCollateralizedAmount + collateralAmount;
collaterals[tokenId] = collateralAmount;
emit CollateralAssigned(tokenId, collateralAmount);
}
/**
* @dev Updates totalCollateralizedAmount when a bond is redeemed
* @param tokenId uint256
*/
function _redeemBond(uint256 tokenId) internal virtual override returns (uint256) {
uint256 bondValue = super._redeemBond(tokenId);
uint256 collateralAmount = collaterals[tokenId];
totalCollateralizedAmount = totalCollateralizedAmount - collateralAmount;
emit CollateralReleased(tokenId, collateralAmount);
return bondValue;
}
/**
* @dev Returns the amount of collateral that links to the bond
* @param principal uint256
*/
function _calculateCollateralBondAmount(uint256 principal) internal view returns (uint256) {
return principal * collateralMultiplier;
}
/**
* @dev Return true if the balace of the contract minus totalCollateralizedAmount is greater or equal to
* the amount of the bond's collateral
* @param principal uint256
*/
function _hasCollateral(uint256 principal) internal view returns (bool) {
if (_collateralToken.balanceOf(address(this)) - totalCollateralizedAmount >= principal * collateralMultiplier) {
return true;
}
return false;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/ILiquidityRequester.sol";
import "../access/AccessManagedUpgradeable.sol";
import "../Roles.sol";
/**
* @title LiquidityRequester
* @dev Contains functions related to withdraw or return liquidity to the contract for borrowing
* Increments every time money is taking out for lending projects, decrements every time is returned
* @author Ethichub
*/
abstract contract LiquidityRequester is Initializable, ILiquidityRequester, AccessManagedUpgradeable {
uint256 public totalBorrowed;
event LiquidityRequested(uint256 totalBorrowed, address indexed destination);
event LiquidityReturned(uint256 totalBorrowed, address indexed destination);
/**
* @dev External function to withdraw liquidity for borrowing
* @param destination address of recipient
* @param amount uint256 in wei
*
* Requirement:
*
* - Only the role LIQUIDITY_REQUESTER can call this function
*/
function requestLiquidity(address destination, uint256 amount) public virtual override onlyRole(LIQUIDITY_REQUESTER) returns (uint256) {
return _requestLiquidity(destination, amount);
}
/**
* @dev External function to return liquidity from borrowing
* @param origin address of sender
* @param amount uint256 in wei
*/
function returnLiquidity(address origin, uint256 amount) public payable virtual override returns (uint256) {
return _returnLiquidity(origin, amount);
}
/**
* @dev Internal function to withdraw liquidity for borrowing
* Updates and returns totalBorrowed
* @param destination address of recipient
* @param amount uint256 in wei
*/
function _requestLiquidity(address destination, uint256 amount) internal returns (uint256) {
totalBorrowed = totalBorrowed + amount;
emit LiquidityRequested(totalBorrowed, destination);
return totalBorrowed;
}
/**
* @dev Internal function to return liquidity from borrowing
* Updates and returns totalBorrowed
* @param origin address of sender
* @param amount uint256 in wei
*/
function _returnLiquidity(address origin, uint256 amount) internal returns (uint256) {
totalBorrowed = totalBorrowed - amount;
emit LiquidityReturned(totalBorrowed, origin);
return totalBorrowed;
}
uint256[49] private __gap;
}
// 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 (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @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[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* @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[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal onlyInitializing {
}
function __ERC721URIStorage_init_unchained() internal onlyInitializing {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
/**
* @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/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal onlyInitializing {
}
function __ERC721Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
/**
* @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) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate that the this implementation remains valid after an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../Roles.sol";
abstract contract AccessManagedUpgradeable is Initializable {
IAccessControl private _accessControl;
event AccessManagerUpdated(address indexed newAddressManager);
modifier onlyRole(bytes32 role) {
require(_hasRole(role, msg.sender), "AccessManagedUpgradeable::Missing Role");
_;
}
function __AccessManaged_init(address manager) internal initializer {
_accessControl = IAccessControl(manager);
emit AccessManagerUpdated(manager);
}
function setAccessManager(address newManager) public onlyRole(DEFAULT_ADMIN_ROLE) {
_accessControl = IAccessControl(newManager);
emit AccessManagerUpdated(newManager);
}
function _hasRole(bytes32 role, address account) internal view returns (bool) {
return _accessControl.hasRole(role, account);
}
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 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// 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 (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
bytes32 constant DEFAULT_ADMIN_ROLE = bytes32(0);
bytes32 constant INTEREST_PARAMETERS_SETTER = keccak256("INTEREST_PARAMETERS_SETTER");
bytes32 constant COLLATERAL_BOND_SETTER = keccak256("COLLATERAL_BOND_SETTER");
bytes32 constant LIQUIDITY_REQUESTER = keccak256("LIQUIDITY_REQUESTER");
bytes32 constant PAUSER = keccak256("PAUSER");
bytes32 constant UPGRADER = keccak256("UPGRADER");
bytes32 constant MINTER = keccak256("MINTER");
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../utils/InterestCalculator.sol";
import "./InterestParameters.sol";
/**
* @title BondGranter
* @dev This contract contains functions related to the emission or withdrawal of the bonds
* @author Ethichub
*/
abstract contract BondGranter is Initializable, InterestParameters, InterestCalculator {
struct Bond {
uint256 mintingDate;
uint256 maturity;
uint256 principal;
uint256 interest;
bool redeemed;
}
mapping(uint256 => Bond) public bonds;
event BondIssued(uint256 tokenId, uint256 mintingDate, uint256 maturity, uint256 principal, uint256 interest);
event BondRedeemed(uint256 tokenId, uint256 redeemDate, uint256 maturity, uint256 withdrawn, uint256 interest);
/**
* @dev Assigns a bond with its parameters
* @param tokenId uint256
* @param maturity uint256 seconds
* @param principal uint256 in wei
*
* Requirements:
*
* - Principal amount can not be 0
* - Maturity must be greater than the first element of the set of interests
*/
function _issueBond(uint256 tokenId, uint256 maturity, uint256 principal) internal virtual {
require(principal > 0, "BondGranter::Principal is 0");
require(maturity >= maturities[0], "BondGranter::Maturity must be greater than the first interest");
uint256 interest = super.getInterestForMaturity(maturity);
bonds[tokenId] = Bond(block.timestamp, maturity, principal, interest, false);
emit BondIssued(tokenId, block.timestamp, maturity, principal, interest);
}
/**
* @dev Checks eligilibility to redeem the bond and returns its value
* @param tokenId uint256
*/
function _redeemBond(uint256 tokenId) internal virtual returns (uint256) {
Bond memory bond = bonds[tokenId];
require((bond.maturity + bond.mintingDate) < block.timestamp, "BondGranter::Can't redeem yet");
require(!bond.redeemed, "BondGranter::Already redeemed");
bonds[tokenId].redeemed = true;
emit BondRedeemed(tokenId, block.timestamp, bond.maturity, _bondValue(tokenId), bond.interest);
return _bondValue(tokenId);
}
/**
* @dev Returns the actual value of the bond with its interest
* @param tokenId uint256
*/
function _bondValue(uint256 tokenId) internal view virtual returns (uint256) {
Bond memory bond = bonds[tokenId];
return bond.principal + bond.principal * super.simpleInterest(bond.interest, bond.maturity) / 100 / 1000000000000000000;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "../interfaces/IInterestCalculator.sol";
abstract contract InterestCalculator is IInterestCalculator {
function simpleInterest(uint256 interest, uint256 maturity) public view virtual override returns (uint256) {
return _simpleInterest(interest, maturity);
}
function _simpleInterest(uint256 interest, uint256 maturity) internal view virtual returns (uint256) {
return maturity * interest;
}
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IInterestParameters.sol";
import "../access/AccessManagedUpgradeable.sol";
import "../Roles.sol";
/**
* @title InterestParameters
* @dev Contains functions related to interests and maturities for the bonds
* @author Ethichub
*/
abstract contract InterestParameters is Initializable, IInterestParameters, AccessManagedUpgradeable {
uint256[] public interests;
uint256[] public maturities;
uint256 public maxParametersLength;
function __InterestParameters_init(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
internal initializer {
maxParametersLength = 3;
_setInterestParameters(_interests, _maturities);
}
function setInterestParameters(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
external override onlyRole(INTEREST_PARAMETERS_SETTER) {
_setInterestParameters(_interests, _maturities);
}
function setMaxInterestParams(uint256 value) external override onlyRole(INTEREST_PARAMETERS_SETTER) {
_setMaxInterestParams(value);
}
function getInterestForMaturity(uint256 maturity) public view override returns (uint256) {
return _getInterestForMaturity(maturity);
}
/**
* @dev Sets the parameters of interests and maturities
* @param _interests set of interests per second in wei
* @param _maturities set of maturities in second
*
* Requirements:
*
* - The length of the array of interests can not be 0
* - The length of the array of interests can not be greater than maxParametersLength
* - The length of the array of interests and maturities must be the same
* - The value of maturities must be in ascending order
* - The values of interest and maturities can not be 0
*/
function _setInterestParameters(
uint256[] calldata _interests,
uint256[] calldata _maturities
)
internal {
require(_interests.length > 0, "InterestParameters::Interest must be greater than 0");
require(_interests.length <= maxParametersLength, "InterestParameters::Interest parameters is greater than max parameters");
require(_interests.length == _maturities.length, "InterestParameters::Unequal input length");
for (uint256 i = 0; i < _interests.length; ++i) {
if (i != 0) {
require(_maturities[i-1] < _maturities[i], "InterestParameters::Unordered maturities");
}
require(_interests[i] > 0, "InterestParameters::Can't set zero interest");
require(_maturities[i] > 0, "InterestParameters::Can't set zero maturity");
}
interests = _interests;
maturities = _maturities;
emit InterestParametersSet(interests, maturities);
}
/**
* @dev Sets the maximum length of interests and maturities parameters
* @param value uint256
*
* Requirement:
*
* - The length value can not be 0
*/
function _setMaxInterestParams(uint256 value) internal {
require(value > 0, "InterestParameters::Interest length is 0");
maxParametersLength = value;
emit MaxInterestParametersSet(value);
}
/**
* @dev Checks the interest correspondant to the maturity.
* Needs at least 1 maturity / interest pair.
* Returns interest per second
* @param maturity duration of the bond in seconds
*/
function _getInterestForMaturity(uint256 maturity) internal view returns (uint256) {
require(maturity >= maturities[0], "InterestParameters::Maturity must be greater than first interest");
for (uint256 i = interests.length - 1; i >= 0; --i) {
if (maturity >= maturities[i]) {
return interests[i];
}
}
return interests[0];
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
interface IInterestCalculator {
/**
* @dev Calculates interest per second that is int 1e18
* @param maturity duration of the bond in seconds
* @param interest per second
* @return simple interest per second that is int 1e18
*/
function simpleInterest(uint256 interest, uint256 maturity) external view returns (uint256);
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
interface IInterestParameters {
event InterestParametersSet(uint256[] interests, uint256[] maturities);
event MaxInterestParametersSet(uint256 value);
/**
* Set interests and maturities params, all in seconds
*/
function setInterestParameters(uint256[] calldata interests, uint256[] calldata maturities) external;
function setMaxInterestParams(uint256 value) external;
function getInterestForMaturity(uint256 maturity) external returns (uint256);
}
// SPDX-License-Identifier: GPLv3
pragma solidity 0.8.13;
interface ILiquidityRequester {
/**
* Increments every time money is taking out for lending projects, decrements every time is returned
*/
function requestLiquidity(address destination, uint256 amount) external returns (uint256);
function returnLiquidity(address origin, uint256 amount) external payable returns (uint256);
} | * @dev Checks eligilibility to redeem the bond and returns its value @param tokenId uint256/ | function _redeemBond(uint256 tokenId) internal virtual returns (uint256) {
Bond memory bond = bonds[tokenId];
require((bond.maturity + bond.mintingDate) < block.timestamp, "BondGranter::Can't redeem yet");
require(!bond.redeemed, "BondGranter::Already redeemed");
bonds[tokenId].redeemed = true;
emit BondRedeemed(tokenId, block.timestamp, bond.maturity, _bondValue(tokenId), bond.interest);
return _bondValue(tokenId);
}
| 19,031 | [
1,
4081,
415,
360,
330,
3628,
358,
283,
24903,
326,
8427,
471,
1135,
2097,
460,
225,
1147,
548,
2254,
5034,
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
] | [
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,
389,
266,
24903,
9807,
12,
11890,
5034,
1147,
548,
13,
2713,
5024,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
605,
1434,
3778,
8427,
273,
15692,
63,
2316,
548,
15533,
203,
3639,
2583,
12443,
26425,
18,
7373,
2336,
397,
8427,
18,
81,
474,
310,
1626,
13,
411,
1203,
18,
5508,
16,
315,
9807,
43,
2450,
387,
2866,
2568,
1404,
283,
24903,
4671,
8863,
203,
3639,
2583,
12,
5,
26425,
18,
266,
24903,
329,
16,
315,
9807,
43,
2450,
387,
2866,
9430,
283,
24903,
329,
8863,
203,
3639,
15692,
63,
2316,
548,
8009,
266,
24903,
329,
273,
638,
31,
203,
3639,
3626,
605,
1434,
426,
24903,
329,
12,
2316,
548,
16,
1203,
18,
5508,
16,
8427,
18,
7373,
2336,
16,
389,
26425,
620,
12,
2316,
548,
3631,
8427,
18,
2761,
395,
1769,
203,
3639,
327,
389,
26425,
620,
12,
2316,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.11;
/*
TenX Reseller
========================
Resells TenX tokens from the crowdsale before transfers are enabled.
Author: /u/Cintix
*/
// ERC20 Interface: https://github.com/ethereum/EIPs/issues/20
// Well, almost. PAY tokens throw on transfer failure instead of returning false.
contract ERC20 {
function transfer(address _to, uint _value);
function balanceOf(address _owner) constant returns (uint balance);
}
// Interface to TenX ICO Contract
contract MainSale {
function createTokens(address recipient) payable;
}
contract Reseller {
// Store the amount of PAY claimed by each account.
mapping (address => uint256) public pay_claimed;
// Total claimed PAY of all accounts.
uint256 public total_pay_claimed;
// The TenX Token Sale address.
MainSale public sale = MainSale(0xd43D09Ec1bC5e57C8F3D0c64020d403b04c7f783);
// TenX Token (PAY) Contract address.
ERC20 public token = ERC20(0xB97048628DB6B661D4C2aA833e95Dbe1A905B280);
// The developer address.
address developer = 0x4e6A1c57CdBfd97e8efe831f8f4418b1F2A09e6e;
// Buys PAY for the contract with user funds.
function buy() payable {
// Transfer received funds to the TenX crowdsale contract to buy tokens.
sale.createTokens.value(msg.value)(address(this));
}
// Withdraws PAY claimed by the user.
function withdraw() {
// Store the user's amount of claimed PAY as the amount of PAY to withdraw.
uint256 pay_to_withdraw = pay_claimed[msg.sender];
// Update the user's amount of claimed PAY first to prevent recursive call.
pay_claimed[msg.sender] = 0;
// Update the total amount of claimed PAY.
total_pay_claimed -= pay_to_withdraw;
// Send the user their PAY. Throws on failure to prevent loss of funds.
token.transfer(msg.sender, pay_to_withdraw);
}
// Claims PAY at a price determined by the block number.
function claim() payable {
// Verify ICO is over.
if(block.number < 3930000) throw;
// Calculate current sale price (PAY per ETH) based on block number.
uint256 pay_per_eth = (block.number - 3930000) / 10;
// Calculate amount of PAY user can purchase.
uint256 pay_to_claim = pay_per_eth * msg.value;
// Retrieve current PAY balance of contract.
uint256 contract_pay_balance = token.balanceOf(address(this));
// Verify the contract has enough remaining unclaimed PAY.
if((contract_pay_balance - total_pay_claimed) < pay_to_claim) throw;
// Update the amount of PAY claimed by the user.
pay_claimed[msg.sender] += pay_to_claim;
// Update the total amount of PAY claimed by all users.
total_pay_claimed += pay_to_claim;
// Send the funds to the developer instead of leaving them in the contract.
developer.transfer(msg.value);
}
// Default function. Called when a user sends ETH to the contract.
function () payable {
// If the user sent a 0 ETH transaction, withdraw their PAY.
if(msg.value == 0) {
withdraw();
}
// If the user sent ETH, claim PAY with it.
else {
claim();
}
}
} | Interface to TenX ICO Contract | contract MainSale {
function createTokens(address recipient) payable;
}
| 2,246,899 | [
1,
1358,
358,
399,
275,
60,
467,
3865,
13456,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
12740,
30746,
288,
203,
225,
445,
752,
5157,
12,
2867,
8027,
13,
8843,
429,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.13;
import "./openzeppelin/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "./openzeppelin/access/OwnableUpgradeable.sol";
import "./openzeppelin/security/PausableUpgradeable.sol";
import "./abstract/Generator.sol";
import "./abstract/Whitelist.sol";
import "./interface/ISerum.sol";
import "./interface/IMetadata.sol";
import "./interface/IBlueprint.sol";
error NotWhitelisted(address _account);
error InvalidMintAmount(uint256 _amount);
error LimitExceeded(address _account);
error SoldOut();
error GenerationLimit(uint256 _generation);
error NotEnoughEther(uint256 _given, uint256 _expected);
error InvalidBurnLength(uint256 _given, uint256 _expected);
error BurnNotOwned(address _sender, uint256 _tokenId);
error InvalidBurnGeneration(uint256 _given, uint256 _expected);
error BlueprintNotReady();
error EarlyMintIsEnabled();
error EarlyMintNotEnabled();
// LabGame V2.0
contract LabGame is ERC721EnumerableUpgradeable, OwnableUpgradeable, PausableUpgradeable, Generator, Whitelist {
uint256 constant GEN0_PRICE = 0 ether; // @since V2.0 Free mint
uint256 constant GEN1_PRICE = 5_000 ether;
uint256 constant GEN2_PRICE = 12_500 ether;
uint256 constant GEN3_PRICE = 45_000 ether;
uint256 constant GEN0_MAX = 1_111;
uint256 constant GEN1_MAX = 2_222;
uint256 constant GEN2_MAX = 3_333;
uint256 constant GEN3_MAX = 4_444;
uint256 constant WHITELIST_MINT_LIMIT = 2;
uint256 constant PUBLIC_MINT_LIMIT = 5;
uint256 constant EXTRA_MINT_LIMIT = 20;
uint256 constant MAX_TRAITS = 16;
uint256 constant TYPE_OFFSET = 9;
mapping(uint256 => uint256) tokens;
mapping(address => uint256) whitelistMints;
mapping(address => uint256) publicMints;
uint256 tokenOffset;
ISerum public serum;
IMetadata public metadata;
IBlueprint public blueprint;
uint8[][MAX_TRAITS] rarities;
uint8[][MAX_TRAITS] aliases;
bool public earlyMintEnabled; // @since V2.0
mapping(address => bool) public extraMintAccounts;
/**
* LabGame constructor
* @param _name ERC721 name
* @param _symbol ERC721 symbol
* @param _serum Serum contract address
* @param _metadata Metadata contract address
* @param _vrfCoordinator VRF Coordinator address
* @param _keyHash Gas lane key hash
* @param _subscriptionId VRF subscription id
* @param _callbackGasLimit VRF callback gas limit
*/
function initialize(
string memory _name,
string memory _symbol,
address _serum,
address _metadata,
address _vrfCoordinator,
bytes32 _keyHash,
uint64 _subscriptionId,
uint32 _callbackGasLimit
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
__Pausable_init();
__Generator_init(_vrfCoordinator, _keyHash, _subscriptionId, _callbackGasLimit);
__Whitelist_init();
serum = ISerum(_serum);
metadata = IMetadata(_metadata);
// Setup rarity and alias tables for token traits
rarities[0] = [255, 255, 255, 255, 255, 255, 255, 255];
aliases[0] = [0, 0, 0, 0, 0, 0, 0, 0];
rarities[1] = [89, 236, 255, 44, 179, 249, 134];
aliases[1] = [2, 2, 0, 1, 5, 2, 5];
rarities[2] = [50, 73, 96, 119, 142, 164, 187, 210, 233, 255, 28];
aliases[2] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0];
rarities[3] = [255, 128, 255, 192, 128, 192, 255, 255, 255, 64, 255, 255, 64, 255, 128, 255, 128, 128, 255, 128, 255, 255, 128, 255, 255];
aliases[3] = [0, 6, 0, 24, 7, 24, 0, 0, 0, 3, 0, 0, 5, 0, 8, 0, 11, 15, 0, 18, 0, 0, 20, 0, 0];
rarities[4] = [199, 209, 133, 255, 209, 209, 255, 133, 255, 133, 199, 255, 199, 66, 66, 199, 255, 133, 255, 255, 66, 255, 255, 66, 250, 240];
aliases[4] = [22, 24, 8, 0, 24, 25, 0, 11, 0, 16, 24, 0, 25, 25, 1, 22, 0, 19, 0, 0, 4, 0, 0, 5, 8, 22];
rarities[5] = [255, 204, 255, 204, 40, 235, 204, 204, 235, 204, 204, 40, 204, 204, 204, 204];
aliases[5] = [0, 5, 0, 8, 0, 0, 5, 8, 2, 5, 8, 2, 5, 8, 5, 8];
rarities[6] = [158, 254, 220, 220, 158, 158, 220, 220, 220, 220, 158, 158, 238, 79, 158, 238, 79, 220, 220, 238, 158, 220, 245, 245, 245, 253, 158, 255, 253, 158, 253];
aliases[6] = [2, 27, 22, 23, 3, 6, 24, 25, 28, 30, 7, 8, 25, 1, 9, 28, 27, 22, 23, 30, 17, 24, 25, 28, 30, 1, 18, 0, 27, 21, 1];
rarities[7] = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255];
aliases[7] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
rarities[8] = [112, 112, 160, 160, 208, 64, 64, 208, 255, 255];
aliases[8] = [2, 3, 4, 7, 8, 0, 1, 9, 0, 0];
rarities[9] = [255, 255, 255, 255, 255, 255, 255, 255];
aliases[9] = [0, 0, 0, 0, 0, 0, 0, 0];
rarities[10] = [235, 250, 46, 30, 255, 76];
aliases[10] = [4, 4, 1, 0, 0, 4];
rarities[11] = [153, 204, 255, 102];
aliases[11] = [1, 2, 0, 0];
rarities[12] = [81, 138, 133, 30, 184, 189, 189, 138, 235, 240, 240, 255];
aliases[12] = [2, 5, 4, 0, 8, 9, 10, 6, 11, 11, 11, 0];
rarities[13] = [255, 255, 255, 255, 255, 255, 255, 255];
aliases[13] = [0, 0, 0, 0, 0, 0, 0, 0];
rarities[14] = [76, 192, 255];
aliases[14] = [2, 2, 0];
rarities[15] = [236, 236, 224, 224, 249, 249, 255];
aliases[15] = [4, 5, 0, 1, 6, 6, 0];
}
// -- EXTERNAL --
// @since V2.0 - Whitelist mint no longer needed
/**
* Mint scientists & mutants
* @param _amount Number of tokens to mint
* @param _burnIds Token Ids to burn as payment (for gen 1 & 2)
*/
function mint(uint256 _amount, uint256[] calldata _burnIds) external payable whenNotPaused {
if (earlyMintEnabled)
revert EarlyMintIsEnabled();
uint256 publicMintCount = publicMints[_msgSender()];
// Verify amount
// @since V2.0 Transaction limit of 10, account limit of 20
if (_amount == 0 || _amount > PUBLIC_MINT_LIMIT) revert InvalidMintAmount(_amount);
// Verify generation and price
uint256 id = totalMinted();
if (id >= GEN3_MAX) revert SoldOut();
uint256 max = id + _amount;
uint256 generation;
// Generation 0
if (id < GEN0_MAX) {
if (max > GEN0_MAX) revert GenerationLimit(0);
// @since V2.0 - No ether required to mint
// Account limit of PUBLIC_MINT_LIMIT not including whitelist mints
// @since V2.0 - Fix underflow bug
uint256 currentBalance = balanceOf(_msgSender());
uint256 whitelistMintCount = whitelistMints[_msgSender()];
if (
(currentBalance >= whitelistMintCount && currentBalance - whitelistMintCount + _amount > PUBLIC_MINT_LIMIT) ||
(publicMintCount + _amount > PUBLIC_MINT_LIMIT)
) revert LimitExceeded(_msgSender());
// Generation 1
} else if (id < GEN1_MAX) {
if (max > GEN1_MAX) revert GenerationLimit(1);
serum.burn(_msgSender(), _amount * GEN1_PRICE);
generation = 1;
// Generation 2
} else if (id < GEN2_MAX) {
if (max > GEN2_MAX) revert GenerationLimit(2);
serum.burn(_msgSender(), _amount * GEN2_PRICE);
generation = 2;
// Generation 3
} else if (id < GEN3_MAX) {
if (address(blueprint) == address(0)) revert BlueprintNotReady();
if (max > GEN3_MAX) revert GenerationLimit(3);
serum.burn(_msgSender(), _amount * GEN3_PRICE);
generation = 3;
}
// Burn tokens to mint gen 1, 2, and 3
uint256 burnLength = _burnIds.length;
if (generation != 0) {
if (burnLength != _amount) revert InvalidBurnLength(burnLength, _amount);
for (uint256 i; i < burnLength; i++) {
// Verify token to be burned
if (_msgSender() != ownerOf(_burnIds[i])) revert BurnNotOwned(_msgSender(), _burnIds[i]);
if (tokens[_burnIds[i]] & 3 != generation - 1) revert InvalidBurnGeneration(tokens[_burnIds[i]] & 3, generation - 1);
_burn(_burnIds[i]);
}
// Add burned tokens to id offset
tokenOffset += burnLength;
// Generation 0 no burn needed
} else {
if (burnLength != 0) revert InvalidBurnLength(burnLength, 0);
}
publicMints[_msgSender()] = publicMintCount + _amount;
// Request token mint
// @since V2.0 - Single transaction mint
// Token id to mint in [id + 1, id + _amount]
max++;
for (uint i = id + 1; i < max; i++) {
uint256 seed = _random(i);
_revealToken(i, seed);
}
}
function earlyMint(uint256 _amount) external whenNotPaused {
if (!earlyMintEnabled) revert EarlyMintNotEnabled(); // Only when early mint enabled
uint256 whitelistMintCount = whitelistMints[_msgSender()];
uint256 publicMintCount = publicMints[_msgSender()];
bool hasExtraMints = extraMintAccounts[_msgSender()];
if (whitelistMintCount == 0 && publicMintCount == 0 && hasExtraMints == false)
revert EarlyMintIsEnabled();
uint256 limit = hasExtraMints ? EXTRA_MINT_LIMIT : PUBLIC_MINT_LIMIT;
// Verify amount
// @since V2.0 Transaction limit of 10, account limit of 20
if (_amount == 0 || _amount > limit) revert InvalidMintAmount(_amount);
// Verify generation and price
uint256 id = totalMinted();
uint256 max = id + _amount;
if (id >= GEN0_MAX || max > GEN0_MAX) revert GenerationLimit(0);
// @since V2.0 - No ether required to mint
// Account limit of PUBLIC_MINT_LIMIT not including whitelist mints
// @since V2.0 - Fix underflow bug
uint256 currentBalance = balanceOf(_msgSender());
if (
(currentBalance >= whitelistMintCount && currentBalance - whitelistMintCount + _amount > limit) ||
(publicMintCount + _amount > limit)
) revert LimitExceeded(_msgSender());
publicMints[_msgSender()] = publicMintCount + _amount;
// Request token mint
// @since V2.0 - Single transaction mint
// Token id to mint in [id + 1, id + _amount]
max++;
for (uint i = id + 1; i < max; i++) {
_revealToken(i, _random(i));
}
}
/**
* Reveal pending mints
*/
function reveal() external whenNotPaused {
(, uint256 count) = pendingOf(_msgSender());
_reveal(_msgSender());
// Tokens minted, update offset
tokenOffset -= count;
}
/**
* Get the metadata uri for a token
* @param _tokenId Token ID to query
* @return Token metadata json URI
*/
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
if (!_exists(_tokenId)) revert ERC721_QueryForNonexistentToken(_tokenId);
return metadata.tokenURI(_tokenId);
}
/**
* Get the total number of minted tokens
* @return Total number of minted tokens
*/
function totalMinted() public view returns (uint256) {
return totalSupply() + tokenOffset;
}
/**
* Get the data of a token
* @param _tokenId Token ID to query
* @return Token structure
*/
function getToken(uint256 _tokenId) external view returns (uint256) {
if (!_exists(_tokenId)) revert ERC721_QueryForNonexistentToken(_tokenId);
return tokens[_tokenId];
}
// -- INTERNAL --
function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal override {
super._beforeTokenTransfer(_from, _to, _tokenId);
// Update serum claim on transfer and burn
if (_from != address(0))
serum.updateClaim(_from, _tokenId);
}
/**
* Generate and mint pending token using random seed
* @param _tokenId Token ID to reveal
* @param _seed Random seed
*/
function _revealToken(uint256 _tokenId, uint256 _seed) internal override {
// Calculate generation of token
uint256 token;
if (_tokenId <= GEN0_MAX) {}
else if (_tokenId <= GEN1_MAX) token = 1;
else if (_tokenId <= GEN2_MAX) token = 2;
else if (_tokenId <= GEN3_MAX) token = 3;
// Select scientist or mutant
// @since V2.0 Mint mutants at 2%
token |= (((_seed & 0xFFFF) % 100) < 2) ? 128 : 0;
// Loop over tokens traits (9 scientist, 8 mutant)
(uint256 start, uint256 count) = (token & 128 != 0) ? (TYPE_OFFSET, MAX_TRAITS - TYPE_OFFSET) : (0, TYPE_OFFSET);
for (uint256 i; i < count; i++) {
_seed >>= 16;
token |= _selectTrait(_seed, start + i) << (8 * i + 8);
}
// Save traits
tokens[_tokenId] = token;
// Mint token
_safeMint(_msgSender(), _tokenId);
// Setup serum claim for token
serum.initializeClaim(_tokenId);
// Mint blueprint to gen3 tokens
if (token & 3 == 3)
blueprint.mint(_msgSender(), _seed >> 16);
}
/**
* Select a trait from the alias tables using a random seed (16 bit)
* @param _seed Random seed
* @param _trait Trait to select
* @return Index of the selected trait
*/
function _selectTrait(uint256 _seed, uint256 _trait) internal view returns (uint256) {
uint256 i = (_seed & 0xFF) % rarities[_trait].length;
return (((_seed >> 8) & 0xFF) < rarities[_trait][i]) ? i : aliases[_trait][i];
}
/**
* Generate a psuedo-random number
* @param _seed Seed for the RNG
* @return Random 256 bit number
*/
function _random(uint256 _seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
_seed
)));
}
// -- OWNER --
/**
* Enable/disable holder only early mint
*/
function setEarlyMintEnabled(bool _earlyMintEnabled) external onlyOwner {
earlyMintEnabled = _earlyMintEnabled;
}
/**
* Add account to the early mint
* @param _accounts Account to add
*/
function addEarlyMintAccounts(address[] calldata _accounts) external onlyOwner {
for (uint256 i; i < _accounts.length; i++)
whitelistMints[_accounts[i]]++;
}
/**
* Add account to the extra mint list
* @param _accounts Account to add
*/
function addExtraMintAccounts(address[] calldata _accounts) external onlyOwner {
for (uint256 i; i < _accounts.length; i++)
extraMintAccounts[_accounts[i]] = true;
}
/**
* Pause the contract
*/
function pause() external onlyOwner {
_pause();
}
/**
* Unpause the contract
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* Set blueprint contract
* @param _blueprint Address of the blueprint contract
*/
function setBlueprint(address _blueprint) external onlyOwner {
blueprint = IBlueprint(_blueprint);
}
/**
* Withdraw funds to owner
*/
function withdraw() external onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
// Modified to use custom errors instead of require strings
pragma solidity ^0.8.13;
import "../ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
error ERC721Enumerable_IndexOutOfBounds(uint256 index, uint256 max);
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
if (index >= ERC721Upgradeable.balanceOf(owner))
revert ERC721Enumerable_IndexOutOfBounds(index, ERC721Upgradeable.balanceOf(owner));
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) {
if (index >= ERC721EnumerableUpgradeable.totalSupply())
revert ERC721Enumerable_IndexOutOfBounds(index, ERC721EnumerableUpgradeable.totalSupply());
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* @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[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
// Modified to use custom errors instead of require strings
pragma solidity ^0.8.13;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
error Ownable_CallerNotOwner(address caller, address owner);
error Ownable_NewOwnerZeroAddress();
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
if (owner() != _msgSender()) revert Ownable_CallerNotOwner(_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 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 {
if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress();
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
// Modified to use custom errors instead of require strings
pragma solidity ^0.8.13;
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.
*/
error Pausable_Paused();
error Pausable_NotPaused();
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() {
if (paused()) revert Pausable_Paused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
if (!paused()) revert Pausable_NotPaused();
_;
}
/**
* @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
pragma solidity ^0.8.13;
import "./VRFConsumerBaseV2Upgradable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import "../openzeppelin/proxy/utils/Initializable.sol";
error AccountHasPendingMint(address _account);
error AcountHasNoPendingMint(address _account);
error InvalidAccount();
error InvalidRequestBase();
error InvalidRequestCount();
error RevealNotReady();
abstract contract Generator is VRFConsumerBaseV2Upgradable {
VRFCoordinatorV2Interface internal vrfCoordinator;
bytes32 internal keyHash;
uint64 internal subscriptionId;
uint32 internal callbackGasLimit;
struct Mint {
uint64 base;
uint32 count;
uint256[] random;
}
mapping(uint256 => address) internal mintRequests;
mapping(address => Mint) internal pendingMints;
event Requested(address indexed _account, uint256 _baseId, uint256 _count);
event Pending(address indexed _account, uint256 _baseId, uint256 _count);
event Revealed(address indexed _account, uint256 _tokenId);
/**
* Constructor to initialize VRF
* @param _vrfCoordinator VRF Coordinator address
* @param _keyHash Gas lane key hash
* @param _subscriptionId VRF subscription id
* @param _callbackGasLimit VRF callback gas limit
*/
function __Generator_init(
address _vrfCoordinator,
bytes32 _keyHash,
uint64 _subscriptionId,
uint32 _callbackGasLimit
) internal onlyInitializing {
__VRFConsumerBaseV2_init(_vrfCoordinator);
vrfCoordinator = VRFCoordinatorV2Interface(_vrfCoordinator);
keyHash = _keyHash;
subscriptionId = _subscriptionId;
callbackGasLimit = _callbackGasLimit;
}
// -- PUBLIC --
modifier zeroPending(address _account) {
if (pendingMints[_account].base != 0) revert AccountHasPendingMint(_account);
_;
}
/**
* Get the current pending mints of a user account
* @param _account Address of account to query
* @return Pending token base ID, amount of pending tokens
*/
function pendingOf(address _account) public view returns (uint256, uint256) {
return (pendingMints[_account].base, pendingMints[_account].random.length);
}
// -- INTERNAL --
/**
* Update pending mint with response from VRF
* @param _requestId Request ID that was fulfilled
* @param _randomWords Received random numbers
*/
function fulfillRandomWords(uint256 _requestId, uint256[] memory _randomWords) internal virtual override {
// Pop request
address account = mintRequests[_requestId];
delete mintRequests[_requestId];
// Update pending mints with received random numbers
pendingMints[account].random = _randomWords;
// Ready to reveal
emit Pending(account, pendingMints[account].base, _randomWords.length);
}
/**
* Setup a pending mint and request numbers from VRF
* @param _account Account to request for
* @param _base Base token ID
* @param _count Number of tokens
*/
function _request(address _account, uint256 _base, uint256 _count) internal zeroPending(_account) {
if (_account == address(0)) revert InvalidAccount();
if (_base == 0) revert InvalidRequestBase();
if (_count == 0) revert InvalidRequestCount();
// Request random numbers for tokens, save request id to account
uint256 requestId = vrfCoordinator.requestRandomWords(
keyHash,
subscriptionId,
3,
callbackGasLimit,
uint32(_count)
);
mintRequests[requestId] = _account;
// Initialize mint request with id and count
pendingMints[_account].base = uint64(_base);
pendingMints[_account].count = uint32(_count);
// Mint requested
emit Requested(_account, _base, _count);
}
/**
* Reveal pending tokens with received random numbers
* @param _account Account to reveal for
*/
function _reveal(address _account) internal {
if (_account == address(0)) revert InvalidAccount();
Mint memory mint = pendingMints[_account];
if (mint.base == 0) revert AcountHasNoPendingMint(_account);
if (mint.random.length == 0) revert RevealNotReady();
delete pendingMints[_account];
// Generate all tokens
for (uint256 i; i < mint.count; i++) {
_revealToken(mint.base + i, mint.random[i]);
emit Revealed(_account, mint.base + i);
}
}
/**
* Abstract function called on each token when revealing
* @param _tokenId Token ID to reveal
* @param _seed Random number from VRF for the token
*/
function _revealToken(uint256 _tokenId, uint256 _seed) internal virtual;
/**
* Set the VRF key hash
* @param _keyHash New keyHash
*/
function _setKeyHash(bytes32 _keyHash) internal {
keyHash = _keyHash;
}
/**
* Set the VRF subscription ID
* @param _subscriptionId New subscriptionId
*/
function _setSubscriptionId(uint64 _subscriptionId) internal {
subscriptionId = _subscriptionId;
}
/**
* Set the VRF callback gas limit
* @param _callbackGasLimit New callbackGasLimit
*/
function _setCallbackGasLimit(uint32 _callbackGasLimit) internal {
callbackGasLimit = _callbackGasLimit;
}
/**
* @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[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol";
import "../openzeppelin/proxy/utils/Initializable.sol";
error WhitelistIsEnabled();
error WhitelistNotEnabled();
abstract contract Whitelist is Initializable {
bytes32 internal merkleRoot;
event WhitelistEnabled();
event WhitelistDisabled();
/** Whitelist contstructor (empty) */
function __Whitelist_init() internal onlyInitializing {}
function whitelisted() public view returns (bool) {
return merkleRoot != bytes32(0);
}
modifier whenWhitelisted {
if (!whitelisted()) revert WhitelistNotEnabled();
_;
}
modifier whenNotWhitelisted {
if (whitelisted()) revert WhitelistIsEnabled();
_;
}
/**
* Checks if an account is whitelisted using the given proof
* @param _account Account to verify
* @param _merkleProof Proof to verify the account is in the merkle tree
*/
function _whitelisted(address _account, bytes32[] calldata _merkleProof) internal view returns (bool) {
return MerkleProofUpgradeable.verify(_merkleProof, merkleRoot, keccak256(abi.encodePacked(_account)));
}
/**
* Enable the whitelist and set the merkle tree root
* @param _merkleRoot Whitelist merkle tree root hash
*/
function _enableWhitelist(bytes32 _merkleRoot) internal {
if (whitelisted()) revert WhitelistIsEnabled();
merkleRoot = _merkleRoot;
emit WhitelistEnabled();
}
/**
* Disable the whitelist and clear the root hash
*/
function _disableWhitelist() internal {
if (!whitelisted()) revert WhitelistNotEnabled();
delete merkleRoot;
emit WhitelistDisabled();
}
/**
* @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
pragma solidity ^0.8.13;
import "./IClaimable.sol";
interface ISerum is IClaimable {
function mint(address _to, uint256 _amount) external;
function burn(address _from, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface IMetadata {
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
interface IBlueprint {
function mint(address _account, uint256 _seed) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
// Modified to use custom errors instead of require strings
pragma solidity ^0.8.13;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
error ERC721_QueryOnZeroAddress();
error ERC721_QueryForNonexistentToken(uint256 tokenId);
error ERC721Metadata_QueryForNonexistentToken(uint256 tokenId);
error ERC721_ApprovalToCurrentOwner(address owner);
error ERC721_CallerNotOwnerOrApproved(address caller);
error ERC721_TransferToNonReceiverImplementer(address to, uint256 tokenId);
error ERC721_MintToZeroAddress(uint256 tokenId);
error ERC721_TokenAlreadyMinted(uint256 tokenId);
error ERC721_TransferFromIncorrectOwner(address from, address expected);
error ERC721_TransferToZeroAddress(uint256 tokenId);
error ERC721_ApprovalToCaller(address caller);
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
if (owner == address(0)) revert ERC721_QueryOnZeroAddress();
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
if (owner == address(0)) revert ERC721_QueryForNonexistentToken(tokenId);
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) {
if (!_exists(tokenId)) revert ERC721Metadata_QueryForNonexistentToken(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
if (to == owner) revert ERC721_ApprovalToCurrentOwner(to);
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ERC721_CallerNotOwnerOrApproved(_msgSender());
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert ERC721_CallerNotOwnerOrApproved(_msgSender());
_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 {
if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert ERC721_CallerNotOwnerOrApproved(_msgSender());
_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);
if (!_checkOnERC721Received(from, to, tokenId, _data)) revert ERC721_TransferToNonReceiverImplementer(to, tokenId);
}
/**
* @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) {
if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId);
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
if (!_checkOnERC721Received(address(0), to, tokenId, _data)) revert ERC721_TransferToNonReceiverImplementer(to, tokenId);
}
/**
* @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 {
if (to == address(0)) revert ERC721_MintToZeroAddress(tokenId);
if (_exists(tokenId)) revert ERC721_TokenAlreadyMinted(tokenId);
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
if (ERC721Upgradeable.ownerOf(tokenId) != from) revert ERC721_TransferFromIncorrectOwner(from, ERC721Upgradeable.ownerOf(tokenId));
if (to == address(0)) revert ERC721_TransferToZeroAddress(tokenId);
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
if (owner == operator) revert ERC721_ApprovalToCaller(owner);
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert ERC721_TransferToNonReceiverImplementer(to, tokenId);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @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[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
// Modified to use custom errors instead of require strings
pragma solidity ^0.8.13;
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 {}
* ```
* ====
*/
error Initializable_AlreadyInitialized();
error Initializable_NotInitializing();
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.
if(_initializing ? !_isConstructor() : _initialized) revert Initializable_AlreadyInitialized();
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() {
if (!_initializing) revert Initializable_NotInitializing();
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// 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 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
// Modified to use custom errors instead of require strings
pragma solidity ^0.8.13;
/**
* @dev Collection of functions related to the address type
*/
error Address_InsufficientBalance(uint256 balance, uint256 amount);
error Address_UnableToSendValue(address recipient, uint256 amount);
error Address_CallToNonContract(address target);
error Address_StaticCallToNonContract(address target);
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 {
if (address(this).balance < amount) revert Address_InsufficientBalance(address(this).balance, amount);
(bool success, ) = recipient.call{value: amount}("");
if (!success) revert Address_UnableToSendValue(recipient, amount);
}
/**
* @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) {
if (address(this).balance < value) revert Address_InsufficientBalance(address(this).balance, value);
if (!isContract(target)) revert Address_CallToNonContract(target);
(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) {
if (!isContract(target)) revert Address_StaticCallToNonContract(target);
(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)
// Modified to use custom errors instead of require strings
pragma solidity ^0.8.13;
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)
// Modified to use custom errors instead of require strings
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/introspection/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
pragma solidity ^0.8.13;
import "../openzeppelin/proxy/utils/Initializable.sol";
// Modified to use OpenZeppelin upgradeables
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinator
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords),
* @dev see (VRFCoordinatorInterface for a description of the arguments).
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2Upgradable is Initializable {
error OnlyCoordinatorCanFulfill(address have, address want);
address private vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
function __VRFConsumerBaseV2_init(address _vrfCoordinator) internal onlyInitializing {
vrfCoordinator = _vrfCoordinator;
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {
if (msg.sender != vrfCoordinator) {
revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
}
fulfillRandomWords(requestId, randomWords);
}
/**
* @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
pragma solidity ^0.8.0;
interface VRFCoordinatorV2Interface {
/**
* @notice Get configuration relevant for making requests
* @return minimumRequestConfirmations global min for request confirmations
* @return maxGasLimit global max for request gas limit
* @return s_provingKeyHashes list of registered key hashes
*/
function getRequestConfig()
external
view
returns (
uint16,
uint32,
bytes32[] memory
);
/**
* @notice Request a set of random words.
* @param keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* @param subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* @param minimumRequestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* @param callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* @param numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(
bytes32 keyHash,
uint64 subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords
) external returns (uint256 requestId);
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
*/
function createSubscription() external returns (uint64 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return reqCount - number of requests for this subscription, determines fee tier.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(uint64 subId)
external
view
returns (
uint96 balance,
uint64 reqCount,
address owner,
address[] memory consumers
);
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(uint64 subId) external;
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint64 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint64 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint64 subId, address to) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProofUpgradeable {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
error NoClaimAvailable(address _account);
interface IClaimable {
function claim() external;
function pendingClaim(address _account) external view returns (uint256);
function initializeClaim(uint256 _tokenId) external;
function updateClaim(address _account, uint256 _tokenId) external;
event Claimed(address indexed _account, uint256 _amount);
event Updated(address indexed _account, uint256 indexed _tokenId);
} | * @dev See {IERC721-getApproved}./ | function getApproved(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId);
return _tokenApprovals[tokenId];
}
| 6,147,375 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
588,
31639,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
31639,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
309,
16051,
67,
1808,
12,
2316,
548,
3719,
15226,
4232,
39,
27,
5340,
67,
1138,
1290,
3989,
19041,
1345,
12,
2316,
548,
1769,
203,
203,
3639,
327,
389,
2316,
12053,
4524,
63,
2316,
548,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████
██████████████████████████████▓╝╘███████████████████████████████
████████████████████████████▓▓ ▓█████████████████████████████
██████████████████████▓▀╙ ╙▀▓██████████████████████
███████████████████▀" ,▄▄▄▄▄▄▄▄▄▄, "▀███████████████████
████████████████▓╜ ▄█████████████████▓w ╙█████████████████
██████████████▓┘ ╔███████████████████████▓╕ └███████████████
█████████████▓ ╓██▓╝``╙▓████████████▓╩```██▓, ▀█████████████
████████████╝ ▄███▓ `▀████████▓" ████▄ ▐████████████
███████████▓ ▓████▓ ╒ ▀███▓▀ █████▓ ▀███████████
██████████▓ ▐█████▓ ]▓▄ ╙╝ ▄▓[ █████▓L ███████████
█████████▓╝ ██████▓ ]███▓, ,▓██▓[ ██████▓ ╚██████████
███████Ü ███████▓▓▓▓▓▓▓▓▓r ▓▓▓▓▓▓▓▓▓██████▓ ║███████
████████▓▄╖ ██████▓ ██████▓ ╓▄█████████
██████████▓ ▐██████▓&&&&&&&& &&&&&&&&▄█████▓F ███████████
███████████@ █████▓ █████▓ ▐███████████
███████████▓L █████▄╥▄▄▄▄▄╥╓ ▄▄▄▄▄▄▄▄▄████▓ ╔████████████
█████████████N ▀████████████r ███████████▓╝ ▄█████████████
██████████████▓ ▀██████████▓▄▄██████████▓╝ ,███████████████
████████████████▓, "▀▓████████████████▓╝ ,▄████████████████
███████████████████▄ "╙▀▀▓▓▓▀▀▀╩" ,▄███████████████████
██████████████████████▓▄µ ╓▄███████████████████████
█████████████████████████████▓ ██████████████████████████████
██████████████████████████████▓,,███████████████████████████████
████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
contract MetaTravelers is ERC721Enumerable, ERC721Pausable, ERC721Burnable, VRFConsumerBase, Ownable {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIdTracker;
string private _baseTokenURI;
/**
* @dev Minting variables
*/
uint256 public constant PRICE = .09 ether;
uint256 public constant MAX_QUANTITY = 3;
uint256 public constant MAX_EA_QUANTITY = 5; // max quantity that each early adopter can mint
uint256 public constant MAX_SUPPLY = 7777;
uint256 public constant MAX_RESERVE = 33;
uint256 public constant MAX_EARLY_ADOPTER = 2775;
uint256 public constant MAX_PRESALE = 2997;
uint256 public constant MAX_MINTPASS = 1332;
mapping(address => bool) private _earlyAdopterList;
mapping(address => bool) private _preSaleList;
mapping(address => uint256) private _earlyAdopterPurchased;
mapping(address => uint256) private _preSalePurchased;
mapping(address => uint256) private _publicSalePurchased;
mapping(address => uint256) private _mintPassQuantity;
bool public isReserveComplete = false;
bool public isEarlyAdopterSale = false;
bool public isPreSale = false;
bool public isMintPassSale = false;
bool public isPublicSale = false;
/**
* @dev Provenance variables
*/
string public provenanceHash;
uint256 public startingIndex;
/**
* @dev Chainlink VRF variables
*/
bytes32 internal _keyHash;
uint256 internal _fee;
/**
* @dev Initializes the contract with the name, symbol, and baseTokenURI,
* and pauses the contract by default
*/
constructor (
string memory name,
string memory symbol,
string memory baseTokenURI,
address vrfCoordinator,
address linkToken,
bytes32 keyHash,
uint256 fee
)
ERC721(name, symbol)
VRFConsumerBase(vrfCoordinator, linkToken)
{
_baseTokenURI = baseTokenURI;
_keyHash = keyHash;
_fee = fee;
_pause();
}
event AssetsMinted(address owner, uint256 quantity);
event RequestedRandomness(bytes32 requestId);
event StartingIndexSet(bytes32 requestId, uint256 randomNumber);
/**
* @dev Update the base token URI for returning metadata
*/
function setBaseTokenURI(string memory baseTokenURI) external onlyOwner {
_baseTokenURI = baseTokenURI;
}
/**
* @dev Add wallet addresses to the Early Adopter mappings used for private sale
*/
function addToEarlyAdopterList(address[] calldata addresses) external onlyOwner {
for(uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
require(!_earlyAdopterList[addresses[i]], "Duplicate entry");
_earlyAdopterList[addresses[i]] = true;
}
}
/**
* @dev Add wallet addresses to the PreSale mappings used for private sale
*/
function addToPreSaleList(address[] calldata addresses) external onlyOwner {
for(uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
require(!_preSaleList[addresses[i]], "Duplicate entry");
_preSaleList[addresses[i]] = true;
}
}
/**
* @dev Add wallet addresses to the Mint Pass mapping used for private sale
*/
function addToMintPassList(address[] calldata addresses, uint256[] calldata quantities) external onlyOwner {
require(addresses.length == quantities.length);
for(uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
_mintPassQuantity[addresses[i]] = quantities[i];
}
}
/**
* @dev Returns the quantity available for the message sender to mint during the mint pass sale
*/
function getMintPassQuantity(address user) external view returns (uint256) {
return _mintPassQuantity[user];
}
/**
* @dev Toggle whether early adopter minting is enabled/disabled
*/
function toggleEarlyAdopter() external onlyOwner {
isEarlyAdopterSale = !isEarlyAdopterSale;
}
/**
* @dev Toggle whether preSale minting is enabled/disabled
*/
function togglePreSale() external onlyOwner {
isPreSale = !isPreSale;
}
/**
* @dev Toggle whether mint pass minting is enabled/disabled
*/
function toggleMintPassSale() external onlyOwner {
isMintPassSale = !isMintPassSale;
}
/**
* @dev Toggle whether public sale minting is enabled/disabled
*/
function togglePublicSale() external onlyOwner {
isPublicSale = !isPublicSale;
}
/**
* @dev Base minting function to be reused by other minting functions
*/
function _baseMint(address to) private {
_tokenIdTracker.increment();
_mint(to, _tokenIdTracker.current());
}
/**
* @dev Early Adopter sale restricted to a list of specified wallet address
*/
function earlyAdopterMint(address to, uint256 quantity) external payable {
require(isEarlyAdopterSale, 'Early Adopter sale is not live');
require(_earlyAdopterList[_msgSender()], "User not on Early Adopter list");
require(totalSupply() + quantity <= MAX_EARLY_ADOPTER, "Early Adopter sale is sold out");
require(_earlyAdopterPurchased[_msgSender()] + quantity <= MAX_EA_QUANTITY, "Limit per wallet exceeded");
require(msg.value == PRICE * quantity, "Ether value sent is not correct");
for(uint256 i=0; i<quantity; i++){
_earlyAdopterPurchased[_msgSender()]++;
_baseMint(to);
}
emit AssetsMinted(to, quantity);
}
/**
* @dev PreSale restricted to a list of specified wallet address
*/
function preSaleMint(address to, uint256 quantity) external payable {
require(isPreSale, 'PreSale is not live');
require(_preSaleList[_msgSender()], "User not on PreSale list");
require(totalSupply() + quantity <= MAX_EARLY_ADOPTER + MAX_PRESALE, "PreSale is sold out");
require(_preSalePurchased[_msgSender()] + quantity <= MAX_QUANTITY, "Limit per wallet exceeded");
require(msg.value == PRICE * quantity, "Ether value sent is not correct");
for(uint256 i=0; i<quantity; i++){
_preSalePurchased[_msgSender()]++;
_baseMint(to);
}
emit AssetsMinted(to, quantity);
}
/**
* @dev Mint pass sale based on snapshot of mint pass holders
*/
function mintPassMint(address to, uint256 quantity) external payable {
require(isMintPassSale, 'Mint pass sale is not live');
require(_mintPassQuantity[_msgSender()] > 0, "User does not have valid mint pass");
require(totalSupply() + quantity <= MAX_EARLY_ADOPTER + MAX_PRESALE +
MAX_MINTPASS, "Mint pass sale is sold out");
require(msg.value == PRICE * quantity, "Ether value sent is not correct");
for(uint256 i=0; i<quantity; i++){
require(_mintPassQuantity[_msgSender()] > 0, "No mint pass mints left");
_mintPassQuantity[_msgSender()]--;
_baseMint(to);
}
emit AssetsMinted(to, quantity);
}
/**
* @dev Creates a new token for `to`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_mint}.
*/
function publicSaleMint(address to, uint256 quantity) external payable {
require(isPublicSale, "Public sale is not live");
require(totalSupply() + quantity <= MAX_SUPPLY, "Purchase exceeds max supply");
require(quantity <= MAX_QUANTITY, "Order exceeds max quantity");
require(msg.value == PRICE * quantity, "Ether value sent is not correct");
require(_publicSalePurchased[_msgSender()] + quantity <= MAX_QUANTITY, "Limit per wallet exceeded");
for(uint256 i=0; i<quantity; i++){
_publicSalePurchased[_msgSender()]++;
_baseMint(to);
}
emit AssetsMinted(to, quantity);
}
/**
* @dev Reserve MetaTravelers
*/
function reserveMetaTravelers() external onlyOwner {
require(!isReserveComplete, "MetaTravelers: Already reserved");
for(uint256 i=0; i<MAX_RESERVE; i++){
_baseMint(_msgSender());
}
isReserveComplete = true;
emit AssetsMinted(_msgSender(), MAX_RESERVE);
}
/**
* @dev Set the provenanceHash used for verifying fair and random distribution
*/
function setProvenanceHash(string memory newProvenanceHash) external onlyOwner {
provenanceHash = newProvenanceHash;
}
/**
* @dev Set the startingIndex using Chainlink VRF for provable on-chain randomness
* See callback function 'fulfillRandomness'
*/
function setStartingIndex() external onlyOwner returns (bytes32) {
bytes memory tempProvenanceHash = bytes(provenanceHash);
require(tempProvenanceHash.length > 0, "Need to set provenance hash");
require(startingIndex == 0, "Starting index is already set");
require(LINK.balanceOf(address(this)) >= _fee, "Not enough LINK");
bytes32 requestId = requestRandomness(_keyHash, _fee);
emit RequestedRandomness(requestId);
return requestId;
}
/**
* @dev Callback function used by VRF Coordinator.
* Sets the startingIndex based on the random number generated by Chainlink VRF
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
startingIndex = randomness % MAX_SUPPLY;
// Prevent default sequence
if (startingIndex == 0) {
startingIndex += 1;
}
emit StartingIndexSet(requestId, randomness);
}
/**
* @dev Used to withdraw funds from the contract
*/
function withdraw() external onlyOwner() {
uint256 balance = address(this).balance;
payable(_msgSender()).transfer(balance);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token.");
return bytes(_baseTokenURI).length > 0 ? string(abi.encodePacked(_baseTokenURI, tokenId.toString())) : "";
}
/**
* @dev Used to pause contract minting per ERC721Pausable
*/
function pause() external onlyOwner() {
_pause();
}
/**
* @dev Used to unpause contract minting per ERC721Pausable
*/
function unpause() external onlyOwner() {
_unpause();
}
/**
* @dev Required due to inheritance
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev Required due to inheritance
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
} | * @dev See {IERC721Metadata-tokenURI}./ | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token.");
return bytes(_baseTokenURI).length > 0 ? string(abi.encodePacked(_baseTokenURI, tokenId.toString())) : "";
}
| 6,346,481 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
2277,
17,
2316,
3098,
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
] | [
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,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
654,
39,
27,
5340,
2277,
30,
3699,
843,
364,
1661,
19041,
1147,
1199,
1769,
203,
3639,
327,
1731,
24899,
1969,
1345,
3098,
2934,
2469,
405,
374,
692,
533,
12,
21457,
18,
3015,
4420,
329,
24899,
1969,
1345,
3098,
16,
1147,
548,
18,
10492,
1435,
3719,
294,
1408,
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
] |
./partial_match/1/0xd156a09704171AFe371572D4Aece2F75112B9677/sources/src/GasTankModule.sol | * @dev Gets the list of allowed tokens for a `_delegate` on a `_safes`. @param _safe The safe address. @param _delegate The delegate address./ | function getTokens(address _safe, address _delegate) public view returns (address[] memory) {
uint16 currentIndex = delegates[_safe].contains(_delegate) ? delegatesCurrentIndex[_safe][_delegate] : 0;
return tokens[_safe][_delegate][currentIndex].values();
}
| 9,412,629 | [
1,
3002,
326,
666,
434,
2935,
2430,
364,
279,
1375,
67,
22216,
68,
603,
279,
1375,
67,
87,
1727,
281,
8338,
225,
389,
4626,
1021,
4183,
1758,
18,
225,
389,
22216,
1021,
7152,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18349,
12,
2867,
389,
4626,
16,
1758,
389,
22216,
13,
1071,
1476,
1135,
261,
2867,
8526,
3778,
13,
288,
203,
3639,
2254,
2313,
17032,
273,
22310,
63,
67,
4626,
8009,
12298,
24899,
22216,
13,
692,
22310,
3935,
1016,
63,
67,
4626,
6362,
67,
22216,
65,
294,
374,
31,
203,
203,
3639,
327,
2430,
63,
67,
4626,
6362,
67,
22216,
6362,
2972,
1016,
8009,
2372,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/*
Additional contract info will be added, as needed, to the contractInfo storage variable.
You can read this on etherscan by passing in incrementing indicies as parameter.
*/
contract Gener8tiveTonesERC721 is ERC721URIStorage, ERC721Holder, Ownable
{
using Counters for Counters.Counter;
using Strings for uint256;
using Strings for bytes32;
// =======================================================
// EVENTS
// =======================================================
event CauseBeneficiaryChanged(address newCauseBeneficiary);
event TokenUriUpdated(uint256 tokenId, string uri);
event TokenPurchased(uint256 tokenId, address newOwner, TokenType tokenType);
event TokenMinted(uint256 tokenIndex, bytes32 hashValue, TokenType tokenType);
// =======================================================
// STATE
// =======================================================
Counters.Counter public tokenId;
address payable public causeBeneficiary;
mapping(uint256 => TokenData) public tokenData;
uint256 public maxSupply = 125;
uint256 public mintPrice = 400000000 gwei;
bool public preSalePurchaseEnabled = true;
bool public mintingEnabled = false;
mapping(uint256 => string) public contractInfo;
string mintBaseUri;
address kCompsContractAddress;
mapping(address => uint16) numTokensByAddress;
// =======================================================
// ENUMS & STRUCTS
// =======================================================
enum TokenType { PRESALE, PRESALE_KCOMPSOWNER, OPEN, OPEN_KCOMPSOWNER }
struct TokenData {
uint256 price;
bytes32 seed;
string name;
bool forSale;
TokenType tokenType;
}
// =======================================================
// CONSTRUCTOR
// =======================================================
constructor(
string memory _name,
string memory _symbol,
address _kCompsContractAddress,
string memory _mintBaseUri,
address payable _causeBeneficiary
)
ERC721(_name, _symbol)
{
kCompsContractAddress = _kCompsContractAddress;
mintBaseUri = _mintBaseUri;
causeBeneficiary = _causeBeneficiary;
}
// =======================================================
// ADMIN
// =======================================================
function disableMinting()
public
onlyOwner
{
mintingEnabled = false;
}
function enableMinting()
public
onlyOwner
{
mintingEnabled = true;
}
function disablePreSalePurchase()
public
onlyOwner
{
preSalePurchaseEnabled = false;
}
function enablePreSalePurchase()
public
onlyOwner
{
preSalePurchaseEnabled = true;
}
function setContractInfo(uint _index, string memory _info)
public
onlyOwner
{
contractInfo[_index] = _info;
}
function changeCauseBeneficiary(address payable newCauseBeneficiary)
public
onlyOwner
{
causeBeneficiary = newCauseBeneficiary;
emit CauseBeneficiaryChanged(causeBeneficiary);
}
function changeMintPrice(uint256 newMintPrice)
public
onlyOwner
{
mintPrice = newMintPrice;
}
function updateTokenURI(uint256 _tokenId, string memory _newTokenURI)
public
onlyOwner
{
super._setTokenURI(_tokenId, _newTokenURI);
emit TokenUriUpdated(_tokenId, _newTokenURI);
}
function changePresaleTokenPrice(uint256 _tokenId, uint256 _newPrice)
public
onlyOwner
{
// ensure token is of PRESALE type
require(tokenData[_tokenId].tokenType == TokenType.PRESALE, "Token is not of Presale Type");
// ensure token is owned by the owner
require(ownerOf(_tokenId) == owner(), "Token has already been sold");
tokenData[_tokenId].price = _newPrice;
}
function preSaleMint(uint256 _price, string memory _tokenUri, bool _forSale)
public
onlyOwner
{
// check max supply
require(tokenId.current() < maxSupply, "Collection max supply reached");
// save token data
tokenData[tokenId.current()] = TokenData({
price: _price,
name: string(abi.encodePacked("Tone ", tokenId.current().toString())),
tokenType: TokenType.PRESALE,
seed: getHashOfTokenIndex(tokenId.current()),
forSale: _forSale
});
// mint and set tokenuri
super._safeMint(msg.sender, tokenId.current());
super._setTokenURI(tokenId.current(), _tokenUri);
tokenId.increment();
}
function withdrawFunds(address payable recipient, uint256 amount)
public
onlyOwner
{
recipient.transfer(amount);
}
// =======================================================
// INTERNAL UTILS
// =======================================================
function getTokenAvailability()
private
view
returns(bool[] memory availableTokens)
{
availableTokens = new bool[](tokenId.current());
for (uint256 i = 0; i < tokenId.current(); i++) {
if(ownerOf(i) == owner() && tokenData[i].forSale) {
availableTokens[i] = true;
}
else {
availableTokens[i] = false;
}
}
}
function div256(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mul256(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;
}
// =======================================================
// PUBLIC API
// =======================================================
function getHashOfTokenIndex(uint256 _tokenId)
public
pure
returns(bytes32 idKeccak)
{
idKeccak = keccak256(abi.encodePacked(_tokenId));
}
function getSupplyData()
public
view
returns(
uint256 _currentTokenId,
uint256 _maxSupply,
uint256 _mintPrice,
bool _mintingEnabled,
bool _preSalePurchaseEnabled,
bool _isKCompsOwner,
bool[] memory _tokenAvailability,
address payable _causeBeneficiary
)
{
_currentTokenId = tokenId.current();
_maxSupply = maxSupply;
_mintPrice = mintPrice;
_isKCompsOwner = isKCompsOwner(msg.sender);
_mintingEnabled = mintingEnabled;
_preSalePurchaseEnabled = preSalePurchaseEnabled;
_tokenAvailability = getTokenAvailability();
_causeBeneficiary = _causeBeneficiary;
}
function getTokenData(uint256 _tokenId)
public
view
returns(TokenData memory _tokenData, string memory _tokenUri)
{
_tokenData = tokenData[_tokenId];
_tokenUri = tokenURI(_tokenId);
}
function isKCompsOwner(address _address)
public
view
returns(bool kCompsOwner)
{
AbstractKCompsContract abstractKcomps = AbstractKCompsContract(kCompsContractAddress);
uint256 numTokensOwned = abstractKcomps.balanceOf(_address);
if(numTokensOwned > 0) {
return true;
}
return false;
}
function purchasePresaleToken(uint256 _tokenId)
public
payable
{
// ensure pre-sale purchasing is enabled
require(preSalePurchaseEnabled, "Pre-Sale purchasing is disabled");
// ensure the token exists
require(_exists(_tokenId), "Requested token does not exist yet");
// ensure token is for sale
require(tokenData[_tokenId].forSale, "Token is not for sale");
// ensure token is of PRESALE type
require(tokenData[_tokenId].tokenType == TokenType.PRESALE, "Token is not of Presale Type");
// ensure token is owned by the owner
require(ownerOf(_tokenId) == owner(), "Token is not owned by the owner");
// ensure sufficient funds were sent
if(isKCompsOwner(msg.sender)) {
require(msg.value >= div256(tokenData[_tokenId].price, 2), "Insufficient ETH sent");
tokenData[_tokenId].tokenType = TokenType.PRESALE_KCOMPSOWNER;
}
else {
require(msg.value >= tokenData[_tokenId].price, "Insufficient ETH sent");
}
// calculate gener8tive fee & send beneficiary portion
uint256 gener8tiveFee = div256(mul256(85, msg.value), 100);
causeBeneficiary.transfer(msg.value - gener8tiveFee);
// remove from sale
tokenData[_tokenId].forSale = false;
_transfer(owner(), msg.sender, _tokenId);
emit TokenPurchased(_tokenId, msg.sender, tokenData[_tokenId].tokenType);
}
function mint()
public
payable
{
// check mint handbrake
require(mintingEnabled, "Minting is currently disabled");
// check max supply
require(tokenId.current() < maxSupply, "Collection max supply reached");
// ensure sufficient funds were sent
if(isKCompsOwner(msg.sender)) {
require(msg.value >= div256(mintPrice, 2), "Insufficient ETH sent for mint");
}
else {
require(msg.value >= mintPrice, "Insufficient ETH sent for mint");
}
TokenType tokenType = TokenType.OPEN;
// set token type if k-comps owner
if(isKCompsOwner(msg.sender)) {
tokenType = TokenType.OPEN_KCOMPSOWNER;
}
// calculate gener8tive fee and send to beneficiary
uint256 gener8tiveFee = div256(mul256(85, msg.value), 100);
causeBeneficiary.transfer(msg.value - gener8tiveFee);
// generate unique seed hash for tone
uint16 numTokensOwnedNySender = numTokensByAddress[msg.sender];
bytes32 _hash = keccak256(abi.encodePacked(tokenId.current(), numTokensOwnedNySender));
numTokensByAddress[msg.sender] ++;
// save token data
tokenData[tokenId.current()] = TokenData({
price: 0,
name: string(abi.encodePacked("Tone ", tokenId.current().toString())),
tokenType: tokenType,
seed: _hash,
forSale: false
});
// build mint token uri
string memory tokenUri = string(abi.encodePacked(mintBaseUri, tokenId.current().toString()));
super._safeMint(msg.sender, tokenId.current());
super._setTokenURI(tokenId.current(), tokenUri);
tokenId.increment();
emit TokenMinted(tokenId.current() - 1, _hash, tokenType);
}
}
contract AbstractKCompsContract
{
function balanceOf(address addr)
public
pure
returns(uint256)
{
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
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.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
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.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| ensure pre-sale purchasing is enabled ensure the token exists ensure token is for sale ensure token is of PRESALE type ensure token is owned by the owner ensure sufficient funds were sent | function purchasePresaleToken(uint256 _tokenId)
public
payable
{
require(preSalePurchaseEnabled, "Pre-Sale purchasing is disabled");
require(_exists(_tokenId), "Requested token does not exist yet");
require(tokenData[_tokenId].forSale, "Token is not for sale");
require(tokenData[_tokenId].tokenType == TokenType.PRESALE, "Token is not of Presale Type");
require(ownerOf(_tokenId) == owner(), "Token is not owned by the owner");
if(isKCompsOwner(msg.sender)) {
require(msg.value >= div256(tokenData[_tokenId].price, 2), "Insufficient ETH sent");
tokenData[_tokenId].tokenType = TokenType.PRESALE_KCOMPSOWNER;
}
else {
require(msg.value >= tokenData[_tokenId].price, "Insufficient ETH sent");
}
causeBeneficiary.transfer(msg.value - gener8tiveFee);
_transfer(owner(), msg.sender, _tokenId);
emit TokenPurchased(_tokenId, msg.sender, tokenData[_tokenId].tokenType);
}
| 6,063,638 | [
1,
15735,
675,
17,
87,
5349,
5405,
343,
11730,
353,
3696,
3387,
326,
1147,
1704,
3387,
1147,
353,
364,
272,
5349,
3387,
1147,
353,
434,
7071,
5233,
900,
618,
3387,
1147,
353,
16199,
635,
326,
3410,
3387,
18662,
284,
19156,
4591,
3271,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
23701,
12236,
5349,
1345,
12,
11890,
5034,
389,
2316,
548,
13,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
565,
288,
203,
3639,
2583,
12,
1484,
30746,
23164,
1526,
16,
315,
1386,
17,
30746,
5405,
343,
11730,
353,
5673,
8863,
203,
203,
3639,
2583,
24899,
1808,
24899,
2316,
548,
3631,
315,
11244,
1147,
1552,
486,
1005,
4671,
8863,
203,
203,
3639,
2583,
12,
2316,
751,
63,
67,
2316,
548,
8009,
1884,
30746,
16,
315,
1345,
353,
486,
364,
272,
5349,
8863,
203,
203,
3639,
2583,
12,
2316,
751,
63,
67,
2316,
548,
8009,
2316,
559,
422,
18794,
18,
3670,
5233,
900,
16,
315,
1345,
353,
486,
434,
18346,
5349,
1412,
8863,
203,
203,
3639,
2583,
12,
8443,
951,
24899,
2316,
548,
13,
422,
3410,
9334,
315,
1345,
353,
486,
16199,
635,
326,
3410,
8863,
203,
203,
3639,
309,
12,
291,
47,
799,
1121,
5541,
12,
3576,
18,
15330,
3719,
288,
203,
5411,
2583,
12,
3576,
18,
1132,
1545,
3739,
5034,
12,
2316,
751,
63,
67,
2316,
548,
8009,
8694,
16,
576,
3631,
315,
5048,
11339,
512,
2455,
3271,
8863,
203,
5411,
1147,
751,
63,
67,
2316,
548,
8009,
2316,
559,
273,
18794,
18,
3670,
5233,
900,
67,
47,
10057,
3584,
22527,
31,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
2583,
12,
3576,
18,
1132,
1545,
1147,
751,
63,
67,
2316,
548,
8009,
8694,
16,
315,
5048,
11339,
512,
2455,
3271,
8863,
203,
3639,
289,
203,
203,
3639,
4620,
38,
4009,
74,
14463,
814,
18,
13866,
12,
3576,
18,
1132,
300,
2
] |
// File: openzeppelin-solidity/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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.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 msg.sender == _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;
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @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-solidity/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) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: openzeppelin-solidity/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.
*
* > 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/interfaces/ISRC20.sol
pragma solidity ^0.5.0;
/**
* @title SRC20 public interface
*/
interface ISRC20 {
event RestrictionsAndRulesUpdated(address restrictions, address rules);
function transferToken(address to, uint256 value, uint256 nonce, uint256 expirationTime,
bytes32 msgHash, bytes calldata signature) external returns (bool);
function transferTokenFrom(address from, address to, uint256 value, uint256 nonce,
uint256 expirationTime, bytes32 hash, bytes calldata signature) external returns (bool);
function getTransferNonce() external view returns (uint256);
function getTransferNonce(address account) external view returns (uint256);
function executeTransfer(address from, address to, uint256 value) external returns (bool);
function updateRestrictionsAndRules(address restrictions, address rules) external returns (bool);
// ERC20 part-like interface
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function 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 increaseAllowance(address spender, uint256 value) external returns (bool);
function decreaseAllowance(address spender, uint256 value) external returns (bool);
}
// File: contracts/interfaces/ISRC20Managed.sol
pragma solidity ^0.5.0;
/**
@title SRC20 interface for managers
*/
interface ISRC20Managed {
event ManagementTransferred(address indexed previousManager, address indexed newManager);
function burn(address account, uint256 value) external returns (bool);
function mint(address account, uint256 value) external returns (bool);
}
// File: contracts/interfaces/ISRC20Roles.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which allows children to implement access managements
* with multiple roles.
*
* `Authority` the one how is authorized by token owner/issuer to authorize transfers
* either on-chain or off-chain.
*
* `Delegate` the person who person responsible for updating KYA document
*
* `Manager` the person who is responsible for minting and burning the tokens. It should be
* be registry contract where staking->minting is executed.
*/
contract ISRC20Roles {
function isAuthority(address account) external view returns (bool);
function removeAuthority(address account) external returns (bool);
function addAuthority(address account) external returns (bool);
function isDelegate(address account) external view returns (bool);
function addDelegate(address account) external returns (bool);
function removeDelegate(address account) external returns (bool);
function manager() external view returns (address);
function isManager(address account) external view returns (bool);
function transferManagement(address newManager) external returns (bool);
function renounceManagement() external returns (bool);
}
// File: contracts/interfaces/IManager.sol
pragma solidity ^0.5.0;
/**
* @dev Manager handles SRC20 burn/mint in relation to
* SWM token staking.
*/
interface IManager {
event SRC20SupplyMinted(address src20, address swmAccount, uint256 swmValue, uint256 src20Value);
event SRC20StakeIncreased(address src20, address swmAccount, uint256 swmValue);
event SRC20StakeDecreased(address src20, address swmAccount, uint256 swmValue);
function mintSupply(address src20, address swmAccount, uint256 swmValue, uint256 src20Value) external returns (bool);
function increaseSupply(address src20, address swmAccount, uint256 srcValue) external returns (bool);
function decreaseSupply(address src20, address swmAccount, uint256 srcValue) external returns (bool);
function renounceManagement(address src20) external returns (bool);
function transferManagement(address src20, address newManager) external returns (bool);
function calcTokens(address src20, uint256 swmValue) external view returns (uint256);
function getStake(address src20) external view returns (uint256);
function swmNeeded(address src20, uint256 srcValue) external view returns (uint256);
function getSrc20toSwmRatio(address src20) external returns (uint256);
function getTokenOwner(address src20) external view returns (address);
}
// File: contracts/factories/Manager.sol
pragma solidity ^0.5.0;
/**
* @dev Manager handles SRC20 burn/mint in relation to
* SWM token staking.
*/
contract Manager is IManager, Ownable {
using SafeMath for uint256;
event SRC20SupplyMinted(address src20, address swmAccount, uint256 swmValue, uint256 src20Value);
event SRC20SupplyIncreased(address src20, address swmAccount, uint256 srcValue);
event SRC20SupplyDecreased(address src20, address swmAccount, uint256 srcValue);
mapping (address => SRC20) internal _registry;
struct SRC20 {
address owner;
address roles;
uint256 stake;
address minter;
}
IERC20 private _swmERC20;
constructor(address swmERC20) public {
require(swmERC20 != address(0), 'SWM ERC20 is zero address');
_swmERC20 = IERC20(swmERC20);
}
modifier onlyTokenOwner(address src20) {
require(_isTokenOwner(src20), "Caller not token owner.");
_;
}
// Note that, similarly to the role of token owner, there is only one manager per src20 token contract.
// Only one address can have this role.
modifier onlyMinter(address src20) {
require(msg.sender == _registry[src20].minter, "Caller not token minter.");
_;
}
/**
* @dev Mint additional supply of SRC20 tokens based on SWN token stake.
* Can be used for initial supply and subsequent minting of new SRC20 tokens.
* When used, Manager will update SWM/SRC20 values in this call and use it
* for token owner's incStake/decStake calls, minting/burning SRC20 based on
* current SWM/SRC20 ratio.
* Only owner of this contract can invoke this method. Owner is SWARM controlled
* address.
* Emits SRC20SupplyMinted event.
*
* @param src20 SRC20 token address.
* @param swmAccount SWM ERC20 account holding enough SWM tokens (>= swmValue)
* with manager contract address approved to transferFrom.
* @param swmValue SWM stake value.
* @param src20Value SRC20 tokens to mint
* @return true on success.
*/
function mintSupply(address src20, address swmAccount, uint256 swmValue, uint256 src20Value)
onlyMinter(src20)
external
returns (bool)
{
require(swmAccount != address(0), "SWM account is zero");
require(swmValue != 0, "SWM value is zero");
require(src20Value != 0, "SRC20 value is zero");
require(_registry[src20].owner != address(0), "SRC20 token contract not registered");
_registry[src20].stake = _registry[src20].stake.add(swmValue);
require(_swmERC20.transferFrom(swmAccount, address(this), swmValue));
require(ISRC20Managed(src20).mint(_registry[src20].owner, src20Value));
emit SRC20SupplyMinted(src20, swmAccount, swmValue, src20Value);
return true;
}
/**
* @dev This is function token issuer can call in order to increase his SRC20 supply this
* and stake his tokens.
*
* @param src20 Address of src20 token contract
* @param swmAccount Account from which stake tokens are going to be deducted
* @param srcValue Value of desired SRC20 token value
* @return true if success
*/
function increaseSupply(address src20, address swmAccount, uint256 srcValue)
external
onlyTokenOwner(src20)
returns (bool)
{
require(swmAccount != address(0), "SWM account is zero");
require(srcValue != 0, "SWM value is zero");
require(_registry[src20].owner != address(0), "SRC20 token contract not registered");
uint256 swmValue = _swmNeeded(src20, srcValue);
require(_swmERC20.transferFrom(swmAccount, address(this), swmValue));
require(ISRC20Managed(src20).mint(_registry[src20].owner, srcValue));
_registry[src20].stake = _registry[src20].stake.add(swmValue);
emit SRC20SupplyIncreased(src20, swmAccount, swmValue);
return true;
}
/**
* @dev This is function token issuer can call in order to decrease his SRC20 supply
* and his stake back
*
* @param src20 Address of src20 token contract
* @param swmAccount Account to which stake tokens will be returned
* @param srcValue Value of desired SRC20 token value
* @return true if success
*/
function decreaseSupply(address src20, address swmAccount, uint256 srcValue)
external
onlyTokenOwner(src20)
returns (bool)
{
require(swmAccount != address(0), "SWM account is zero");
require(srcValue != 0, "SWM value is zero");
require(_registry[src20].owner != address(0), "SRC20 token contract not registered");
uint256 swmValue = _swmNeeded(src20, srcValue);
require(_swmERC20.transfer(swmAccount, swmValue));
require(ISRC20Managed(src20).burn(_registry[src20].owner, srcValue));
_registry[src20].stake = _registry[src20].stake.sub(swmValue);
emit SRC20SupplyDecreased(src20, swmAccount, srcValue);
return true;
}
/**
* @dev Allows manager to renounce management.
*
* @param src20 SRC20 token address.
* @return true on success.
*/
function renounceManagement(address src20)
external
onlyOwner
returns (bool)
{
require(_registry[src20].owner != address(0), "SRC20 token contract not registered");
require(ISRC20Roles(_registry[src20].roles).renounceManagement());
return true;
}
/**
* @dev Allows manager to transfer management to another address.
*
* @param src20 SRC20 token address.
* @param newManager New manager address.
* @return true on success.
*/
function transferManagement(address src20, address newManager)
public
onlyOwner
returns (bool)
{
require(_registry[src20].owner != address(0), "SRC20 token contract not registered");
require(newManager != address(0), "newManager address is zero");
require(ISRC20Roles(_registry[src20].roles).transferManagement(newManager));
return true;
}
/**
* @dev External function allowing consumers to check corresponding SRC20 amount
* to supplied SWM amount.
*
* @param src20 SRC20 token to check for.this
* @param swmValue SWM value.
* @return Amount of SRC20 tokens.
*/
function calcTokens(address src20, uint256 swmValue) external view returns (uint256) {
return _calcTokens(src20, swmValue);
}
/**
* @dev External view function for calculating SWM tokens needed for increasing/decreasing
* src20 token supply.
*
* @param src20 Address of src20 contract
* @param srcValue Amount of src20 tokens.this
* @return Amount of SWM tokens
*/
function swmNeeded(address src20, uint256 srcValue) external view returns (uint256) {
return _swmNeeded(src20, srcValue);
}
/**
* @dev External function for calculating how much SWM tokens are needed to be staked
* in order to get 1 SRC20 token
*
* @param src20 Address of src20 token contract
* @return Amount of SWM tokens
*/
function getSrc20toSwmRatio(address src20) external returns (uint256) {
uint256 totalSupply = ISRC20(src20).totalSupply();
return totalSupply.mul(10 ** 18).div(_registry[src20].stake);
}
/**
* @dev External view function to get current SWM stake
*
* @param src20 Address of SRC20 token contract
* @return Current stake in wei SWM tokens
*/
function getStake(address src20) external view returns (uint256) {
return _registry[src20].stake;
}
/**
* @dev Get address of token owner
*
* @param src20 Address of SRC20 token contract
* @return Address of token owner
*/
function getTokenOwner(address src20) external view returns (address) {
return _registry[src20].owner;
}
/**
* @dev Internal function calculating new SRC20 values based on minted ones. On every
* new minting of supply new SWM and SRC20 values are saved for further calculations.
*
* @param src20 SRC20 token address.
* @param swmValue SWM stake value.
* @return Amount of SRC20 tokens.
*/
function _calcTokens(address src20, uint256 swmValue) internal view returns (uint256) {
require(src20 != address(0), "Token address is zero");
require(swmValue != 0, "SWM value is zero");
require(_registry[src20].owner != address(0), "SRC20 token contract not registered");
uint256 totalSupply = ISRC20(src20).totalSupply();
return swmValue.mul(totalSupply).div(_registry[src20].stake);
}
function _swmNeeded(address src20, uint256 srcValue) internal view returns (uint256) {
uint256 totalSupply = ISRC20(src20).totalSupply();
return srcValue.mul(_registry[src20].stake).div(totalSupply);
}
/**
* @return true if `msg.sender` is the token owner of the registered SRC20 contract.
*/
function _isTokenOwner(address src20) internal view returns (bool) {
return msg.sender == _registry[src20].owner;
}
}
// File: contracts/interfaces/ISRC20Registry.sol
pragma solidity ^0.5.0;
/**
* @dev Interface for SRC20 Registry contract
*/
contract ISRC20Registry {
event FactoryAdded(address account);
event FactoryRemoved(address account);
event SRC20Registered(address token, address tokenOwner);
event SRC20Removed(address token);
event MinterAdded(address minter);
event MinterRemoved(address minter);
function put(address token, address roles, address tokenOwner, address minter) external returns (bool);
function remove(address token) external returns (bool);
function contains(address token) external view returns (bool);
function addMinter(address minter) external returns (bool);
function getMinter(address src20) external view returns (address);
function removeMinter(address minter) external returns (bool);
function addFactory(address account) external returns (bool);
function removeFactory(address account) external returns (bool);
}
// File: contracts/factories/SRC20Registry.sol
pragma solidity ^0.5.0;
/**
* @dev SRC20 registry contains the address of every created
* SRC20 token. Registered factories can add addresses of
* new tokens, public can query tokens.
*/
contract SRC20Registry is ISRC20Registry, Manager {
using Roles for Roles.Role;
Roles.Role private _factories;
mapping (address => bool) _authorizedMinters;
/**
* @dev constructor requiring SWM ERC20 contract address.
*/
constructor(address swmERC20)
Manager(swmERC20)
public
{
}
/**
* @dev Adds new factory that can register token.
* Emits FactoryAdded event.
*
* @param account The factory contract address.
* @return True on success.
*/
function addFactory(address account) external onlyOwner returns (bool) {
require(account != address(0), "account is zero address");
_factories.add(account);
emit FactoryAdded(account);
return true;
}
/**
* @dev Removes factory that can register token.
* Emits FactoryRemoved event.
*
* @param account The factory contract address.
* @return True on success.
*/
function removeFactory(address account) external onlyOwner returns (bool) {
require(account != address(0), "account is zero address");
_factories.remove(account);
emit FactoryRemoved(account);
return true;
}
/**
* @dev Adds token to registry. Only factories can add.
* Emits SRC20Registered event.
*
* @param token The token address.
* @param roles roles SRC20Roles contract address.
* @param tokenOwner Owner of the token.
* @return True on success.
*/
function put(address token, address roles, address tokenOwner, address minter) external returns (bool) {
require(token != address(0), "token is zero address");
require(roles != address(0), "roles is zero address");
require(tokenOwner != address(0), "tokenOwner is zero address");
require(_factories.has(msg.sender), "factory not registered");
require(_authorizedMinters[minter] == true, 'minter not authorized');
_registry[token].owner = tokenOwner;
_registry[token].roles = roles;
_registry[token].minter = minter;
emit SRC20Registered(token, tokenOwner);
return true;
}
/**
* @dev Removes token from registry.
* Emits SRC20Removed event.
*
* @param token The token address.
* @return True on success.
*/
function remove(address token) external onlyOwner returns (bool) {
require(token != address(0), "token is zero address");
require(_registry[token].owner != address(0), "token not registered");
delete _registry[token];
emit SRC20Removed(token);
return true;
}
/**
* @dev Checks if registry contains token.
*
* @param token The token address.
* @return True if registry contains token.
*/
function contains(address token) external view returns (bool) {
return _registry[token].owner != address(0);
}
/**
* This proxy function adds a contract to the list of authorized minters
*
* @param minter The address of the minter contract to add to the list of authorized minters
* @return true on success
*/
function addMinter(address minter) external onlyOwner returns (bool) {
require(minter != address(0), "minter is zero address");
_authorizedMinters[minter] = true;
emit MinterAdded(minter);
return true;
}
/**
* With this function you can fetch address of authorized minter for SRC20.
*
* @param src20 Address of SRC20 token we want to check minters for.
* @return address of authorized minter.
*/
function getMinter(address src20) external view returns (address) {
return _registry[src20].minter;
}
/**
* This proxy function removes a contract from the list of authorized minters
*
* @param minter The address of the minter contract to remove from the list of authorized minters
* @return true on success
*/
function removeMinter(address minter) external onlyOwner returns (bool) {
require(minter != address(0), "minter is zero address");
_authorizedMinters[minter] = false;
emit MinterRemoved(minter);
return true;
}
} | * @dev Manager handles SRC20 burn/mint in relation to SWM token staking./ | interface IManager {
event SRC20SupplyMinted(address src20, address swmAccount, uint256 swmValue, uint256 src20Value);
event SRC20StakeIncreased(address src20, address swmAccount, uint256 swmValue);
event SRC20StakeDecreased(address src20, address swmAccount, uint256 swmValue);
function mintSupply(address src20, address swmAccount, uint256 swmValue, uint256 src20Value) external returns (bool);
function increaseSupply(address src20, address swmAccount, uint256 srcValue) external returns (bool);
function decreaseSupply(address src20, address swmAccount, uint256 srcValue) external returns (bool);
function renounceManagement(address src20) external returns (bool);
function transferManagement(address src20, address newManager) external returns (bool);
function calcTokens(address src20, uint256 swmValue) external view returns (uint256);
function getStake(address src20) external view returns (uint256);
function swmNeeded(address src20, uint256 srcValue) external view returns (uint256);
function getSrc20toSwmRatio(address src20) external returns (uint256);
function getTokenOwner(address src20) external view returns (address);
}
| 5,349,195 | [
1,
1318,
7372,
348,
11529,
3462,
18305,
19,
81,
474,
316,
2533,
358,
16392,
49,
1147,
384,
6159,
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
] | [
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,
5831,
467,
1318,
288,
203,
7010,
565,
871,
348,
11529,
3462,
3088,
1283,
49,
474,
329,
12,
2867,
1705,
3462,
16,
1758,
1352,
81,
3032,
16,
2254,
5034,
1352,
81,
620,
16,
2254,
5034,
1705,
3462,
620,
1769,
203,
565,
871,
348,
11529,
3462,
510,
911,
27597,
8905,
12,
2867,
1705,
3462,
16,
1758,
1352,
81,
3032,
16,
2254,
5034,
1352,
81,
620,
1769,
203,
565,
871,
348,
11529,
3462,
510,
911,
23326,
8905,
12,
2867,
1705,
3462,
16,
1758,
1352,
81,
3032,
16,
2254,
5034,
1352,
81,
620,
1769,
203,
203,
565,
445,
312,
474,
3088,
1283,
12,
2867,
1705,
3462,
16,
1758,
1352,
81,
3032,
16,
2254,
5034,
1352,
81,
620,
16,
2254,
5034,
1705,
3462,
620,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
10929,
3088,
1283,
12,
2867,
1705,
3462,
16,
1758,
1352,
81,
3032,
16,
2254,
5034,
1705,
620,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
20467,
3088,
1283,
12,
2867,
1705,
3462,
16,
1758,
1352,
81,
3032,
16,
2254,
5034,
1705,
620,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
1654,
8386,
10998,
12,
2867,
1705,
3462,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
7412,
10998,
12,
2867,
1705,
3462,
16,
1758,
394,
1318,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
7029,
5157,
12,
2867,
1705,
3462,
16,
2254,
5034,
1352,
81,
620,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
21491,
911,
12,
2867,
1705,
3462,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
2
] |
pragma solidity 0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Owned
* @author Adria Massanet <[email protected]>
* @notice The Owned contract has an owner address, and provides basic
* authorization control functions, this simplifies & the implementation of
* user permissions; this contract has three work flows for a change in
* ownership, the first requires the new owner to validate that they have the
* ability to accept ownership, the second allows the ownership to be
* directly transferred without requiring acceptance, and the third allows for
* the ownership to be removed to allow for decentralization
*/
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
/**
* @dev The constructor sets the `msg.sender` as the`owner` of the contract
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev `owner` is the only address that can call a function with this
* modifier
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev In this 1st option for ownership transfer `proposeOwnership()` must
* be called first by the current `owner` then `acceptOwnership()` must be
* called by the `newOwnerCandidate`
* @notice `onlyOwner` Proposes to transfer control of the contract to a
* new owner
* @param _newOwnerCandidate The address being proposed as the new owner
*/
function proposeOwnership(address _newOwnerCandidate) external onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
emit OwnershipRequested(msg.sender, newOwnerCandidate);
}
/**
* @notice Can only be called by the `newOwnerCandidate`, accepts the
* transfer of ownership
*/
function acceptOwnership() external {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
emit OwnershipTransferred(oldOwner, owner);
}
/**
* @dev In this 2nd option for ownership transfer `changeOwnership()` can
* be called and it will immediately assign ownership to the `newOwner`
* @notice `owner` can step down and assign some other address to this role
* @param _newOwner The address of the new owner
*/
function changeOwnership(address _newOwner) external onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
emit OwnershipTransferred(oldOwner, owner);
}
/**
* @dev In this 3rd option for ownership transfer `removeOwnership()` can
* be called and it will immediately assign ownership to the 0x0 address;
* it requires a 0xdece be input as a parameter to prevent accidental use
* @notice Decentralizes the contract, this operation cannot be undone
* @param _dac `0xdac` has to be entered for this function to work
*/
function removeOwnership(address _dac) external onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
emit OwnershipRemoved();
}
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
interface ERC777TokensRecipient {
function tokensReceived(
address operator,
address from,
address to,
uint amount,
bytes userData,
bytes operatorData
) public;
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
interface ERC777TokensSender {
function tokensToSend(
address operator,
address from,
address to,
uint amount,
bytes userData,
bytes operatorData
) public;
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
interface ERC777Token {
function name() public view returns (string);
function symbol() public view returns (string);
function totalSupply() public view returns (uint256);
function granularity() public view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function send(address to, uint256 amount) public;
function send(address to, uint256 amount, bytes userData) public;
function authorizeOperator(address operator) public;
function revokeOperator(address operator) public;
function isOperatorFor(address operator, address tokenHolder) public view returns (bool);
function operatorSend(address from, address to, uint256 amount, bytes userData, bytes operatorData) public;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes userData,
bytes operatorData
); // solhint-disable-next-line separate-by-one-line-in-contract
event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes userData, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
interface ERC20Token {
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
function totalSupply() public view returns (uint256);
function balanceOf(address owner) public view returns (uint256);
function transfer(address to, uint256 amount) public returns (bool);
function transferFrom(address from, address to, uint256 amount) public returns (bool);
function approve(address spender, uint256 amount) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
contract ERC820Registry {
function getManager(address addr) public view returns(address);
function setManager(address addr, address newManager) public;
function getInterfaceImplementer(address addr, bytes32 iHash) public constant returns (address);
function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public;
}
contract ERC820Implementer {
ERC820Registry public erc820Registry;
constructor(address _registry) public {
erc820Registry = ERC820Registry(_registry);
}
function setInterfaceImplementation(string ifaceLabel, address impl) internal {
bytes32 ifaceHash = keccak256(ifaceLabel);
erc820Registry.setInterfaceImplementer(this, ifaceHash, impl);
}
function interfaceAddr(address addr, string ifaceLabel) internal constant returns(address) {
bytes32 ifaceHash = keccak256(ifaceLabel);
return erc820Registry.getInterfaceImplementer(addr, ifaceHash);
}
function delegateManagement(address newManager) internal {
erc820Registry.setManager(this, newManager);
}
}
/**
* @title ERC777 Helper Contract
* @author Panos
*/
contract ERC777Helper is ERC777Token, ERC20Token, ERC820Implementer {
using SafeMath for uint256;
bool internal mErc20compatible;
uint256 internal mGranularity;
mapping(address => uint) internal mBalances;
/**
* @notice Internal function that ensures `_amount` is multiple of the granularity
* @param _amount The quantity that want's to be checked
*/
function requireMultiple(uint256 _amount) internal view {
require(_amount.div(mGranularity).mul(mGranularity) == _amount);
}
/**
* @notice Check whether an address is a regular address or not.
* @param _addr Address of the contract that has to be checked
* @return `true` if `_addr` is a regular address (not a contract)
*/
function isRegularAddress(address _addr) internal view returns(bool) {
if (_addr == 0) { return false; }
uint size;
assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly
return size == 0;
}
/**
* @notice Helper function actually performing the sending of tokens.
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData Data generated by the user to be passed to the recipient
* @param _operatorData Data generated by the operator to be passed to the recipient
* @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
* implementing `erc777_tokenHolder`.
* ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
* functions SHOULD set this parameter to `false`.
*/
function doSend(
address _from,
address _to,
uint256 _amount,
bytes _userData,
address _operator,
bytes _operatorData,
bool _preventLocking
)
internal
{
requireMultiple(_amount);
callSender(_operator, _from, _to, _amount, _userData, _operatorData);
require(_to != address(0)); // forbid sending to 0x0 (=burning)
require(mBalances[_from] >= _amount); // ensure enough funds
mBalances[_from] = mBalances[_from].sub(_amount);
mBalances[_to] = mBalances[_to].add(_amount);
callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking);
emit Sent(_operator, _from, _to, _amount, _userData, _operatorData);
if (mErc20compatible) { emit Transfer(_from, _to, _amount); }
}
/**
* @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it.
* May throw according to `_preventLocking`
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData Data generated by the user to be passed to the recipient
* @param _operatorData Data generated by the operator to be passed to the recipient
* @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
* implementing `ERC777TokensRecipient`.
* ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
* functions SHOULD set this parameter to `false`.
*/
function callRecipient(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
) internal {
address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient");
if (recipientImplementation != 0) {
ERC777TokensRecipient(recipientImplementation).tokensReceived(
_operator, _from, _to, _amount, _userData, _operatorData);
} else if (_preventLocking) {
require(isRegularAddress(_to));
}
}
/**
* @notice Helper function that checks for ERC777TokensSender on the sender and calls it.
* May throw according to `_preventLocking`
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The amount of tokens to be sent
* @param _userData Data generated by the user to be passed to the recipient
* @param _operatorData Data generated by the operator to be passed to the recipient
* implementing `ERC777TokensSender`.
* ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
* functions SHOULD set this parameter to `false`.
*/
function callSender(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData
) internal {
address senderImplementation = interfaceAddr(_from, "ERC777TokensSender");
if (senderImplementation != 0) {
ERC777TokensSender(senderImplementation).tokensToSend(
_operator, _from, _to, _amount, _userData, _operatorData);
}
}
}
/**
* @title ERC20 Compatibility Contract
* @author Panos
*/
contract ERC20TokenCompat is ERC777Helper, Owned {
mapping(address => mapping(address => uint256)) private mAllowed;
/**
* @notice Contract construction
*/
constructor() public {
mErc20compatible = true;
setInterfaceImplementation("ERC20Token", this);
}
/**
* @notice This modifier is applied to erc20 obsolete methods that are
* implemented only to maintain backwards compatibility. When the erc20
* compatibility is disabled, this methods will fail.
*/
modifier erc20 () {
require(mErc20compatible);
_;
}
/**
* @notice Disables the ERC20 interface. This function can only be called
* by the owner.
*/
function disableERC20() public onlyOwner {
mErc20compatible = false;
setInterfaceImplementation("ERC20Token", 0x0);
}
/**
* @notice Re enables the ERC20 interface. This function can only be called
* by the owner.
*/
function enableERC20() public onlyOwner {
mErc20compatible = true;
setInterfaceImplementation("ERC20Token", this);
}
/*
* @notice For Backwards compatibility
* @return The decimals of the token. Forced to 18 in ERC777.
*/
function decimals() public erc20 view returns (uint8) {return uint8(18);}
/**
* @notice ERC20 backwards compatible transfer.
* @param _to The address of the recipient
* @param _amount The number of tokens to be transferred
* @return `true`, if the transfer can't be done, it should fail.
*/
function transfer(address _to, uint256 _amount) public erc20 returns (bool success) {
doSend(msg.sender, _to, _amount, "", msg.sender, "", false);
return true;
}
/**
* @notice ERC20 backwards compatible transferFrom.
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The number of tokens to be transferred
* @return `true`, if the transfer can't be done, it should fail.
*/
function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) {
require(_amount <= mAllowed[_from][msg.sender]);
// Cannot be after doSend because of tokensReceived re-entry
mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount);
doSend(_from, _to, _amount, "", msg.sender, "", false);
return true;
}
/**
* @notice ERC20 backwards compatible approve.
* `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf.
* @param _spender The address of the account able to transfer the tokens
* @param _amount The number of tokens to be approved for transfer
* @return `true`, if the approve can't be done, it should fail.
*/
function approve(address _spender, uint256 _amount) public erc20 returns (bool success) {
mAllowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @notice ERC20 backwards compatible allowance.
* This function makes it easy to read the `allowed[]` map
* @param _owner The address of the account that owns the token
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens of _owner that _spender is allowed
* to spend
*/
function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) {
return mAllowed[_owner][_spender];
}
}
/**
* @title ERC777 Standard Contract
* @author Panos
*/
contract ERC777StandardToken is ERC777Helper, Owned {
string private mName;
string private mSymbol;
uint256 private mTotalSupply;
mapping(address => mapping(address => bool)) private mAuthorized;
/**
* @notice Constructor to create a ERC777StandardToken
* @param _name Name of the new token
* @param _symbol Symbol of the new token.
* @param _totalSupply Total tokens issued
* @param _granularity Minimum transferable chunk.
*/
constructor(
string _name,
string _symbol,
uint256 _totalSupply,
uint256 _granularity
)
public {
require(_granularity >= 1);
require(_totalSupply > 0);
mName = _name;
mSymbol = _symbol;
mTotalSupply = _totalSupply;
mGranularity = _granularity;
mBalances[msg.sender] = mTotalSupply;
setInterfaceImplementation("ERC777Token", this);
}
/**
* @return the name of the token
*/
function name() public view returns (string) {return mName;}
/**
* @return the symbol of the token
*/
function symbol() public view returns (string) {return mSymbol;}
/**
* @return the granularity of the token
*/
function granularity() public view returns (uint256) {return mGranularity;}
/**
* @return the total supply of the token
*/
function totalSupply() public view returns (uint256) {return mTotalSupply;}
/**
* @notice Return the account balance of some account
* @param _tokenHolder Address for which the balance is returned
* @return the balance of `_tokenAddress`.
*/
function balanceOf(address _tokenHolder) public view returns (uint256) {return mBalances[_tokenHolder];}
/**
* @notice Send `_amount` of tokens to address `_to`
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
*/
function send(address _to, uint256 _amount) public {
doSend(msg.sender, _to, _amount, "", msg.sender, "", true);
}
/**
* @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData The user supplied data
*/
function send(address _to, uint256 _amount, bytes _userData) public {
doSend(msg.sender, _to, _amount, _userData, msg.sender, "", true);
}
/**
* @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens.
* @param _operator The operator that wants to be Authorized
*/
function authorizeOperator(address _operator) public {
require(_operator != msg.sender);
mAuthorized[_operator][msg.sender] = true;
emit AuthorizedOperator(_operator, msg.sender);
}
/**
* @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens.
* @param _operator The operator that wants to be Revoked
*/
function revokeOperator(address _operator) public {
require(_operator != msg.sender);
mAuthorized[_operator][msg.sender] = false;
emit RevokedOperator(_operator, msg.sender);
}
/**
* @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address.
* @param _operator address to check if it has the right to manage the tokens
* @param _tokenHolder address which holds the tokens to be managed
* @return `true` if `_operator` is authorized for `_tokenHolder`
*/
function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) {
return _operator == _tokenHolder || mAuthorized[_operator][_tokenHolder];
}
/**
* @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`.
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData Data generated by the user to be sent to the recipient
* @param _operatorData Data generated by the operator to be sent to the recipient
*/
function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public {
require(isOperatorFor(msg.sender, _from));
doSend(_from, _to, _amount, _userData, msg.sender, _operatorData, true);
}
}
/**
* @title ERC20 Multi Transfer Contract
* @author Panos
*/
contract ERC20Multi is ERC20TokenCompat {
/**
* @dev Transfer the specified amounts of tokens to the specified addresses.
* @dev Be aware that there is no check for duplicate recipients.
* @param _toAddresses Receiver addresses.
* @param _amounts Amounts of tokens that will be transferred.
*/
function multiPartyTransfer(address[] _toAddresses, uint256[] _amounts) external erc20 {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
transfer(_toAddresses[i], _amounts[i]);
}
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender.
* @dev Be aware that there is no check for duplicate recipients.
* @param _from The address of the sender
* @param _toAddresses The addresses of the recipients (MAX 255)
* @param _amounts The amounts of tokens to be transferred
*/
function multiPartyTransferFrom(address _from, address[] _toAddresses, uint256[] _amounts) external erc20 {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
transferFrom(_from, _toAddresses[i], _amounts[i]);
}
}
}
/**
* @title ERC777 Multi Transfer Contract
* @author Panos
*/
contract ERC777Multi is ERC777Helper {
/**
* @dev Transfer the specified amounts of tokens to the specified addresses as `_from`.
* @dev Be aware that there is no check for duplicate recipients.
* @param _from Address to use as sender
* @param _to Receiver addresses.
* @param _amounts Amounts of tokens that will be transferred.
* @param _userData User supplied data
* @param _operatorData Operator supplied data
*/
function multiOperatorSend(address _from, address[] _to, uint256[] _amounts, bytes _userData, bytes _operatorData)
external {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_to.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_to.length == _amounts.length);
for (uint8 i = 0; i < _to.length; i++) {
operatorSend(_from, _to[i], _amounts[i], _userData, _operatorData);
}
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses.
* @dev Be aware that there is no check for duplicate recipients.
* @param _toAddresses Receiver addresses.
* @param _amounts Amounts of tokens that will be transferred.
* @param _userData User supplied data
*/
function multiPartySend(address[] _toAddresses, uint256[] _amounts, bytes _userData) public {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
doSend(msg.sender, _toAddresses[i], _amounts[i], _userData, msg.sender, "", true);
}
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses.
* @dev Be aware that there is no check for duplicate recipients.
* @param _toAddresses Receiver addresses.
* @param _amounts Amounts of tokens that will be transferred.
*/
function multiPartySend(address[] _toAddresses, uint256[] _amounts) public {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
doSend(msg.sender, _toAddresses[i], _amounts[i], "", msg.sender, "", true);
}
}
}
/**
* @title Safe Guard Contract
* @author Panos
*/
contract SafeGuard is Owned {
event Transaction(address indexed destination, uint value, bytes data);
/**
* @dev Allows owner to execute a transaction.
*/
function executeTransaction(address destination, uint value, bytes data)
public
onlyOwner
{
require(externalCall(destination, value, data.length, data));
emit Transaction(destination, value, data);
}
/**
* @dev call has been separated into its own function in order to take advantage
* of the Solidity's code generator to produce a loop that copies tx.data into memory.
*/
function externalCall(address destination, uint value, uint dataLength, bytes data)
private
returns (bool) {
bool result;
assembly { // solhint-disable-line no-inline-assembly
let x := mload(0x40) // "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas, 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
}
/**
* @title ERC664 Standard Balances Contract
* @author chrisfranko
*/
contract ERC664Balances is SafeGuard {
using SafeMath for uint256;
uint256 public totalSupply;
event BalanceAdj(address indexed module, address indexed account, uint amount, string polarity);
event ModuleSet(address indexed module, bool indexed set);
mapping(address => bool) public modules;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
modifier onlyModule() {
require(modules[msg.sender]);
_;
}
/**
* @notice Constructor to create ERC664Balances
* @param _initialAmount Database initial amount
*/
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
}
/**
* @notice Set allowance of `_spender` in behalf of `_sender` at `_value`
* @param _sender Owner account
* @param _spender Spender account
* @param _value Value to approve
* @return Operation status
*/
function setApprove(address _sender, address _spender, uint256 _value) external onlyModule returns (bool) {
allowed[_sender][_spender] = _value;
return true;
}
/**
* @notice Decrease allowance of `_spender` in behalf of `_from` at `_value`
* @param _from Owner account
* @param _spender Spender account
* @param _value Value to decrease
* @return Operation status
*/
function decApprove(address _from, address _spender, uint _value) external onlyModule returns (bool) {
allowed[_from][_spender] = allowed[_from][_spender].sub(_value);
return true;
}
/**
* @notice Increase total supply by `_val`
* @param _val Value to increase
* @return Operation status
*/
function incTotalSupply(uint _val) external onlyOwner returns (bool) {
totalSupply = totalSupply.add(_val);
return true;
}
/**
* @notice Decrease total supply by `_val`
* @param _val Value to decrease
* @return Operation status
*/
function decTotalSupply(uint _val) external onlyOwner returns (bool) {
totalSupply = totalSupply.sub(_val);
return true;
}
/**
* @notice Set/Unset `_acct` as an authorized module
* @param _acct Module address
* @param _set Module set status
* @return Operation status
*/
function setModule(address _acct, bool _set) external onlyOwner returns (bool) {
modules[_acct] = _set;
emit ModuleSet(_acct, _set);
return true;
}
/**
* @notice Get `_acct` balance
* @param _acct Target account to get balance.
* @return The account balance
*/
function getBalance(address _acct) external view returns (uint256) {
return balances[_acct];
}
/**
* @notice Get allowance of `_spender` in behalf of `_owner`
* @param _owner Owner account
* @param _spender Spender account
* @return Allowance
*/
function getAllowance(address _owner, address _spender) external view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @notice Get if `_acct` is an authorized module
* @param _acct Module address
* @return Operation status
*/
function getModule(address _acct) external view returns (bool) {
return modules[_acct];
}
/**
* @notice Get total supply
* @return Total supply
*/
function getTotalSupply() external view returns (uint256) {
return totalSupply;
}
/**
* @notice Increment `_acct` balance by `_val`
* @param _acct Target account to increment balance.
* @param _val Value to increment
* @return Operation status
*/
function incBalance(address _acct, uint _val) public onlyModule returns (bool) {
balances[_acct] = balances[_acct].add(_val);
emit BalanceAdj(msg.sender, _acct, _val, "+");
return true;
}
/**
* @notice Decrement `_acct` balance by `_val`
* @param _acct Target account to decrement balance.
* @param _val Value to decrement
* @return Operation status
*/
function decBalance(address _acct, uint _val) public onlyModule returns (bool) {
balances[_acct] = balances[_acct].sub(_val);
emit BalanceAdj(msg.sender, _acct, _val, "-");
return true;
}
}
/**
* @title ERC664 Database Contract
* @author Panos
*/
contract CStore is ERC664Balances, ERC820Implementer {
mapping(address => mapping(address => bool)) private mAuthorized;
/**
* @notice Database construction
* @param _totalSupply The total supply of the token
* @param _registry The ERC820 Registry Address
*/
constructor(uint256 _totalSupply, address _registry) public
ERC664Balances(_totalSupply)
ERC820Implementer(_registry) {
setInterfaceImplementation("ERC664Balances", this);
}
/**
* @notice Increase total supply by `_val`
* @param _val Value to increase
* @return Operation status
*/
// solhint-disable-next-line no-unused-vars
function incTotalSupply(uint _val) external onlyOwner returns (bool) {
return false;
}
/**
* @notice Decrease total supply by `_val`
* @param _val Value to decrease
* @return Operation status
*/
// solhint-disable-next-line no-unused-vars
function decTotalSupply(uint _val) external onlyOwner returns (bool) {
return false;
}
/**
* @notice moving `_amount` from `_from` to `_to`
* @param _from The sender address
* @param _to The receiving address
* @param _amount The moving amount
* @return bool The move result
*/
function move(address _from, address _to, uint256 _amount) external
onlyModule
returns (bool) {
balances[_from] = balances[_from].sub(_amount);
emit BalanceAdj(msg.sender, _from, _amount, "-");
balances[_to] = balances[_to].add(_amount);
emit BalanceAdj(msg.sender, _to, _amount, "+");
return true;
}
/**
* @notice Setting operator `_operator` for `_tokenHolder`
* @param _operator The operator to set status
* @param _tokenHolder The token holder to set operator
* @param _status The operator status
* @return bool Status of operation
*/
function setOperator(address _operator, address _tokenHolder, bool _status) external
onlyModule
returns (bool) {
mAuthorized[_operator][_tokenHolder] = _status;
return true;
}
/**
* @notice Getting operator `_operator` for `_tokenHolder`
* @param _operator The operator address to get status
* @param _tokenHolder The token holder address
* @return bool Operator status
*/
function getOperator(address _operator, address _tokenHolder) external
view
returns (bool) {
return mAuthorized[_operator][_tokenHolder];
}
/**
* @notice Increment `_acct` balance by `_val`
* @param _acct Target account to increment balance.
* @param _val Value to increment
* @return Operation status
*/
// solhint-disable-next-line no-unused-vars
function incBalance(address _acct, uint _val) public onlyModule returns (bool) {
return false;
}
/**
* @notice Decrement `_acct` balance by `_val`
* @param _acct Target account to decrement balance.
* @param _val Value to decrement
* @return Operation status
*/
// solhint-disable-next-line no-unused-vars
function decBalance(address _acct, uint _val) public onlyModule returns (bool) {
return false;
}
}
/**
* @title ERC777 CALL Contract
* @author Panos
*/
contract CALL is ERC820Implementer, ERC777StandardToken, ERC20TokenCompat, ERC20Multi, ERC777Multi, SafeGuard {
using SafeMath for uint256;
CStore public balancesDB;
/**
* @notice Token construction
* @param _intRegistry The ERC820 Registry Address
* @param _name The name of the token
* @param _symbol The symbol of the token
* @param _totalSupply The total supply of the token
* @param _granularity The granularity of the token
* @param _balancesDB The address of balances database
*/
constructor(address _intRegistry, string _name, string _symbol, uint256 _totalSupply,
uint256 _granularity, address _balancesDB) public
ERC820Implementer(_intRegistry)
ERC777StandardToken(_name, _symbol, _totalSupply, _granularity) {
balancesDB = CStore(_balancesDB);
setInterfaceImplementation("ERC777CALLToken", this);
}
/**
* @notice change the balances database to `_newDB`
* @param _newDB The new balances database address
*/
function changeBalancesDB(address _newDB) public onlyOwner {
balancesDB = CStore(_newDB);
}
/**
* @notice ERC20 backwards compatible transferFrom using backendDB.
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The number of tokens to be transferred
* @return `true`, if the transfer can't be done, it should fail.
*/
function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) {
uint256 allowance = balancesDB.getAllowance(_from, msg.sender);
require(_amount <= allowance);
// Cannot be after doSend because of tokensReceived re-entry
require(balancesDB.decApprove(_from, msg.sender, _amount));
doSend(_from, _to, _amount, "", msg.sender, "", false);
return true;
}
/**
* @notice ERC20 backwards compatible approve.
* `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf.
* @param _spender The address of the account able to transfer the tokens
* @param _amount The number of tokens to be approved for transfer
* @return `true`, if the approve can't be done, it should fail.
*/
function approve(address _spender, uint256 _amount) public erc20 returns (bool success) {
require(balancesDB.setApprove(msg.sender, _spender, _amount));
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @notice ERC20 backwards compatible allowance.
* This function makes it easy to read the `allowed[]` map
* @param _owner The address of the account that owns the token
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens of _owner that _spender is allowed
* to spend
*/
function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) {
return balancesDB.getAllowance(_owner, _spender);
}
/**
* @return the total supply of the token
*/
function totalSupply() public view returns (uint256) {
return balancesDB.getTotalSupply();
}
/**
* @notice Return the account balance of some account
* @param _tokenHolder Address for which the balance is returned
* @return the balance of `_tokenAddress`.
*/
function balanceOf(address _tokenHolder) public view returns (uint256) {
return balancesDB.getBalance(_tokenHolder);
}
/**
* @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens at remote database.
* @param _operator The operator that wants to be Authorized
*/
function authorizeOperator(address _operator) public {
require(_operator != msg.sender);
require(balancesDB.setOperator(_operator, msg.sender, true));
emit AuthorizedOperator(_operator, msg.sender);
}
/**
* @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens at remote database.
* @param _operator The operator that wants to be Revoked
*/
function revokeOperator(address _operator) public {
require(_operator != msg.sender);
require(balancesDB.setOperator(_operator, msg.sender, false));
emit RevokedOperator(_operator, msg.sender);
}
/**
* @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder`
* address at remote database.
* @param _operator address to check if it has the right to manage the tokens
* @param _tokenHolder address which holds the tokens to be managed
* @return `true` if `_operator` is authorized for `_tokenHolder`
*/
function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) {
return _operator == _tokenHolder || balancesDB.getOperator(_operator, _tokenHolder);
}
/**
* @notice Helper function actually performing the sending of tokens using a backend database.
* @param _from The address holding the tokens being sent
* @param _to The address of the recipient
* @param _amount The number of tokens to be sent
* @param _userData Data generated by the user to be passed to the recipient
* @param _operatorData Data generated by the operator to be passed to the recipient
* @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not
* implementing `erc777_tokenHolder`.
* ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer
* functions SHOULD set this parameter to `false`.
*/
function doSend(
address _from,
address _to,
uint256 _amount,
bytes _userData,
address _operator,
bytes _operatorData,
bool _preventLocking
)
internal
{
requireMultiple(_amount);
callSender(_operator, _from, _to, _amount, _userData, _operatorData);
require(_to != address(0)); // forbid sending to 0x0 (=burning)
// require(mBalances[_from] >= _amount); // ensure enough funds
// (Not Required due to SafeMath throw if underflow in database and false check)
require(balancesDB.move(_from, _to, _amount));
callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking);
emit Sent(_operator, _from, _to, _amount, _userData, _operatorData);
if (mErc20compatible) { emit Transfer(_from, _to, _amount); }
}
} | * @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. @param _operator The operator that wants to be Authorized/ | function authorizeOperator(address _operator) public {
require(_operator != msg.sender);
mAuthorized[_operator][msg.sender] = true;
emit AuthorizedOperator(_operator, msg.sender);
}
| 1,825,421 | [
1,
18987,
279,
12126,
18285,
1375,
67,
9497,
68,
358,
10680,
261,
4661,
13,
1375,
3576,
18,
15330,
11294,
87,
2430,
18,
225,
389,
9497,
1021,
3726,
716,
14805,
358,
506,
6712,
1235,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12229,
5592,
12,
2867,
389,
9497,
13,
1071,
288,
203,
3639,
2583,
24899,
9497,
480,
1234,
18,
15330,
1769,
203,
3639,
312,
15341,
63,
67,
9497,
6362,
3576,
18,
15330,
65,
273,
638,
31,
203,
3639,
3626,
6712,
1235,
5592,
24899,
9497,
16,
1234,
18,
15330,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-02-02
*/
// File: contracts/interfaces/CERC20.sol
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
interface CERC20 {
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function totalReserves() external view returns (uint256);
function getCash() external view returns (uint256);
function totalBorrows() external view returns (uint256);
function reserveFactorMantissa() external view returns (uint256);
function interestRateModel() external view returns (address);
}
// File: contracts/interfaces/iERC20Fulcrum.sol
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
interface iERC20Fulcrum {
function mint(
address receiver,
uint256 depositAmount)
external
returns (uint256 mintAmount);
function burn(
address receiver,
uint256 burnAmount)
external
returns (uint256 loanAmountPaid);
function tokenPrice()
external
view
returns (uint256 price);
function supplyInterestRate()
external
view
returns (uint256);
function rateMultiplier()
external
view
returns (uint256);
function baseRate()
external
view
returns (uint256);
function borrowInterestRate()
external
view
returns (uint256);
function avgBorrowInterestRate()
external
view
returns (uint256);
function protocolInterestRate()
external
view
returns (uint256);
function spreadMultiplier()
external
view
returns (uint256);
function totalAssetBorrow()
external
view
returns (uint256);
function totalAssetSupply()
external
view
returns (uint256);
function nextSupplyInterestRate(uint256)
external
view
returns (uint256);
function nextBorrowInterestRate(uint256)
external
view
returns (uint256);
function nextLoanInterestRate(uint256)
external
view
returns (uint256);
function claimLoanToken()
external
returns (uint256 claimedAmount);
function dsr()
external
view
returns (uint256);
function chaiPrice()
external
view
returns (uint256);
}
// File: contracts/interfaces/ILendingProtocol.sol
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
interface ILendingProtocol {
function mint() external returns (uint256);
function redeem(address account) external returns (uint256);
function nextSupplyRate(uint256 amount) external view returns (uint256);
function nextSupplyRateWithParams(uint256[] calldata params) external view returns (uint256);
function getAPR() external view returns (uint256);
function getPriceInToken() external view returns (uint256);
function token() external view returns (address);
function underlying() external view returns (address);
}
// File: contracts/interfaces/WhitePaperInterestRateModel.sol
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
interface WhitePaperInterestRateModel {
function getBorrowRate(uint256 cash, uint256 borrows, uint256 _reserves) external view returns (uint256, uint256);
function getSupplyRate(uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa) external view returns (uint256);
function multiplier() external view returns (uint256);
function baseRate() external view returns (uint256);
function blocksPerYear() external view returns (uint256);
function dsrPerBlock() external view returns (uint256);
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
/*
* @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 { }
// 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/ownership/Ownable.sol
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
/**
* @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 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 {
_owner = _msgSender();
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;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
/**
* @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/math/SafeMath.sol
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
/**
* @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: contracts/IdleRebalancer.sol
/**
* @title: Idle Rebalancer contract
* @summary: Used for calculating amounts to lend on each implemented protocol.
* This implementation works with Compound and Fulcrum only,
* when a new protocol will be added this should be replaced
* @author: William Bergamo, idle.finance
*/
pragma solidity ^0.5.11; //inject UNLIMITED COMPILER VERSIONS
contract IdleRebalancer is Ownable {
using SafeMath for uint256;
// IdleToken address
address public idleToken;
// protocol token (cToken) address
address public cToken;
// protocol token (iToken) address
address public iToken;
// cToken protocol wrapper IdleCompound
address public cWrapper;
// iToken protocol wrapper IdleFulcrum
address public iWrapper;
// max % difference between next supply rate of Fulcrum and Compound
uint256 public maxRateDifference; // 10**17 -> 0.1 %
// max % difference between off-chain user supplied params for rebalance and actual amount to be rebalanced
uint256 public maxSupplyedParamsDifference; // 100000 -> 0.001%
// max number of recursive calls for bisection algorithm
uint256 public maxIterations;
/**
* @param _cToken : cToken address
* @param _iToken : iToken address
* @param _cWrapper : cWrapper address
* @param _iWrapper : iWrapper address
*/
constructor(address _cToken, address _iToken, address _cWrapper, address _iWrapper) public {
require(_cToken != address(0) && _iToken != address(0) && _cWrapper != address(0) && _iWrapper != address(0), 'some addr is 0');
cToken = _cToken;
iToken = _iToken;
cWrapper = _cWrapper;
iWrapper = _iWrapper;
maxRateDifference = 10**17; // 0.1%
maxSupplyedParamsDifference = 100000; // 0.001%
maxIterations = 30;
}
/**
* Throws if called by any account other than IdleToken contract.
*/
modifier onlyIdle() {
require(msg.sender == idleToken, "Ownable: caller is not IdleToken contract");
_;
}
// onlyOwner
/**
* sets idleToken address
* NOTE: can be called only once. It's not on the constructor because we are deploying this contract
* after the IdleToken contract
* @param _idleToken : idleToken address
*/
function setIdleToken(address _idleToken)
external onlyOwner {
require(idleToken == address(0), "idleToken addr already set");
require(_idleToken != address(0), "_idleToken addr is 0");
idleToken = _idleToken;
}
/**
* sets maxIterations for bisection recursive calls
* @param _maxIterations : max number of iterations for the bisection algorithm
*/
function setMaxIterations(uint256 _maxIterations)
external onlyOwner {
maxIterations = _maxIterations;
}
/**
* sets maxRateDifference
* @param _maxDifference : max rate difference in percentage scaled by 10**18
*/
function setMaxRateDifference(uint256 _maxDifference)
external onlyOwner {
maxRateDifference = _maxDifference;
}
/**
* sets maxSupplyedParamsDifference
* @param _maxSupplyedParamsDifference : max slippage between the rebalance params given from the client
* and actual amount to be rebalanced
*/
function setMaxSupplyedParamsDifference(uint256 _maxSupplyedParamsDifference)
external onlyOwner {
maxSupplyedParamsDifference = _maxSupplyedParamsDifference;
}
// end onlyOwner
/**
* Used by IdleToken contract to calculate the amount to be lended
* on each protocol in order to get the best available rate for all funds.
*
* @param _rebalanceParams : first param is the total amount to be rebalanced,
* all other elements are client side calculated amounts to put on each lending protocol
* @return tokenAddresses : array with all token addresses used,
* currently [cTokenAddress, iTokenAddress]
* @return amounts : array with all amounts for each protocol in order,
* currently [amountCompound, amountFulcrum]
*/
function calcRebalanceAmounts(uint256[] calldata _rebalanceParams)
external view onlyIdle
returns (address[] memory tokenAddresses, uint256[] memory amounts)
{
// Get all params for calculating Compound nextSupplyRateWithParams
CERC20 _cToken = CERC20(cToken);
WhitePaperInterestRateModel white = WhitePaperInterestRateModel(_cToken.interestRateModel());
uint256[] memory paramsCompound = new uint256[](10);
paramsCompound[0] = 10**18; // j
paramsCompound[1] = white.baseRate(); // a
paramsCompound[2] = _cToken.totalBorrows(); // b
paramsCompound[3] = white.multiplier(); // c
paramsCompound[4] = _cToken.totalReserves(); // d
paramsCompound[5] = paramsCompound[0].sub(_cToken.reserveFactorMantissa()); // e
paramsCompound[6] = _cToken.getCash(); // s
paramsCompound[7] = white.blocksPerYear(); // k
paramsCompound[8] = 100; // f
// Get all params for calculating Fulcrum nextSupplyRateWithParams
iERC20Fulcrum _iToken = iERC20Fulcrum(iToken);
uint256[] memory paramsFulcrum = new uint256[](4);
paramsFulcrum[0] = _iToken.protocolInterestRate(); // a1
paramsFulcrum[1] = _iToken.totalAssetBorrow(); // b1
paramsFulcrum[2] = _iToken.totalAssetSupply(); // s1
tokenAddresses = new address[](2);
tokenAddresses[0] = cToken;
tokenAddresses[1] = iToken;
// _rebalanceParams should be [totAmountToRebalance, amountCompound, amountFulcrum];
if (_rebalanceParams.length == 3) {
(bool amountsAreCorrect, uint256[] memory checkedAmounts) = checkRebalanceAmounts(_rebalanceParams, paramsCompound, paramsFulcrum);
if (amountsAreCorrect) {
return (tokenAddresses, checkedAmounts);
}
}
// Initial guess for shrinking initial bisection interval
/*
Compound: (getCash returns the available supply only, not the borrowed one)
getCash + totalBorrows = totalSuppliedCompound
Fulcrum:
totalSupply = totalSuppliedFulcrum
we try to correlate borrow and supply on both markets
totC = totalSuppliedCompound + totalBorrowsCompound
totF = totalSuppliedFulcrum + totalBorrowsFulcrum
n : (totC + totF) = x : totF
x = n * totF / (totC + totF)
*/
uint256 amountFulcrum = _rebalanceParams[0].mul(paramsFulcrum[2].add(paramsFulcrum[1])).div(
paramsFulcrum[2].add(paramsFulcrum[1]).add(paramsCompound[6].add(paramsCompound[2]).add(paramsCompound[2]))
);
// Recursive bisection algorithm
amounts = bisectionRec(
_rebalanceParams[0].sub(amountFulcrum), // amountCompound
amountFulcrum,
maxRateDifference, // 0.1% of rate difference,
0, // currIter
maxIterations, // maxIter
_rebalanceParams[0],
paramsCompound,
paramsFulcrum
); // returns [amountCompound, amountFulcrum]
return (tokenAddresses, amounts);
}
/**
* Used by IdleToken contract to check if provided amounts
* causes the rates of Fulcrum and Compound to be balanced
* (counting a tolerance)
*
* @param rebalanceParams : first element is the total amount to be rebalanced,
* the rest is an array with all amounts for each protocol in order,
* currently [amountCompound, amountFulcrum]
* @param paramsCompound : array with all params (except for the newDAIAmount)
* for calculating next supply rate of Compound
* @param paramsFulcrum : array with all params (except for the newDAIAmount)
* for calculating next supply rate of Fulcrum
* @return bool : if provided amount correctly rebalances the pool
*/
function checkRebalanceAmounts(
uint256[] memory rebalanceParams,
uint256[] memory paramsCompound,
uint256[] memory paramsFulcrum
)
internal view
returns (bool, uint256[] memory checkedAmounts)
{
// This is the amount that should be rebalanced no more no less
uint256 actualAmountToBeRebalanced = rebalanceParams[0]; // n
// interest is earned between when tx was submitted and when it is mined so params sent by users
// should always be slightly less than what should be rebalanced
uint256 totAmountSentByUser;
for (uint8 i = 1; i < rebalanceParams.length; i++) {
totAmountSentByUser = totAmountSentByUser.add(rebalanceParams[i]);
}
// check if amounts sent from user are less than actualAmountToBeRebalanced and
// at most `actualAmountToBeRebalanced - 0.001% of (actualAmountToBeRebalanced)`
if (totAmountSentByUser > actualAmountToBeRebalanced ||
totAmountSentByUser.add(totAmountSentByUser.div(maxSupplyedParamsDifference)) < actualAmountToBeRebalanced) {
return (false, new uint256[](2));
}
uint256 interestToBeSplitted = actualAmountToBeRebalanced.sub(totAmountSentByUser);
// sets newDAIAmount for each protocol
paramsCompound[9] = rebalanceParams[1].add(interestToBeSplitted.div(2));
paramsFulcrum[3] = rebalanceParams[2].add(interestToBeSplitted.sub(interestToBeSplitted.div(2)));
// calculate next rates with amountCompound and amountFulcrum
// For Fulcrum see https://github.com/bZxNetwork/bZx-monorepo/blob/development/packages/contracts/extensions/loanTokenization/contracts/LoanToken/LoanTokenLogicV3.sol#L1418
// fulcrumUtilRate = fulcrumBorrow.mul(10**20).div(assetSupply);
uint256 currFulcRate = (paramsFulcrum[1].mul(10**20).div(paramsFulcrum[2])) > 90 ether ?
ILendingProtocol(iWrapper).nextSupplyRate(paramsFulcrum[3]) :
ILendingProtocol(iWrapper).nextSupplyRateWithParams(paramsFulcrum);
uint256 currCompRate = ILendingProtocol(cWrapper).nextSupplyRateWithParams(paramsCompound);
bool isCompoundBest = currCompRate > currFulcRate;
// |fulcrumRate - compoundRate| <= tolerance
bool areParamsOk = (currFulcRate.add(maxRateDifference) >= currCompRate && isCompoundBest) ||
(currCompRate.add(maxRateDifference) >= currFulcRate && !isCompoundBest);
uint256[] memory actualParams = new uint256[](2);
actualParams[0] = paramsCompound[9];
actualParams[1] = paramsFulcrum[3];
return (areParamsOk, actualParams);
}
/**
* Internal implementation of our bisection algorithm
*
* @param amountCompound : amount to be lended in compound in current iteration
* @param amountFulcrum : amount to be lended in Fulcrum in current iteration
* @param tolerance : max % difference between next supply rate of Fulcrum and Compound
* @param currIter : current iteration
* @param maxIter : max number of iterations
* @param n : amount of underlying tokens (eg. DAI) to rebalance
* @param paramsCompound : array with all params (except for the newDAIAmount)
* for calculating next supply rate of Compound
* @param paramsFulcrum : array with all params (except for the newDAIAmount)
* for calculating next supply rate of Fulcrum
* @return amounts : array with all amounts for each protocol in order,
* currently [amountCompound, amountFulcrum]
*/
function bisectionRec(
uint256 amountCompound, uint256 amountFulcrum,
uint256 tolerance, uint256 currIter, uint256 maxIter, uint256 n,
uint256[] memory paramsCompound,
uint256[] memory paramsFulcrum
)
internal view
returns (uint256[] memory amounts) {
// sets newDAIAmount for each protocol
paramsCompound[9] = amountCompound;
paramsFulcrum[3] = amountFulcrum;
// calculate next rates with amountCompound and amountFulcrum
// For Fulcrum see https://github.com/bZxNetwork/bZx-monorepo/blob/development/packages/contracts/extensions/loanTokenization/contracts/LoanToken/LoanTokenLogicV3.sol#L1418
// fulcrumUtilRate = fulcrumBorrow.mul(10**20).div(assetSupply);
uint256 currFulcRate = (paramsFulcrum[1].mul(10**20).div(paramsFulcrum[2])) > 90 ether ?
ILendingProtocol(iWrapper).nextSupplyRate(amountFulcrum) :
ILendingProtocol(iWrapper).nextSupplyRateWithParams(paramsFulcrum);
uint256 currCompRate = ILendingProtocol(cWrapper).nextSupplyRateWithParams(paramsCompound);
bool isCompoundBest = currCompRate > currFulcRate;
// bisection interval update, we choose to halve the smaller amount
uint256 step = amountCompound < amountFulcrum ? amountCompound.div(2) : amountFulcrum.div(2);
// base case
// |fulcrumRate - compoundRate| <= tolerance
if (
((currFulcRate.add(tolerance) >= currCompRate && isCompoundBest) ||
(currCompRate.add(tolerance) >= currFulcRate && !isCompoundBest)) ||
currIter >= maxIter
) {
amounts = new uint256[](2);
amounts[0] = amountCompound;
amounts[1] = amountFulcrum;
return amounts;
}
return bisectionRec(
isCompoundBest ? amountCompound.add(step) : amountCompound.sub(step),
isCompoundBest ? amountFulcrum.sub(step) : amountFulcrum.add(step),
tolerance, currIter + 1, maxIter, n,
paramsCompound, // paramsCompound[9] would be overwritten on next iteration
paramsFulcrum // paramsFulcrum[3] would be overwritten on next iteration
);
}
} | sets newDAIAmount for each protocol | paramsCompound[9] = rebalanceParams[1].add(interestToBeSplitted.div(2));
| 1,767,272 | [
1,
4424,
394,
9793,
45,
6275,
364,
1517,
1771,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
859,
16835,
63,
29,
65,
273,
283,
12296,
1370,
63,
21,
8009,
1289,
12,
2761,
395,
15360,
5521,
2344,
18,
2892,
12,
22,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xE83E7B1E80488b1549887bAe14735764Df0F7B5c/sources/contracts/Ozacoin.sol | * @notice Construct a new Ozacoin token/ | constructor() ERC20("Ozacoin", "OZA") ERC20Permit("Ozacoin") {
_mint(msg.sender, 100000000 * 10 ** decimals());
}
| 16,601,280 | [
1,
7249,
279,
394,
531,
94,
1077,
885,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
51,
94,
1077,
885,
3113,
315,
51,
62,
37,
7923,
4232,
39,
3462,
9123,
305,
2932,
51,
94,
1077,
885,
7923,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
2130,
9449,
380,
1728,
2826,
15105,
10663,
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
] |
./full_match/1/0xEcFaaC1D527C227D4ad13ccAf544867F1CDc1d66/sources/contracts/coin.sol | wallet address here:approve pancake _approve(msg.sender, 0x10ED43C718714eb63d5aA57B78B54704E256024E, 5000000000000000000000000000);approve uniswap | constructor() ERC20("Safe Rocket", "SRT"){
_mint(msg.sender, 10000000000000000000000000000);
_burn(msg.sender, 5000000000000000000000000000);
_transfer(msg.sender, 0xBcfB4020d13E2057448881184781E533B987Bb5B, 5000000000000000000000000000);
_approve(msg.sender, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 5000000000000000000000000000);
}
| 8,459,142 | [
1,
19177,
1758,
2674,
30,
12908,
537,
2800,
23780,
389,
12908,
537,
12,
3576,
18,
15330,
16,
374,
92,
2163,
2056,
8942,
39,
27,
2643,
27,
3461,
24008,
4449,
72,
25,
69,
37,
10321,
38,
8285,
38,
6564,
27,
3028,
41,
5034,
3103,
24,
41,
16,
1381,
12648,
12648,
12648,
3784,
1769,
12908,
537,
640,
291,
91,
438,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4232,
39,
3462,
2932,
9890,
534,
1861,
3113,
315,
10090,
56,
7923,
95,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
2130,
12648,
12648,
2787,
9449,
1769,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
1381,
12648,
12648,
12648,
3784,
1769,
203,
3639,
389,
13866,
12,
3576,
18,
15330,
16,
374,
20029,
8522,
38,
24,
3103,
20,
72,
3437,
41,
31777,
5608,
24,
5482,
28,
2499,
5193,
8285,
21,
41,
25,
3707,
38,
10689,
27,
38,
70,
25,
38,
16,
1381,
12648,
12648,
12648,
3784,
1769,
203,
540,
203,
3639,
389,
12908,
537,
12,
3576,
18,
15330,
16,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
16,
1381,
12648,
12648,
12648,
3784,
1769,
203,
3639,
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
] |
./full_match/421611/0xD85391F2863ed10244e7A8348538Aa4354F91034/sources/_aave/core-v3/contracts/dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol | * @title BaseUpgradeabilityProxy @dev This contract implements a proxy that allows to change the implementation address to which it will delegate. Such a change is called an implementation upgrade./ | contract BaseUpgradeabilityProxy is Proxy {
event Upgraded(address indexed implementation);
bytes32 internal constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
pragma solidity 0.8.7;
function _implementation() internal view override returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _implementation() internal view override returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
'Cannot set a proxy implementation to a non-contract address'
);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
'Cannot set a proxy implementation to a non-contract address'
);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
| 13,220,607 | [
1,
2171,
10784,
2967,
3886,
225,
1220,
6835,
4792,
279,
2889,
716,
5360,
358,
2549,
326,
4471,
1758,
358,
1492,
518,
903,
7152,
18,
8002,
279,
2549,
353,
2566,
392,
4471,
8400,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3360,
10784,
2967,
3886,
353,
7659,
288,
203,
225,
871,
1948,
19305,
12,
2867,
8808,
4471,
1769,
203,
203,
225,
1731,
1578,
2713,
5381,
15694,
7618,
2689,
67,
55,
1502,
56,
273,
203,
565,
374,
92,
29751,
6675,
24,
69,
3437,
12124,
21,
69,
1578,
2163,
6028,
27,
71,
11149,
5193,
9975,
1966,
10689,
72,
5353,
23,
73,
3462,
6669,
952,
6418,
4763,
69,
29,
3462,
69,
23,
5353,
3361,
25,
72,
7414,
22,
9897,
71,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
27,
31,
203,
225,
445,
389,
30810,
1435,
2713,
1476,
3849,
1135,
261,
2867,
9380,
13,
288,
203,
565,
1731,
1578,
4694,
273,
15694,
7618,
2689,
67,
55,
1502,
56,
31,
203,
565,
19931,
288,
203,
1377,
9380,
519,
272,
945,
12,
14194,
13,
203,
565,
289,
203,
225,
289,
203,
203,
225,
445,
389,
30810,
1435,
2713,
1476,
3849,
1135,
261,
2867,
9380,
13,
288,
203,
565,
1731,
1578,
4694,
273,
15694,
7618,
2689,
67,
55,
1502,
56,
31,
203,
565,
19931,
288,
203,
1377,
9380,
519,
272,
945,
12,
14194,
13,
203,
565,
289,
203,
225,
289,
203,
203,
225,
445,
389,
15097,
774,
12,
2867,
394,
13621,
13,
2713,
288,
203,
565,
389,
542,
13621,
12,
2704,
13621,
1769,
203,
565,
3626,
1948,
19305,
12,
2704,
13621,
1769,
203,
225,
289,
203,
203,
225,
445,
389,
542,
13621,
12,
2867,
394,
13621,
13,
2713,
288,
203,
565,
2583,
12,
203,
1377,
5267,
18,
291,
8924,
12,
2704,
13621,
3631,
203,
1377,
296,
4515,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/ModelInterface.sol";
import "../ModelStorage.sol";
import "../3rdDeFiInterfaces/CTokenInterface.sol";
import "../3rdDeFiInterfaces/IUniswapV2Router.sol";
import "../3rdDeFiInterfaces/IComptroller.sol";
contract WbtcModel is ModelInterface, ModelStorage {
using SafeERC20 for IERC20;
using SafeMath for uint256;
event Swap(uint256 compAmount, uint256 underlying);
address _cToken;
address _comp;
address _comptroller;
address _uRouterV2;
uint256 public leverage;
IComptroller public Comptroller;
function initialize(
address forge_,
address token_,
address cToken_,
address comp_,
address comptroller_,
address uRouterV2_
) public {
addToken(token_);
setForge(forge_);
_cToken = cToken_;
_comp = comp_;
_comptroller = comptroller_;
_uRouterV2 = uRouterV2_;
Comptroller = IComptroller(_comptroller);
leverage = 30;
}
function underlyingBalanceInModel() public view override returns (uint256) {
return IERC20(token(0)).balanceOf(address(this));
}
function underlyingBalanceWithInvestment() public view override returns (uint256) {
// Hard Work Now! For Punkers by 0xViktor
return
underlyingBalanceInModel().add(
CTokenInterface(_cToken).exchangeRateStored().mul(_cTokenBalanceOf()).div(1e18)
);
}
function invest() public override {
// Hard Work Now! For Punkers by 0xViktor
IERC20(token(0)).safeApprove(_cToken, underlyingBalanceInModel());
emit Invest(underlyingBalanceInModel(), block.timestamp);
CTokenInterface(_cToken).mint(underlyingBalanceInModel());
_borrow();
}
function reInvest() public {
// Hard Work Now! For Punkers by 0xViktor
_claimComp();
_swapCompToUnderlying();
invest();
}
function withdrawAllToForge() public override OnlyForge {
// Hard Work Now! For Punkers by 0xViktor
_claimComp();
_swapCompToUnderlying();
_repay(CTokenInterface(_cToken).balanceOfUnderlying(address(this)).mul(leverage).div(100));
emit Withdraw(underlyingBalanceWithInvestment(), forge(), block.timestamp);
CTokenInterface(_cToken).redeem(_cTokenBalanceOf());
}
function withdrawToForge(uint256 amount) public override OnlyForge {
withdrawTo(amount, forge());
}
function withdrawTo(uint256 amount, address to) public override OnlyForge {
// Hard Work Now! For Punkers by 0xViktor
_repay(amount.mul(leverage).div(100));
uint256 oldBalance = IERC20(token(0)).balanceOf(address(this));
amount = Math.min(amount, CTokenInterface(_cToken).balanceOfUnderlying(address(this)));
amount = CTokenInterface(_cToken).redeemUnderlying(amount);
uint256 newBalance = IERC20(token(0)).balanceOf(address(this));
require(newBalance.sub(oldBalance) > 0, "MODEL : REDEEM BALANCE IS ZERO");
IERC20(token(0)).safeTransfer(to, newBalance.sub(oldBalance));
emit Withdraw(amount, forge(), block.timestamp);
}
function setLeveragePercent(uint256 _leveragePercent) external OnlyForge {
leverage = _leveragePercent;
_borrow();
}
function _borrow() internal {
uint256 borrowBalance = CTokenInterface(_cToken).borrowBalanceCurrent(address(this));
uint256 availableCollateral = CTokenInterface(_cToken).balanceOfUnderlying(address(this)).sub(borrowBalance);
uint256 canBorrowAmount = availableCollateral.mul(leverage).div(100);
if (borrowBalance > canBorrowAmount) {
_repay(borrowBalance.sub(canBorrowAmount));
return;
}
uint256 toBorrow = canBorrowAmount.sub(borrowBalance);
CTokenInterface(_cToken).borrow(toBorrow);
CTokenInterface(_cToken).mint(toBorrow);
}
function _repay(uint256 _amount) internal {
_amount = Math.min(_amount, CTokenInterface(_cToken).borrowBalanceCurrent(address(this)));
CTokenInterface(_cToken).redeemUnderlying(_amount);
CTokenInterface(_cToken).repayBorrow(_amount);
}
function _cTokenBalanceOf() internal view returns (uint256) {
return CTokenInterface(_cToken).balanceOf(address(this));
}
function _claimComp() internal {
// Hard Work Now! For Punkers by 0xViktor
CTokenInterface(_comptroller).claimComp(address(this));
}
function _swapCompToUnderlying() internal {
// Hard Work Now! For Punkers by 0xViktor
uint256 balance = IERC20(_comp).balanceOf(address(this));
if (balance > 0) {
IERC20(_comp).safeApprove(_uRouterV2, balance);
address[] memory path = new address[](3);
path[0] = address(_comp);
path[1] = IUniswapV2Router02(_uRouterV2).WETH();
path[2] = address(token(0));
IUniswapV2Router02(_uRouterV2).swapExactTokensForTokens(
balance,
1,
path,
address(this),
block.timestamp + (15 * 60)
);
emit Swap(balance, underlyingBalanceInModel());
}
}
}
| Hard Work Now! For Punkers by 0xViktor | function _claimComp() internal {
CTokenInterface(_comptroller).claimComp(address(this));
}
| 5,393,039 | [
1,
29601,
4147,
4494,
5,
2457,
453,
1683,
414,
635,
374,
92,
58,
1766,
13039,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
14784,
2945,
1435,
2713,
288,
203,
3639,
385,
1345,
1358,
24899,
832,
337,
1539,
2934,
14784,
2945,
12,
2867,
12,
2211,
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,
-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-04-22
*/
// SPDX-License-Identifier: MIT
/*
This is a Stacker.vc FarmTreasury version 1 contract. It deploys a rebase token where it rebases to be equivalent to it's underlying token. 1 stackUSDT = 1 USDT.
The underlying assets are used to farm on different smart contract and produce yield via the ever-expanding DeFi ecosystem.
THANKS! To Lido DAO for the inspiration in more ways than one, but especially for a lot of the code here.
If you haven't already, stake your ETH for ETH2.0 with Lido.fi!
Also thanks for Aragon for hosting our Stacker Ventures DAO, and for more inspiration!
*/
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.11;
/*
* @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;
}
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @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;
}
}
/**
* @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);
}
/**
* @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");
}
}
}
abstract contract FarmTokenV1 is IERC20 {
using SafeMath for uint256;
using Address for address;
// shares are how a users balance is generated. For rebase tokens, balances are always generated at runtime, while shares stay constant.
// shares is your proportion of the total pool of invested UnderlyingToken
// shares are like a Compound.finance cToken, while our token balances are like an Aave aToken.
mapping(address => uint256) private shares;
mapping(address => mapping (address => uint256)) private allowances;
uint256 public totalShares;
string public name;
string public symbol;
string public underlying;
address public underlyingContract;
uint8 public decimals;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(string memory _name, uint8 _decimals, address _underlyingContract) public {
name = string(abi.encodePacked(abi.encodePacked("Stacker Ventures ", _name), " v1"));
symbol = string(abi.encodePacked("stack", _name));
underlying = _name;
decimals = _decimals;
underlyingContract = _underlyingContract;
}
// 1 stackToken = 1 underlying token
function totalSupply() external override view returns (uint256){
return _getTotalUnderlying();
}
function totalUnderlying() external view returns (uint256){
return _getTotalUnderlying();
}
function balanceOf(address _account) public override view returns (uint256){
return getUnderlyingForShares(_sharesOf(_account));
}
// transfer tokens, not shares
function transfer(address _recipient, uint256 _amount) external override returns (bool){
_verify(msg.sender, _amount);
_transfer(msg.sender, _recipient, _amount);
return true;
}
function transferFrom(address _sender, address _recipient, uint256 _amount) external override returns (bool){
_verify(_sender, _amount);
uint256 _currentAllowance = allowances[_sender][msg.sender];
require(_currentAllowance >= _amount, "FARMTOKENV1: not enough allowance");
_transfer(_sender, _recipient, _amount);
_approve(_sender, msg.sender, _currentAllowance.sub(_amount));
return true;
}
// this checks if a transfer/transferFrom/withdraw is allowed. There are some conditions on withdraws/transfers from new deposits
// function stub, this needs to be implemented in a contract which inherits this for a valid deployment
// IMPLEMENT THIS
function _verify(address _account, uint256 _amountUnderlyingToSend) internal virtual;
// allow tokens, not shares
function allowance(address _owner, address _spender) external override view returns (uint256){
return allowances[_owner][_spender];
}
// approve tokens, not shares
function approve(address _spender, uint256 _amount) external override returns (bool){
_approve(msg.sender, _spender, _amount);
return true;
}
// shares of _account
function sharesOf(address _account) external view returns (uint256) {
return _sharesOf(_account);
}
// how many shares for _amount of underlying?
// if there are no shares, or no underlying yet, we are initing the contract or suffered a total loss
// either way, init this state at 1:1 shares:underlying
function getSharesForUnderlying(uint256 _amountUnderlying) public view returns (uint256){
uint256 _totalUnderlying = _getTotalUnderlying();
if (_totalUnderlying == 0){
return _amountUnderlying; // this will init at 1:1 _underlying:_shares
}
uint256 _totalShares = totalShares;
if (_totalShares == 0){
return _amountUnderlying; // this will init the first shares, expected contract underlying balance == 0, or there will be a bonus (doesn't belong to anyone so ok)
}
return _amountUnderlying.mul(_totalShares).div(_totalUnderlying);
}
// how many underlying for _amount of shares?
// if there are no shares, or no underlying yet, we are initing the contract or suffered a total loss
// either way, init this state at 1:1 shares:underlying
function getUnderlyingForShares(uint256 _amountShares) public view returns (uint256){
uint256 _totalShares = totalShares;
if (_totalShares == 0){
return _amountShares; // this will init at 1:1 _shares:_underlying
}
uint256 _totalUnderlying = _getTotalUnderlying();
if (_totalUnderlying == 0){
return _amountShares; // this will init at 1:1
}
return _amountShares.mul(_totalUnderlying).div(_totalShares);
}
function _sharesOf(address _account) internal view returns (uint256){
return shares[_account];
}
// function stub, this needs to be implemented in a contract which inherits this for a valid deployment
// sum the contract balance + working balance withdrawn from the contract and actively farming
// IMPLEMENT THIS
function _getTotalUnderlying() internal virtual view returns (uint256);
// in underlying
function _transfer(address _sender, address _recipient, uint256 _amount) internal {
uint256 _sharesToTransfer = getSharesForUnderlying(_amount);
_transferShares(_sender, _recipient, _sharesToTransfer);
emit Transfer(_sender, _recipient, _amount);
}
// in underlying
function _approve(address _owner, address _spender, uint256 _amount) internal {
require(_owner != address(0), "FARMTOKENV1: from == 0x0");
require(_spender != address(0), "FARMTOKENV1: to == 0x00");
allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
function _transferShares(address _sender, address _recipient, uint256 _amountShares) internal {
require(_sender != address(0), "FARMTOKENV1: from == 0x00");
require(_recipient != address(0), "FARMTOKENV1: to == 0x00");
uint256 _currentSenderShares = shares[_sender];
require(_amountShares <= _currentSenderShares, "FARMTOKENV1: transfer amount exceeds balance");
shares[_sender] = _currentSenderShares.sub(_amountShares);
shares[_recipient] = shares[_recipient].add(_amountShares);
}
function _mintShares(address _recipient, uint256 _amountShares) internal {
require(_recipient != address(0), "FARMTOKENV1: to == 0x00");
totalShares = totalShares.add(_amountShares);
shares[_recipient] = shares[_recipient].add(_amountShares);
// NOTE: we're not emitting a Transfer event from the zero address here
// If we mint shares with no underlying, we basically just diluted everyone
// It's not possible to send events from _everyone_ to reflect each balance dilution (ie: balance going down)
// Not compliant to ERC20 standard...
}
function _burnShares(address _account, uint256 _amountShares) internal {
require(_account != address(0), "FARMTOKENV1: burn from == 0x00");
uint256 _accountShares = shares[_account];
require(_amountShares <= _accountShares, "FARMTOKENV1: burn amount exceeds balance");
totalShares = totalShares.sub(_amountShares);
shares[_account] = _accountShares.sub(_amountShares);
// NOTE: we're not emitting a Transfer event to the zero address here
// If we burn shares without burning/withdrawing the underlying
// then it looks like a system wide credit to everyones balance
// It's not possible to send events to _everyone_ to reflect each balance credit (ie: balance going up)
// Not compliant to ERC20 standard...
}
}
contract FarmTreasuryV1 is ReentrancyGuard, FarmTokenV1 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Address for address;
mapping(address => DepositInfo) public userDeposits;
mapping(address => bool) public noLockWhitelist;
struct DepositInfo {
uint256 amountUnderlyingLocked;
uint256 timestampDeposit;
uint256 timestampUnlocked;
}
uint256 internal constant LOOP_LIMIT = 200;
address payable public governance;
address payable public farmBoss;
bool public paused = false;
bool public pausedDeposits = false;
// fee schedule, can be changed by governance, in bips
// performance fee is on any gains, base fee is on AUM/yearly
uint256 public constant max = 10000;
uint256 public performanceToTreasury = 1000;
uint256 public performanceToFarmer = 1000;
uint256 public baseToTreasury = 100;
uint256 public baseToFarmer = 100;
// limits on rebalancing from the farmer, trying to negate errant rebalances
uint256 public rebalanceUpLimit = 100; // maximum of a 1% gain per rebalance
uint256 public rebalanceUpWaitTime = 23 hours;
uint256 public lastRebalanceUpTime;
// waiting period on withdraws from time of deposit
// locked amount linearly decreases until the time is up, so at waitPeriod/2 after deposit, you can withdraw depositAmt/2 funds.
uint256 public waitPeriod = 1 weeks;
// hot wallet holdings for instant withdraw, in bips
// if the hot wallet balance expires, the users will need to wait for the next rebalance period in order to withdraw
uint256 public hotWalletHoldings = 1000; // 10% initially
uint256 public ACTIVELY_FARMED;
event RebalanceHot(uint256 amountIn, uint256 amountToFarmer, uint256 timestamp);
event ProfitDeclared(bool profit, uint256 amount, uint256 timestamp, uint256 totalAmountInPool, uint256 totalSharesInPool, uint256 performanceFeeTotal, uint256 baseFeeTotal);
event Deposit(address depositor, uint256 amount, address referral);
event Withdraw(address withdrawer, uint256 amount);
constructor(string memory _nameUnderlying, uint8 _decimalsUnderlying, address _underlying) public FarmTokenV1(_nameUnderlying, _decimalsUnderlying, _underlying) {
governance = msg.sender;
lastRebalanceUpTime = block.timestamp;
}
function setGovernance(address payable _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
governance = _new;
}
// the "farmBoss" is a trusted smart contract that functions kind of like an EOA.
// HOWEVER specific contract addresses need to be whitelisted in order for this contract to be allowed to interact w/ them
// the governance has full control over the farmBoss, and other addresses can have partial control for strategy rotation/rebalancing
function setFarmBoss(address payable _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
farmBoss = _new;
}
function setNoLockWhitelist(address[] calldata _accounts, bool[] calldata _noLock) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_accounts.length == _noLock.length && _accounts.length <= LOOP_LIMIT, "FARMTREASURYV1: check array lengths");
for (uint256 i = 0; i < _accounts.length; i++){
noLockWhitelist[_accounts[i]] = _noLock[i];
}
}
function pause() external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
paused = true;
}
function unpause() external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
paused = false;
}
function pauseDeposits() external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
pausedDeposits = true;
}
function unpauseDeposits() external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
pausedDeposits = false;
}
function setFeeDistribution(uint256 _performanceToTreasury, uint256 _performanceToFarmer, uint256 _baseToTreasury, uint256 _baseToFarmer) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_performanceToTreasury.add(_performanceToFarmer) < max, "FARMTREASURYV1: too high performance");
require(_baseToTreasury.add(_baseToFarmer) <= 500, "FARMTREASURYV1: too high base");
performanceToTreasury = _performanceToTreasury;
performanceToFarmer = _performanceToFarmer;
baseToTreasury = _baseToTreasury;
baseToFarmer = _baseToFarmer;
}
function setWaitPeriod(uint256 _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_new <= 10 weeks, "FARMTREASURYV1: too long wait");
waitPeriod = _new;
}
function setHotWalletHoldings(uint256 _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_new <= max && _new >= 100, "FARMTREASURYV1: hot wallet values bad");
hotWalletHoldings = _new;
}
function setRebalanceUpLimit(uint256 _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_new < max, "FARMTREASURYV1: >= max");
rebalanceUpLimit = _new;
}
function setRebalanceUpWaitTime(uint256 _new) external {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
require(_new <= 1 weeks, "FARMTREASURYV1: > 1 week");
rebalanceUpWaitTime = _new;
}
function deposit(uint256 _amountUnderlying, address _referral) external nonReentrant {
require(_amountUnderlying > 0, "FARMTREASURYV1: amount == 0");
require(!paused && !pausedDeposits, "FARMTREASURYV1: paused");
_deposit(_amountUnderlying, _referral);
IERC20 _underlying = IERC20(underlyingContract);
uint256 _before = _underlying.balanceOf(address(this));
_underlying.safeTransferFrom(msg.sender, address(this), _amountUnderlying);
uint256 _after = _underlying.balanceOf(address(this));
uint256 _total = _after.sub(_before);
require(_total >= _amountUnderlying, "FARMTREASURYV1: bad transfer");
}
function _deposit(uint256 _amountUnderlying, address _referral) internal {
// determine how many shares this will be
uint256 _sharesToMint = getSharesForUnderlying(_amountUnderlying);
_mintShares(msg.sender, _sharesToMint);
// store some important info for this deposit, that will be checked on withdraw/transfer of tokens
_storeDepositInfo(msg.sender, _amountUnderlying);
// emit deposit w/ referral event... can't refer yourself
if (_referral != msg.sender){
emit Deposit(msg.sender, _amountUnderlying, _referral);
}
else {
emit Deposit(msg.sender, _amountUnderlying, address(0));
}
emit Transfer(address(0), msg.sender, _amountUnderlying);
}
function _storeDepositInfo(address _account, uint256 _amountUnderlying) internal {
DepositInfo memory _existingInfo = userDeposits[_account];
// first deposit, make a new entry in the mapping, lock all funds for "waitPeriod"
if (_existingInfo.timestampDeposit == 0){
DepositInfo memory _info = DepositInfo(
{
amountUnderlyingLocked: _amountUnderlying,
timestampDeposit: block.timestamp,
timestampUnlocked: block.timestamp.add(waitPeriod)
}
);
userDeposits[_account] = _info;
}
// not the first deposit, if there are still funds locked, then average out the waits (ie: 1 BTC locked 10 days = 2 BTC locked 5 days)
else {
uint256 _lockedAmt = _getLockedAmount(_account, _existingInfo.amountUnderlyingLocked, _existingInfo.timestampDeposit, _existingInfo.timestampUnlocked);
// if there's no lock, disregard old info and make a new lock
if (_lockedAmt == 0){
DepositInfo memory _info = DepositInfo(
{
amountUnderlyingLocked: _amountUnderlying,
timestampDeposit: block.timestamp,
timestampUnlocked: block.timestamp.add(waitPeriod)
}
);
userDeposits[_account] = _info;
}
// funds are still locked from a past deposit, average out the waittime remaining with the waittime for this new deposit
/*
solve this equation:
newDepositAmt * waitPeriod + remainingAmt * existingWaitPeriod = (newDepositAmt + remainingAmt) * X waitPeriod
therefore:
(newDepositAmt * waitPeriod + remainingAmt * existingWaitPeriod)
X waitPeriod = ----------------------------------------------------------------
(newDepositAmt + remainingAmt)
Example: 7 BTC new deposit, with wait period of 2 weeks
1 BTC remaining, with remaining wait period of 1 week
...
(7 BTC * 2 weeks + 1 BTC * 1 week) / 8 BTC = 1.875 weeks
*/
else {
uint256 _lockedAmtTime = _lockedAmt.mul(_existingInfo.timestampUnlocked.sub(block.timestamp));
uint256 _newAmtTime = _amountUnderlying.mul(waitPeriod);
uint256 _total = _amountUnderlying.add(_lockedAmt);
uint256 _newLockedTime = (_lockedAmtTime.add(_newAmtTime)).div(_total);
DepositInfo memory _info = DepositInfo(
{
amountUnderlyingLocked: _total,
timestampDeposit: block.timestamp,
timestampUnlocked: block.timestamp.add(_newLockedTime)
}
);
userDeposits[_account] = _info;
}
}
}
function getLockedAmount(address _account) public view returns (uint256) {
DepositInfo memory _existingInfo = userDeposits[_account];
return _getLockedAmount(_account, _existingInfo.amountUnderlyingLocked, _existingInfo.timestampDeposit, _existingInfo.timestampUnlocked);
}
// the locked amount linearly decreases until the timestampUnlocked time, then it's zero
// Example: if 5 BTC contributed (2 week lock), then after 1 week there will be 2.5 BTC locked, the rest is free to transfer/withdraw
function _getLockedAmount(address _account, uint256 _amountLocked, uint256 _timestampDeposit, uint256 _timestampUnlocked) internal view returns (uint256) {
if (_timestampUnlocked <= block.timestamp || noLockWhitelist[_account]){
return 0;
}
else {
uint256 _remainingTime = _timestampUnlocked.sub(block.timestamp);
uint256 _totalTime = _timestampUnlocked.sub(_timestampDeposit);
return _amountLocked.mul(_remainingTime).div(_totalTime);
}
}
function withdraw(uint256 _amountUnderlying) external nonReentrant {
require(_amountUnderlying > 0, "FARMTREASURYV1: amount == 0");
require(!paused, "FARMTREASURYV1: paused");
_withdraw(_amountUnderlying);
IERC20(underlyingContract).safeTransfer(msg.sender, _amountUnderlying);
}
function _withdraw(uint256 _amountUnderlying) internal {
_verify(msg.sender, _amountUnderlying);
// try and catch the more obvious error of hot wallet being depleted, otherwise proceed
if (IERC20(underlyingContract).balanceOf(address(this)) < _amountUnderlying){
revert("FARMTREASURYV1: Hot wallet balance depleted. Please try smaller withdraw or wait for rebalancing.");
}
uint256 _sharesToBurn = getSharesForUnderlying(_amountUnderlying);
_burnShares(msg.sender, _sharesToBurn); // they must have >= _sharesToBurn, checked here
emit Transfer(msg.sender, address(0), _amountUnderlying);
emit Withdraw(msg.sender, _amountUnderlying);
}
// wait time verification
function _verify(address _account, uint256 _amountUnderlyingToSend) internal override {
DepositInfo memory _existingInfo = userDeposits[_account];
uint256 _lockedAmt = _getLockedAmount(_account, _existingInfo.amountUnderlyingLocked, _existingInfo.timestampDeposit, _existingInfo.timestampUnlocked);
uint256 _balance = balanceOf(_account);
// require that any funds locked are not leaving the account in question.
require(_balance.sub(_amountUnderlyingToSend) >= _lockedAmt, "FARMTREASURYV1: requested funds are temporarily locked");
}
// this means that we made a GAIN, due to standard farming gains
// operaratable by farmBoss, this is standard operating procedure, farmers can only report gains
function rebalanceUp(uint256 _amount, address _farmerRewards) external nonReentrant returns (bool, uint256) {
require(msg.sender == farmBoss, "FARMTREASURYV1: !farmBoss");
require(!paused, "FARMTREASURYV1: paused");
// fee logic & profit recording
// check farmer limits on rebalance wait time for earning reportings. if there is no _amount reported, we don't take any fees and skip these checks
// we should always allow pure hot wallet rebalances, however earnings needs some checks and restrictions
if (_amount > 0){
require(block.timestamp.sub(lastRebalanceUpTime) >= rebalanceUpWaitTime, "FARMTREASURYV1: <rebalanceUpWaitTime");
require(ACTIVELY_FARMED.mul(rebalanceUpLimit).div(max) >= _amount, "FARMTREASURYV1 _amount > rebalanceUpLimit");
// farmer incurred a gain of _amount, add this to the amount being farmed
ACTIVELY_FARMED = ACTIVELY_FARMED.add(_amount);
uint256 _totalPerformance = _performanceFee(_amount, _farmerRewards);
uint256 _totalAnnual = _annualFee(_farmerRewards);
// for farmer controls, and also for the annual fee time
// only update this if there is a reported gain, otherwise this is just a hot wallet rebalance, and we should always allow these
lastRebalanceUpTime = block.timestamp;
// for off-chain APY calculations, fees assessed
emit ProfitDeclared(true, _amount, block.timestamp, _getTotalUnderlying(), totalShares, _totalPerformance, _totalAnnual);
}
else {
// for off-chain APY calculations, no fees assessed
emit ProfitDeclared(true, _amount, block.timestamp, _getTotalUnderlying(), totalShares, 0, 0);
}
// end fee logic & profit recording
// funds are in the contract and gains are accounted for, now determine if we need to further rebalance the hot wallet up, or can take funds in order to farm
// start hot wallet and farmBoss rebalance logic
(bool _fundsNeeded, uint256 _amountChange) = _calcHotWallet();
_rebalanceHot(_fundsNeeded, _amountChange); // if the hot wallet rebalance fails, revert() the entire function
// end logic
return (_fundsNeeded, _amountChange); // in case we need them, FE simulations and such
}
// this means that the system took a loss, and it needs to be reflected in the next rebalance
// only operatable by governance, (large) losses should be extremely rare by good farming practices
// this would look like a farmed smart contract getting exploited/hacked, and us not having the necessary insurance for it
// possible that some more aggressive IL strategies could also need this function called
function rebalanceDown(uint256 _amount, bool _rebalanceHotWallet) external nonReentrant returns (bool, uint256) {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
// require(!paused, "FARMTREASURYV1: paused"); <-- governance can only call this anyways, leave this commented out
ACTIVELY_FARMED = ACTIVELY_FARMED.sub(_amount);
if (_rebalanceHotWallet){
(bool _fundsNeeded, uint256 _amountChange) = _calcHotWallet();
_rebalanceHot(_fundsNeeded, _amountChange); // if the hot wallet rebalance fails, revert() the entire function
return (_fundsNeeded, _amountChange); // in case we need them, FE simulations and such
}
// for off-chain APY calculations, no fees assessed
emit ProfitDeclared(false, _amount, block.timestamp, _getTotalUnderlying(), totalShares, 0, 0);
return (false, 0);
}
function _performanceFee(uint256 _amount, address _farmerRewards) internal returns (uint256){
uint256 _existingShares = totalShares;
uint256 _balance = _getTotalUnderlying();
uint256 _performanceToFarmerUnderlying = _amount.mul(performanceToFarmer).div(max);
uint256 _performanceToTreasuryUnderlying = _amount.mul(performanceToTreasury).div(max);
uint256 _performanceTotalUnderlying = _performanceToFarmerUnderlying.add(_performanceToTreasuryUnderlying);
if (_performanceTotalUnderlying == 0){
return 0;
}
uint256 _sharesToMint = _underlyingFeeToShares(_performanceTotalUnderlying, _balance, _existingShares);
uint256 _sharesToFarmer = _sharesToMint.mul(_performanceToFarmerUnderlying).div(_performanceTotalUnderlying); // by the same ratio
uint256 _sharesToTreasury = _sharesToMint.sub(_sharesToFarmer);
_mintShares(_farmerRewards, _sharesToFarmer);
_mintShares(governance, _sharesToTreasury);
uint256 _underlyingFarmer = getUnderlyingForShares(_sharesToFarmer);
uint256 _underlyingTreasury = getUnderlyingForShares(_sharesToTreasury);
// do two mint events, in underlying, not shares
emit Transfer(address(0), _farmerRewards, _underlyingFarmer);
emit Transfer(address(0), governance, _underlyingTreasury);
return _underlyingFarmer.add(_underlyingTreasury);
}
// we are taking baseToTreasury + baseToFarmer each year, every time this is called, look when we took fee last, and linearize the fee to now();
function _annualFee(address _farmerRewards) internal returns (uint256) {
uint256 _lastAnnualFeeTime = lastRebalanceUpTime;
if (_lastAnnualFeeTime >= block.timestamp){
return 0;
}
uint256 _elapsedTime = block.timestamp.sub(_lastAnnualFeeTime);
uint256 _existingShares = totalShares;
uint256 _balance = _getTotalUnderlying();
uint256 _annualPossibleUnderlying = _balance.mul(_elapsedTime).div(365 days);
uint256 _annualToFarmerUnderlying = _annualPossibleUnderlying.mul(baseToFarmer).div(max);
uint256 _annualToTreasuryUnderlying = _annualPossibleUnderlying.mul(baseToFarmer).div(max);
uint256 _annualTotalUnderlying = _annualToFarmerUnderlying.add(_annualToTreasuryUnderlying);
if (_annualTotalUnderlying == 0){
return 0;
}
uint256 _sharesToMint = _underlyingFeeToShares(_annualTotalUnderlying, _balance, _existingShares);
uint256 _sharesToFarmer = _sharesToMint.mul(_annualToFarmerUnderlying).div(_annualTotalUnderlying); // by the same ratio
uint256 _sharesToTreasury = _sharesToMint.sub(_sharesToFarmer);
_mintShares(_farmerRewards, _sharesToFarmer);
_mintShares(governance, _sharesToTreasury);
uint256 _underlyingFarmer = getUnderlyingForShares(_sharesToFarmer);
uint256 _underlyingTreasury = getUnderlyingForShares(_sharesToTreasury);
// do two mint events, in underlying, not shares
emit Transfer(address(0), _farmerRewards, _underlyingFarmer);
emit Transfer(address(0), governance, _underlyingTreasury);
return _underlyingFarmer.add(_underlyingTreasury);
}
function _underlyingFeeToShares(uint256 _totalFeeUnderlying, uint256 _balance, uint256 _existingShares) pure internal returns (uint256 _sharesToMint){
// to mint the required amount of fee shares, solve:
/*
ratio:
currentShares newShares
-------------------------- : --------------------, where newShares = (currentShares + mintShares)
(totalUnderlying - feeAmt) totalUnderlying
solved:
---> (currentShares / (totalUnderlying - feeAmt) * totalUnderlying) - currentShares = mintShares, where newBalanceLessFee = (totalUnderlying - feeAmt)
*/
return _existingShares
.mul(_balance)
.div(_balance.sub(_totalFeeUnderlying))
.sub(_existingShares);
}
function _calcHotWallet() internal view returns (bool _fundsNeeded, uint256 _amountChange) {
uint256 _balanceHere = IERC20(underlyingContract).balanceOf(address(this));
uint256 _balanceFarmed = ACTIVELY_FARMED;
uint256 _totalAmount = _balanceHere.add(_balanceFarmed);
uint256 _hotAmount = _totalAmount.mul(hotWalletHoldings).div(max);
// we have too much in hot wallet, send to farmBoss
if (_balanceHere >= _hotAmount){
return (false, _balanceHere.sub(_hotAmount));
}
// we have too little in hot wallet, pull from farmBoss
if (_balanceHere < _hotAmount){
return (true, _hotAmount.sub(_balanceHere));
}
}
// usually paired with _calcHotWallet()
function _rebalanceHot(bool _fundsNeeded, uint256 _amountChange) internal {
if (_fundsNeeded){
uint256 _before = IERC20(underlyingContract).balanceOf(address(this));
IERC20(underlyingContract).safeTransferFrom(farmBoss, address(this), _amountChange);
uint256 _after = IERC20(underlyingContract).balanceOf(address(this));
uint256 _total = _after.sub(_before);
require(_total >= _amountChange, "FARMTREASURYV1: bad rebalance, hot wallet needs funds!");
// we took funds from the farmBoss to refill the hot wallet, reflect this in ACTIVELY_FARMED
ACTIVELY_FARMED = ACTIVELY_FARMED.sub(_amountChange);
emit RebalanceHot(_amountChange, 0, block.timestamp);
}
else {
require(farmBoss != address(0), "FARMTREASURYV1: !FarmBoss"); // don't burn funds
IERC20(underlyingContract).safeTransfer(farmBoss, _amountChange); // _calcHotWallet() guarantees we have funds here to send
// we sent more funds for the farmer to farm, reflect this
ACTIVELY_FARMED = ACTIVELY_FARMED.add(_amountChange);
emit RebalanceHot(0, _amountChange, block.timestamp);
}
}
function _getTotalUnderlying() internal override view returns (uint256) {
uint256 _balanceHere = IERC20(underlyingContract).balanceOf(address(this));
uint256 _balanceFarmed = ACTIVELY_FARMED;
return _balanceHere.add(_balanceFarmed);
}
function rescue(address _token, uint256 _amount) external nonReentrant {
require(msg.sender == governance, "FARMTREASURYV1: !governance");
if (_token != address(0)){
IERC20(_token).safeTransfer(governance, _amount);
}
else { // if _tokenContract is 0x0, then escape ETH
governance.transfer(_amount);
}
}
}
interface IUniswapRouterV2 {
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint[] memory amounts);
}
abstract contract FarmBossV1 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Address for address;
mapping(address => mapping(bytes4 => uint256)) public whitelist; // contracts -> mapping (functionSig -> allowed, msg.value allowed)
mapping(address => bool) public farmers;
// constants for the whitelist logic
bytes4 constant internal FALLBACK_FN_SIG = 0xffffffff;
// 0 = not allowed ... 1 = allowed however value must be zero ... 2 = allowed with msg.value either zero or non-zero
uint256 constant internal NOT_ALLOWED = 0;
uint256 constant internal ALLOWED_NO_MSG_VALUE = 1;
uint256 constant internal ALLOWED_W_MSG_VALUE = 2;
uint256 internal constant LOOP_LIMIT = 200;
uint256 public constant max = 10000;
uint256 public CRVTokenTake = 1500; // pct of max
// for passing to functions more cleanly
struct WhitelistData {
address account;
bytes4 fnSig;
bool valueAllowed;
}
// for passing to functions more cleanly
struct Approves {
address token;
address allow;
}
address payable public governance;
address public daoCouncilMultisig;
address public treasury;
address public underlying;
// constant - if the addresses change, assume that the functions will be different too and this will need a rewrite
address public constant UniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant SushiswapRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant CRVToken = 0xD533a949740bb3306d119CC777fa900bA034cd52;
event NewFarmer(address _farmer);
event RmFarmer(address _farmer);
event NewWhitelist(address _contract, bytes4 _fnSig, uint256 _allowedType);
event RmWhitelist(address _contract, bytes4 _fnSig);
event NewApproval(address _token, address _contract);
event RmApproval(address _token, address _contract);
event ExecuteSuccess(bytes _returnData);
event ExecuteERROR(bytes _returnData);
constructor(address payable _governance, address _daoMultisig, address _treasury, address _underlying) public {
governance = _governance;
daoCouncilMultisig = _daoMultisig;
treasury = _treasury;
underlying = _underlying;
farmers[msg.sender] = true;
emit NewFarmer(msg.sender);
// no need to set to zero first on safeApprove, is brand new contract
IERC20(_underlying).safeApprove(_treasury, type(uint256).max); // treasury has full control over underlying in this contract
_initFirstFarms();
}
receive() payable external {}
// function stub, this needs to be implemented in a contract which inherits this for a valid deployment
// some fixed logic to set up the first farmers, farms, whitelists, approvals, etc. future farms will need to be approved by governance
// called on init only
// IMPLEMENT THIS
function _initFirstFarms() internal virtual;
function setGovernance(address payable _new) external {
require(msg.sender == governance, "FARMBOSSV1: !governance");
governance = _new;
}
function setDaoCouncilMultisig(address _new) external {
require(msg.sender == governance || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(governance || multisig)");
daoCouncilMultisig = _new;
}
function setCRVTokenTake(uint256 _new) external {
require(msg.sender == governance || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(governance || multisig)");
require(_new <= max.div(2), "FARMBOSSV1: >half CRV to take");
CRVTokenTake = _new;
}
function getWhitelist(address _contract, bytes4 _fnSig) external view returns (uint256){
return whitelist[_contract][_fnSig];
}
function changeFarmers(address[] calldata _newFarmers, address[] calldata _rmFarmers) external {
require(msg.sender == governance, "FARMBOSSV1: !governance");
require(_newFarmers.length.add(_rmFarmers.length) <= LOOP_LIMIT, "FARMBOSSV1: >LOOP_LIMIT"); // dont allow unbounded loops
// add the new farmers in
for (uint256 i = 0; i < _newFarmers.length; i++){
farmers[_newFarmers[i]] = true;
emit NewFarmer(_newFarmers[i]);
}
// remove farmers
for (uint256 j = 0; j < _rmFarmers.length; j++){
farmers[_rmFarmers[j]] = false;
emit RmFarmer(_rmFarmers[j]);
}
}
// callable by the DAO Council multisig, we can instantly remove a group of malicious farmers (no delay needed from DAO voting)
function emergencyRemoveFarmers(address[] calldata _rmFarmers) external {
require(msg.sender == daoCouncilMultisig, "FARMBOSSV1: !multisig");
require(_rmFarmers.length <= LOOP_LIMIT, "FARMBOSSV1: >LOOP_LIMIT"); // dont allow unbounded loops
// remove farmers
for (uint256 j = 0; j < _rmFarmers.length; j++){
farmers[_rmFarmers[j]] = false;
emit RmFarmer(_rmFarmers[j]);
}
}
function changeWhitelist(WhitelistData[] calldata _newActions, WhitelistData[] calldata _rmActions, Approves[] calldata _newApprovals, Approves[] calldata _newDepprovals) external {
require(msg.sender == governance, "FARMBOSSV1: !governance");
require(_newActions.length.add(_rmActions.length).add(_newApprovals.length).add(_newDepprovals.length) <= LOOP_LIMIT, "FARMBOSSV1: >LOOP_LIMIT"); // dont allow unbounded loops
// add to whitelist, or change a whitelist entry if want to allow/disallow msg.value
for (uint256 i = 0; i < _newActions.length; i++){
_addWhitelist(_newActions[i].account, _newActions[i].fnSig, _newActions[i].valueAllowed);
}
// remove from whitelist
for (uint256 j = 0; j < _rmActions.length; j++){
whitelist[_rmActions[j].account][_rmActions[j].fnSig] = NOT_ALLOWED;
emit RmWhitelist(_rmActions[j].account, _rmActions[j].fnSig);
}
// approve safely, needs to be set to zero, then max.
for (uint256 k = 0; k < _newApprovals.length; k++){
_approveMax(_newApprovals[k].token, _newApprovals[k].allow);
}
// de-approve these contracts
for (uint256 l = 0; l < _newDepprovals.length; l++){
IERC20(_newDepprovals[l].token).safeApprove(_newDepprovals[l].allow, 0);
emit RmApproval(_newDepprovals[l].token, _newDepprovals[l].allow);
}
}
function _addWhitelist(address _contract, bytes4 _fnSig, bool _msgValueAllowed) internal {
if (_msgValueAllowed){
whitelist[_contract][_fnSig] = ALLOWED_W_MSG_VALUE;
emit NewWhitelist(_contract, _fnSig, ALLOWED_W_MSG_VALUE);
}
else {
whitelist[_contract][_fnSig] = ALLOWED_NO_MSG_VALUE;
emit NewWhitelist(_contract, _fnSig, ALLOWED_NO_MSG_VALUE);
}
}
function _approveMax(address _token, address _account) internal {
IERC20(_token).safeApprove(_account, 0);
IERC20(_token).safeApprove(_account, type(uint256).max);
emit NewApproval(_token, _account);
}
// callable by the DAO Council multisig, we can instantly remove a group of malicious contracts / approvals (no delay needed from DAO voting)
function emergencyRemoveWhitelist(WhitelistData[] calldata _rmActions, Approves[] calldata _newDepprovals) external {
require(msg.sender == daoCouncilMultisig, "FARMBOSSV1: !multisig");
require(_rmActions.length.add(_newDepprovals.length) <= LOOP_LIMIT, "FARMBOSSV1: >LOOP_LIMIT"); // dont allow unbounded loops
// remove from whitelist
for (uint256 j = 0; j < _rmActions.length; j++){
whitelist[_rmActions[j].account][_rmActions[j].fnSig] = NOT_ALLOWED;
emit RmWhitelist(_rmActions[j].account, _rmActions[j].fnSig);
}
// de-approve these contracts
for (uint256 l = 0; l < _newDepprovals.length; l++){
IERC20(_newDepprovals[l].token).safeApprove(_newDepprovals[l].allow, 0);
emit RmApproval(_newDepprovals[l].token, _newDepprovals[l].allow);
}
}
function govExecute(address payable _target, uint256 _value, bytes calldata _data) external returns (bool, bytes memory){
require(msg.sender == governance, "FARMBOSSV1: !governance");
return _execute(_target, _value, _data);
}
function farmerExecute(address payable _target, uint256 _value, bytes calldata _data) external returns (bool, bytes memory){
require(farmers[msg.sender] || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(farmer || multisig)");
require(_checkContractAndFn(_target, _value, _data), "FARMBOSSV1: target.fn() not allowed. ask DAO for approval.");
return _execute(_target, _value, _data);
}
// farmer is NOT allowed to call the functions approve, transfer on an ERC20
// this will give the farmer direct control over assets held by the contract
// governance must approve() farmer to interact with contracts & whitelist these contracts
// even if contracts are whitelisted, farmer cannot call transfer/approve (many vault strategies will have ERC20 inheritance)
// these approvals must also be called when setting up a new strategy from governance
// if there is a strategy that has additonal functionality for the farmer to take control of assets ie: Uniswap "add a send"
// then a "safe" wrapper contract must be made, ie: you can call Uniswap but "add a send is disabled, only msg.sender in this field"
// strategies must be checked carefully so that farmers cannot take control of assets. trustless farming!
function _checkContractAndFn(address _target, uint256 _value, bytes calldata _data) internal view returns (bool) {
bytes4 _fnSig;
if (_data.length < 4){ // we are calling a payable function, or the data is otherwise invalid (need 4 bytes for any fn call)
_fnSig = FALLBACK_FN_SIG;
}
else { // we are calling a normal function, get the function signature from the calldata (first 4 bytes of calldata)
//////////////////
// NOTE: here we must use assembly in order to covert bytes -> bytes4
// See consensys code for bytes -> bytes32: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
//////////////////
bytes memory _fnSigBytes = bytes(_data[0:4]);
assembly {
_fnSig := mload(add(add(_fnSigBytes, 0x20), 0))
}
// _fnSig = abi.decode(bytes(_data[0:4]), (bytes4)); // NOTE: does not work, open solidity issue: https://github.com/ethereum/solidity/issues/9170
}
bytes4 _transferSig = 0xa9059cbb;
bytes4 _approveSig = 0x095ea7b3;
if (_fnSig == _transferSig || _fnSig == _approveSig || whitelist[_target][_fnSig] == NOT_ALLOWED){
return false;
}
// check if value not allowed & value
else if (whitelist[_target][_fnSig] == ALLOWED_NO_MSG_VALUE && _value > 0){
return false;
}
// either ALLOWED_W_MSG_VALUE or ALLOWED_NO_MSG_VALUE with zero value
return true;
}
// call arbitrary contract & function, forward all gas, return success? & data
function _execute(address payable _target, uint256 _value, bytes memory _data) internal returns (bool, bytes memory){
bool _success;
bytes memory _returnData;
if (_data.length == 4 && _data[0] == 0xff && _data[1] == 0xff && _data[2] == 0xff && _data[3] == 0xff){ // check if fallback function is invoked, send w/ no data
(_success, _returnData) = _target.call{value: _value}("");
}
else {
(_success, _returnData) = _target.call{value: _value}(_data);
}
if (_success){
emit ExecuteSuccess(_returnData);
}
else {
emit ExecuteERROR(_returnData);
}
return (_success, _returnData);
}
// we can call this function on the treasury from farmer/govExecute, but let's make it easy
function rebalanceUp(uint256 _amount, address _farmerRewards) external {
require(msg.sender == governance || farmers[msg.sender] || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(governance || farmer || multisig)");
FarmTreasuryV1(treasury).rebalanceUp(_amount, _farmerRewards);
}
// is a Sushi/Uniswap wrapper to sell tokens for extra safety. This way, the swapping routes & destinations are checked & much safer than simply whitelisting the function
// the function takes the calldata directly as an input. this way, calling the function is very similar to a normal farming call
function sellExactTokensForUnderlyingToken(bytes calldata _data, bool _isSushi) external returns (uint[] memory amounts){
require(msg.sender == governance || farmers[msg.sender] || msg.sender == daoCouncilMultisig, "FARMBOSSV1: !(governance || farmer || multisig)");
(uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline) = abi.decode(_data[4:], (uint256, uint256, address[], address, uint256));
// check the data to make sure it's an allowed sell
require(to == address(this), "FARMBOSSV1: invalid sell, to != address(this)");
// strictly require paths to be [token, WETH, underlying]
// note: underlying can be WETH --> [token, WETH]
if (underlying == WETH){
require(path.length == 2, "FARMBOSSV1: path.length != 2");
require(path[1] == WETH, "FARMBOSSV1: WETH invalid sell, output != underlying");
}
else {
require(path.length == 3, "FARMBOSSV1: path.length != 3");
require(path[1] == WETH, "FARMBOSSV1: path[1] != WETH");
require(path[2] == underlying, "FARMBOSSV1: invalid sell, output != underlying");
}
// DAO takes some percentage of CRVToken pre-sell as part of a long term strategy
if (path[0] == CRVToken && CRVTokenTake > 0){
uint256 _amtTake = amountIn.mul(CRVTokenTake).div(max); // take some portion, and send to governance
// redo the swap input variables, to account for the amount taken
amountIn = amountIn.sub(_amtTake);
amountOutMin = amountOutMin.mul(max.sub(CRVTokenTake)).div(max); // reduce the amountOutMin by the same ratio, therefore target slippage pct is the same
IERC20(CRVToken).safeTransfer(governance, _amtTake);
}
if (_isSushi){ // sell on Sushiswap
return IUniswapRouterV2(SushiswapRouter).swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline);
}
else { // sell on Uniswap
return IUniswapRouterV2(UniswapRouter).swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline);
}
}
function rescue(address _token, uint256 _amount) external {
require(msg.sender == governance, "FARMBOSSV1: !governance");
if (_token != address(0)){
IERC20(_token).safeTransfer(governance, _amount);
}
else { // if _tokenContract is 0x0, then escape ETH
governance.transfer(_amount);
}
}
}
contract FarmBossV1_USDC is FarmBossV1 {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Address for address;
// breaking some constants out here, getting stack ;) issues
// CRV FUNCTIONS
/*
CRV Notes:
add_liquidity takes a fixed size array of input, so it will change the function signature
0x0b4c7e4d --> 2 coin pool --> add_liquidity(uint256[2] uamounts, uint256 min_mint_amount)
0x4515cef3 --> 3 coin pool --> add_liquidity(uint256[3] amounts, uint256 min_mint_amount)
0x029b2f34 --> 4 coin pool --> add_liquidity(uint256[4] amounts, uint256 min_mint_amount)
0xee22be23 --> 2 coin pool underlying --> add_liquidity(uint256[2] _amounts, uint256 _min_mint_amount, bool _use_underlying)
0x2b6e993a -> 3 coin pool underlying --> add_liquidity(uint256[3] _amounts, uint256 _min_mint_amount, bool _use_underlying)
remove_liquidity_one_coin has an optional end argument, bool donate_dust
0x517a55a3 --> remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust)
0x1a4d01d2 --> remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount)
remove_liquidity_imbalance takes a fixes array of input too
0x18a7bd76 --> 4 coin pool --> remove_liquidity_imbalance(uint256[4] amounts, uint256 max_burn_amount)
*/
bytes4 constant private add_liquidity_2 = 0x0b4c7e4d;
bytes4 constant private add_liquidity_3 = 0x4515cef3;
bytes4 constant private add_liquidity_4 = 0x029b2f34;
bytes4 constant private add_liquidity_u_2 = 0xee22be23;
bytes4 constant private add_liquidity_u_3 = 0x2b6e993a;
bytes4 constant private remove_liquidity_one_burn = 0x517a55a3;
bytes4 constant private remove_liquidity_one = 0x1a4d01d2;
bytes4 constant private remove_liquidity_4 = 0x18a7bd76;
bytes4 constant private deposit_gauge = 0xb6b55f25; // deposit(uint256 _value)
bytes4 constant private withdraw_gauge = 0x2e1a7d4d; // withdraw(uint256 _value)
bytes4 constant private mint = 0x6a627842; // mint(address gauge_addr)
bytes4 constant private mint_many = 0xa51e1904; // mint_many(address[8])
bytes4 constant private claim_rewards = 0x84e9bd7e; // claim_rewards(address addr)
// YEARN FUNCTIONS
bytes4 constant private deposit = 0xb6b55f25; // deposit(uint256 _amount)
bytes4 constant private withdraw = 0x2e1a7d4d; // withdraw(uint256 _shares)
// AlphaHomora FUNCTIONS
bytes4 constant private claim = 0x2f52ebb7;
// COMP FUNCTIONS
bytes4 constant private mint_ctoken = 0xa0712d68; // mint(uint256 mintAmount)
bytes4 constant private redeem_ctoken = 0xdb006a75; // redeem(uint256 redeemTokens)
bytes4 constant private claim_COMP = 0x1c3db2e0; // claimComp(address holder, address[] cTokens)
// IDLE FINANCE FUNCTIONS
bytes4 constant private mint_idle = 0x2befabbf; // mintIdleToken(uint256 _amount, bool _skipRebalance, address _referral)
bytes4 constant private redeem_idle = 0x8b30b516; // redeemIdleToken(uint256 _amount)
constructor(address payable _governance, address _daoMultisig, address _treasury, address _underlying) public FarmBossV1(_governance, _daoMultisig, _treasury, _underlying){
}
function _initFirstFarms() internal override {
/*
For our intro USDC strategies, we are using:
-- Curve.fi strategies for their good yielding USDC pools
-- AlphaHomoraV2 USDC
-- yEarn USDC
-- Compound USDC
-- IDLE Finance USDC
*/
////////////// ALLOW CURVE 3, s, y, ib, comp, busd, aave, usdt pools //////////////
////////////// ALLOW crv3pool //////////////
address _crv3Pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
address _crv3PoolToken = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
_approveMax(underlying, _crv3Pool);
_addWhitelist(_crv3Pool, add_liquidity_3, false);
_addWhitelist(_crv3Pool, remove_liquidity_one, false);
////////////// ALLOW crv3 Gauge //////////////
address _crv3Gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A;
_approveMax(_crv3PoolToken, _crv3Gauge);
_addWhitelist(_crv3Pool, deposit_gauge, false);
_addWhitelist(_crv3Pool, withdraw_gauge, false);
////////////// ALLOW crvSUSD Pool //////////////
// deposit USDC to SUSDpool, receive _crvSUSDToken
// this is a weird pool, like it was configured for lending accidentally... we will allow the swap and zap contract both
address _crvSUSDPool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD;
address _crvSUSDToken = 0xC25a3A3b969415c80451098fa907EC722572917F;
_approveMax(underlying, _crvSUSDPool);
_addWhitelist(_crvSUSDPool, add_liquidity_4, false);
_addWhitelist(_crvSUSDPool, remove_liquidity_4, false);
address _crvSUSDWithdraw = 0xFCBa3E75865d2d561BE8D220616520c171F12851; // because crv frontend is misconfigured to think this is a lending pool
_approveMax(underlying, _crvSUSDWithdraw);
_approveMax(_crvSUSDToken, _crvSUSDWithdraw);
_addWhitelist(_crvSUSDWithdraw, add_liquidity_4, false);
_addWhitelist(_crvSUSDWithdraw, remove_liquidity_one_burn, false);
////////////// ALLOW crvSUSD Gauge, SNX REWARDS //////////////
address _crvSUSDGauge = 0xA90996896660DEcC6E997655E065b23788857849;
_approveMax(_crvSUSDToken, _crvSUSDGauge);
_addWhitelist(_crvSUSDGauge, deposit_gauge, false);
_addWhitelist(_crvSUSDGauge, withdraw_gauge, false);
_addWhitelist(_crvSUSDGauge, claim_rewards, false);
address _SNXToken = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F;
_approveMax(_SNXToken, SushiswapRouter);
_approveMax(_SNXToken, UniswapRouter);
////////////// ALLOW crvCOMP Pool //////////////
address _crvCOMPDeposit = 0xeB21209ae4C2c9FF2a86ACA31E123764A3B6Bc06;
address _crvCOMPToken = 0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2;
_approveMax(underlying, _crvCOMPDeposit);
_approveMax(_crvCOMPToken, _crvCOMPDeposit); // allow withdraws, lending pool
_addWhitelist(_crvCOMPDeposit, add_liquidity_2, false);
_addWhitelist(_crvCOMPDeposit, remove_liquidity_one_burn, false);
////////////// ALLOW crvCOMP Gauge //////////////
address _crvCOMPGauge = 0x7ca5b0a2910B33e9759DC7dDB0413949071D7575;
_approveMax(_crvCOMPToken, _crvCOMPGauge);
_addWhitelist(_crvCOMPGauge, deposit_gauge, false);
_addWhitelist(_crvCOMPGauge, withdraw_gauge, false);
////////////// ALLOW crvBUSD Pool //////////////
address _crvBUSDDeposit = 0xb6c057591E073249F2D9D88Ba59a46CFC9B59EdB;
address _crvBUSDToken = 0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B;
_approveMax(underlying, _crvBUSDDeposit);
_approveMax(_crvBUSDToken, _crvBUSDDeposit);
_addWhitelist(_crvBUSDDeposit, add_liquidity_4, false);
_addWhitelist(_crvBUSDDeposit, remove_liquidity_one_burn, false);
////////////// ALLOW crvBUSD Gauge //////////////
address _crvBUSDGauge = 0x69Fb7c45726cfE2baDeE8317005d3F94bE838840;
_approveMax(_crvBUSDToken, _crvBUSDGauge);
_addWhitelist(_crvBUSDGauge, deposit_gauge, false);
_addWhitelist(_crvBUSDGauge, withdraw_gauge, false);
////////////// ALLOW crvAave Pool //////////////
address _crvAavePool = 0xDeBF20617708857ebe4F679508E7b7863a8A8EeE; // new style lending pool w/o second approve needed... direct burn from msg.sender
address _crvAaveToken = 0xFd2a8fA60Abd58Efe3EeE34dd494cD491dC14900;
_approveMax(underlying, _crvAavePool);
_addWhitelist(_crvAavePool, add_liquidity_u_3, false);
_addWhitelist(_crvAavePool, remove_liquidity_one_burn, false);
////////////// ALLOW crvAave Gauge //////////////
address _crvAaveGauge = 0xd662908ADA2Ea1916B3318327A97eB18aD588b5d;
_approveMax(_crvAaveToken, _crvAaveGauge);
_addWhitelist(_crvAaveGauge, deposit_gauge, false);
_addWhitelist(_crvAaveGauge, withdraw_gauge, false);
////////////// ALLOW crvYpool //////////////
address _crvYDeposit = 0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3;
address _crvYToken = 0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8;
_approveMax(underlying, _crvYDeposit);
_approveMax(_crvYToken, _crvYDeposit); // allow withdraws, lending pool
_addWhitelist(_crvYDeposit, add_liquidity_4, false);
_addWhitelist(_crvYDeposit, remove_liquidity_one_burn, false);
////////////// ALLOW crvY Gauge //////////////
address _crvYGauge = 0xFA712EE4788C042e2B7BB55E6cb8ec569C4530c1;
_approveMax(_crvYToken, _crvYGauge);
_addWhitelist(_crvYGauge, deposit_gauge, false);
_addWhitelist(_crvYGauge, withdraw_gauge, false);
////////////// ALLOW crvUSDTComp Pool //////////////
address _crvUSDTCompDeposit = 0xac795D2c97e60DF6a99ff1c814727302fD747a80;
address _crvUSDTCompToken = 0x9fC689CCaDa600B6DF723D9E47D84d76664a1F23;
_approveMax(underlying, _crvUSDTCompDeposit);
_approveMax(_crvUSDTCompToken, _crvUSDTCompDeposit); // allow withdraws, lending pool
_addWhitelist(_crvUSDTCompDeposit, add_liquidity_3, false);
_addWhitelist(_crvUSDTCompDeposit, remove_liquidity_one_burn, false);
////////////// ALLOW crvUSDTComp Gauge //////////////
address _crvUSDTCompGauge = 0xBC89cd85491d81C6AD2954E6d0362Ee29fCa8F53;
_approveMax(_crvUSDTCompToken, _crvUSDTCompGauge);
_addWhitelist(_crvUSDTCompGauge, deposit_gauge, false);
_addWhitelist(_crvUSDTCompGauge, withdraw_gauge, false);
////////////// ALLOW crvIBPool Pool //////////////
address _crvIBPool = 0x2dded6Da1BF5DBdF597C45fcFaa3194e53EcfeAF;
_approveMax(underlying, _crvIBPool);
_addWhitelist(_crvIBPool, add_liquidity_u_3, false);
_addWhitelist(_crvIBPool, remove_liquidity_one_burn, false);
////////////// ALLOW crvIBPool Gauge //////////////
address _crvIBGauge = 0xF5194c3325202F456c95c1Cf0cA36f8475C1949F;
address _crvIBToken = 0x5282a4eF67D9C33135340fB3289cc1711c13638C;
_approveMax(_crvIBToken, _crvIBGauge);
_addWhitelist(_crvIBGauge, deposit_gauge, false);
_addWhitelist(_crvIBGauge, withdraw_gauge, false);
////////////// CRV tokens mint, sell Sushi/Uni //////////////
address _crvMintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
_addWhitelist(_crvMintr, mint, false);
_addWhitelist(_crvMintr, mint_many, false);
// address CRVToken = 0xD533a949740bb3306d119CC777fa900bA034cd52; -- already in FarmBossV1
_approveMax(CRVToken, SushiswapRouter);
_approveMax(CRVToken, UniswapRouter);
////////////// END ALLOW CURVE 3, s, y, ib, comp, busd, aave, usdt pools //////////////
////////////// ALLOW AlphaHomoraV2 USDC //////////////
address _ahUSDC = 0x08bd64BFC832F1C2B3e07e634934453bA7Fa2db2;
IERC20(underlying).safeApprove(_ahUSDC, type(uint256).max);
whitelist[_ahUSDC][deposit] = ALLOWED_NO_MSG_VALUE;
whitelist[_ahUSDC][withdraw] = ALLOWED_NO_MSG_VALUE;
whitelist[_ahUSDC][claim] = ALLOWED_NO_MSG_VALUE; // claim ALPHA token reward
_approveMax(underlying, _ahUSDC);
_addWhitelist(_ahUSDC, deposit, false);
_addWhitelist(_ahUSDC, withdraw, false);
_addWhitelist(_ahUSDC, claim, false);
address ALPHA_TOKEN = 0xa1faa113cbE53436Df28FF0aEe54275c13B40975;
_approveMax(ALPHA_TOKEN, SushiswapRouter);
_approveMax(ALPHA_TOKEN, UniswapRouter);
////////////// END ALLOW AlphaHomoraV2 USDC //////////////
////////////// ALLOW yEarn USDC //////////////
address _yearnUSDC = 0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9;
IERC20(underlying).safeApprove(_yearnUSDC, type(uint256).max);
whitelist[_yearnUSDC][deposit] = ALLOWED_NO_MSG_VALUE;
whitelist[_yearnUSDC][withdraw] = ALLOWED_NO_MSG_VALUE;
_approveMax(underlying, _yearnUSDC);
_addWhitelist(_yearnUSDC, deposit, false);
_addWhitelist(_yearnUSDC, withdraw, false);
////////////// END ALLOW yEarn USDC //////////////
////////////// ALLOW Compound USDC //////////////
address _compUSDC = 0x39AA39c021dfbaE8faC545936693aC917d5E7563;
_approveMax(underlying, _compUSDC);
_addWhitelist(_compUSDC, mint_ctoken, false);
_addWhitelist(_compUSDC, redeem_ctoken, false);
address _comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; // claimComp
_addWhitelist(_comptroller, claim_COMP, false);
address _COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
_approveMax(_COMP, SushiswapRouter);
_approveMax(_COMP, UniswapRouter);
////////////// END ALLOW Compound USDC //////////////
////////////// ALLOW IDLE Finance USDC //////////////
address _idleBestUSDCv4 = 0x5274891bEC421B39D23760c04A6755eCB444797C;
_approveMax(underlying, _idleBestUSDCv4);
_addWhitelist(_idleBestUSDCv4, mint_idle, false);
_addWhitelist(_idleBestUSDCv4, redeem_idle, false);
// IDLEUSDC doesn't have a pure IDLEClaim() function, you need to either deposit/withdraw again, and then your IDLE & COMP will be sent
address IDLEToken = 0x875773784Af8135eA0ef43b5a374AaD105c5D39e;
_approveMax(IDLEToken, SushiswapRouter);
_approveMax(IDLEToken, UniswapRouter);
// NOTE: Comp rewards already are approved for liquidation above
////////////// END ALLOW IDLE Finance USDC //////////////
}
} | claimComp(address holder, address[] cTokens)
| bytes4 constant private claim_COMP = 0x1c3db2e0; | 1,571,305 | [
1,
14784,
2945,
12,
2867,
10438,
16,
1758,
8526,
276,
5157,
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
] | [
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,
1731,
24,
5381,
3238,
7516,
67,
10057,
273,
374,
92,
21,
71,
23,
1966,
22,
73,
20,
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
] |
./full_match/4/0x106980Cc2C2E3b4C5599B5DD6fdFa3F607FCe72b/sources/browser/Vault.sol | Yggdrasil calls to return assets | function yggdrasilMinus(address asset, uint value) external {
require(asset != address(0), "Ether must be sent from asgard");
require(value <= yggAllowance[msg.sender][asset], "must not send more than allowance");
asgardAllowance[asset] += value;
yggAllowance[msg.sender][asset] -= value;
emit YggdrasilMinus(msg.sender, asset, value);
}
| 13,356,982 | [
1,
61,
14253,
3069,
345,
330,
4097,
358,
327,
7176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
677,
14253,
3069,
345,
330,
18434,
12,
2867,
3310,
16,
2254,
460,
13,
3903,
288,
203,
3639,
2583,
12,
9406,
480,
1758,
12,
20,
3631,
315,
41,
1136,
1297,
506,
3271,
628,
487,
75,
1060,
8863,
203,
3639,
2583,
12,
1132,
1648,
677,
14253,
7009,
1359,
63,
3576,
18,
15330,
6362,
9406,
6487,
315,
11926,
486,
1366,
1898,
2353,
1699,
1359,
8863,
203,
3639,
487,
75,
1060,
7009,
1359,
63,
9406,
65,
1011,
460,
31,
203,
3639,
677,
14253,
7009,
1359,
63,
3576,
18,
15330,
6362,
9406,
65,
3947,
460,
31,
203,
3639,
3626,
1624,
14253,
3069,
345,
330,
18434,
12,
3576,
18,
15330,
16,
3310,
16,
460,
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
] |
./partial_match/1/0xbDCaC2eDbFA8f098B68082A743acC1911E86F4e1/sources/KobeInu.sol | Buy FeeSell FeeOriginal Fee | contract KobeInu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Kobe Inu";
string private constant _symbol = "KOBEI";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 824000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public launchBlock;
uint256 private _redisFeeOnBuy = 0;
uint256 private _taxFeeOnBuy = 5;
uint256 private _redisFeeOnSell = 0;
uint256 private _taxFeeOnSell = 15;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0x252A6A30C3b431503D2c689Dd44cD65ee05eA057);
address payable private _marketingAddress = payable(0x252A6A30C3b431503D2c689Dd44cD65ee05eA057);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = _tTotal.mul(20).div(1000);
uint256 public _maxWalletSize = _tTotal.mul(20).div(1000);
uint256 public _swapTokensAtAmount = _tTotal.mul(5).div(1000);
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
launchBlock = block.number;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function removeLimit() external onlyOwner{
_maxTxAmount = _tTotal;
_maxWalletSize = _tTotal;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
} | 15,738,502 | [
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1475,
947,
73,
382,
89,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
7010,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
565,
533,
3238,
5381,
389,
529,
273,
315,
47,
947,
73,
657,
89,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
47,
5704,
41,
45,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
7010,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
1725,
3247,
9449,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
565,
2254,
5034,
1071,
8037,
1768,
31,
203,
7010,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
38,
9835,
273,
374,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
38,
9835,
273,
1381,
31,
203,
7010,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
55,
1165,
273,
374,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
2
] |
./partial_match/1/0xe192588fDaef2B14cf07de988bAD83aB9a6c1D34/sources/PortionExchange.sol | to be sure that the price in PRT is correct
| require(recoveredSignerAddress == signer, "invalid secret signer"); | 4,379,747 | [
1,
869,
506,
3071,
716,
326,
6205,
316,
11770,
56,
353,
3434,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
202,
6528,
12,
266,
16810,
15647,
1887,
422,
10363,
16,
315,
5387,
4001,
10363,
8863,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x38fcdc9374998c9D01a6337CCD591d1109C1CB6b/sources/LiquidityPoolV1_01.sol | * @dev Withdraw tokens @param amount_ amount of internal token to burn/ | function _withdraw (
uint256 amount_,
uint256[N_TOKENS] memory outAmounts_
)
internal
{
_burn(msg.sender, amount_);
for (uint256 i = 0; i < N_TOKENS; i++) {
if (outAmounts_[i] != 0)
assert(IERC20Upgradeable(tokens[i]).transfer(msg.sender, outAmounts_[i]));
}
emit Withdraw(msg.sender, outAmounts_, amount_);
}
| 3,491,164 | [
1,
1190,
9446,
2430,
225,
3844,
67,
3844,
434,
2713,
1147,
358,
18305,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
389,
1918,
9446,
261,
203,
202,
202,
11890,
5034,
3844,
67,
16,
203,
202,
202,
11890,
5034,
63,
50,
67,
8412,
55,
65,
3778,
596,
6275,
87,
67,
203,
202,
13,
203,
202,
202,
7236,
203,
202,
95,
203,
202,
202,
67,
70,
321,
12,
3576,
18,
15330,
16,
3844,
67,
1769,
203,
202,
202,
1884,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
423,
67,
8412,
55,
31,
277,
27245,
288,
203,
1082,
202,
430,
261,
659,
6275,
87,
67,
63,
77,
65,
480,
374,
13,
203,
9506,
202,
11231,
12,
45,
654,
39,
3462,
10784,
429,
12,
7860,
63,
77,
65,
2934,
13866,
12,
3576,
18,
15330,
16,
596,
6275,
87,
67,
63,
77,
5717,
1769,
203,
202,
202,
97,
203,
202,
202,
18356,
3423,
9446,
12,
3576,
18,
15330,
16,
596,
6275,
87,
67,
16,
3844,
67,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xD9b2DB080C99cd2507405cF2f52feE600cB07662/sources/Snowflake.sol | Buy FeeSell FeeOriginal Fee | contract Snowflake is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Snowflake";
string private constant _symbol = "$SNOW";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 100000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFeeOnBuy = 1;
uint256 private _taxFeeOnBuy = 6;
uint256 private _redisFeeOnSell = 1;
uint256 private _taxFeeOnSell = 6;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping (address => bool) public preTrader;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0x808D424FC8a07320AA129cE5097443300986AE57);
address payable private _marketingAddress = payable(0x808D424FC8a07320AA129cE5097443300986AE57);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
preTrader[owner()] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
bots[address(0x000000000000000000000000000000000000dEaD)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function allowPreTrading(address account, bool allowed) public onlyOwner {
require(preTrader[account] != allowed, "TOKEN: Already enabled.");
preTrader[account] = allowed;
}
} | 8,438,207 | [
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
31040,
30451,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
377,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
5381,
389,
529,
273,
315,
55,
3338,
30451,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
4662,
55,
27091,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
2130,
12648,
2787,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
38,
9835,
273,
404,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
38,
9835,
273,
1666,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
55,
1165,
273,
404,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
55,
1165,
273,
1666,
31,
203,
377,
203,
565,
2254,
5034,
3238,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-15
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
//
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//
/**
* @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 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 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;
}
}
//
library Address {
function isContract(address account) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
//
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
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 (uint)
{
require(owner != address(0), "ERC721: balance query for the zero address");
uint count;
for( uint i; i < _owners.length; ++i ){
if( owner == _owners[i] )
++count;
}
return count;
}
/**
* @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 {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);
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], 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 tokenId < _owners.length && _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");
_owners.push(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);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId] = address(0);
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");
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_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;
}
}
}
//
/**
* @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);
}
//
/**
* @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 but rips out the core of the gas-wasting processing that comes from OpenZeppelin.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
/**
* @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-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _owners.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < _owners.length, "ERC721Enumerable: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
uint count;
for(uint i; i < _owners.length; i++){
if(owner == _owners[i]){
if(count == index) return i;
else count++;
}
}
revert("ERC721Enumerable: owner index out of bounds");
}
}
//
/**
* @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);
}
}
//
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
//
// 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;
}
}
}
//
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
//
contract OwnableDelegateProxy { }
//
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
//
contract TheWanderings is ERC721Enumerable, Ownable, Pausable {
using SafeMath for uint256;
using MerkleProof for bytes32[];
bytes32 merkleRoot;
bool merkleSet = false;
uint256 public constant MAX_PER_CALL = 26;
// max supply is 4444, 4445 is used so we can use < instead of LTE, saving a tiny bit of gas when minting
uint256 public constant MAX_SUPPLY = 4445;
uint256 public NFT_PRICE = 0.01e18;
string public baseURI;
bool public presaleOngoing;
address public proxyRegistryAddress;
mapping(address => bool) public projectProxy;
mapping(address => uint256) public presaleMintedAmounts;
constructor(address openSeaProxy) ERC721("The Wanderings NFT - Ascension ", "The Wanderings NFT") {
proxyRegistryAddress = openSeaProxy;
_pause();
}
receive() external payable {}
function _mint(address to, uint256 tokenId) internal override virtual {
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
function mint(uint256 amount) external payable whenNotPaused {
require(amount < MAX_PER_CALL, "Amount exceeds max per tx");
uint256 ogAmount = _owners.length;
require(ogAmount + amount < MAX_SUPPLY, "Amount exceeds max supply");
require(msg.value == NFT_PRICE * amount, "Wrong eth amount");
for (uint256 i = 0; i < amount; i++) {
_mint(msg.sender, ogAmount + i);
}
}
function mintPresale(uint256 amount, bytes32[] memory merkleProof) external payable whenPaused {
require(presaleOngoing, "Presale hasn't started yet");
uint256 ogAmount = _owners.length;
require(ogAmount + amount < MAX_SUPPLY, "Amount exceeds max supply");
// Verify merkleProof
require(merkleProof.verify(merkleRoot, keccak256(abi.encodePacked(msg.sender, amount))), "Invalid proof. Not whitelisted");
for (uint256 i = 0; i < amount; i++) {
_mint(msg.sender, ogAmount + i);
}
presaleMintedAmounts[msg.sender] += amount;
}
function mintOwner(uint256 amount) external onlyOwner {
uint256 ogAmount = _owners.length;
require(_owners.length + amount < MAX_SUPPLY, "Amount exceeds max supply");
for (uint256 i = 0; i < amount; i++) {
_mint(msg.sender, ogAmount + i);
}
}
function startPresale() external onlyOwner {
presaleOngoing = true;
}
function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
function withdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
function setNftPrice(uint256 _nftPrice) external onlyOwner {
NFT_PRICE = _nftPrice;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
// Specify a merkle root hash from the gathered k/v dictionary of addresses
// https://github.com/0xKiwi/go-merkle-distributor
function setMerkleRoot(bytes32 root) external onlyOwner {
merkleRoot = root;
merkleSet = true;
}
// Return bool on if merkle root hash is set
function isMerkleSet() public view returns (bool) {
return merkleSet;
}
function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
function flipProxyState(address proxyAddress) public onlyOwner {
projectProxy[proxyAddress] = !projectProxy[proxyAddress];
}
function isApprovedForAll(address _owner, address operator) public view override returns (bool) {
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == operator || projectProxy[operator]) return true;
return super.isApprovedForAll(_owner, operator);
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "Token does not exist.");
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId)));
}
// Returns a list of tokens owned by address
// WARNING: VIEW ONLY, DO NOT USE THIS IN A TRANSACTION UNLESS YOU CAN AFFORD TO SPEND A LAMBO IN GAS
function tokensOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
} | Mapping from token ID to owner address | abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint)
{
require(owner != address(0), "ERC721: balance query for the zero address");
uint count;
for( uint i; i < _owners.length; ++i ){
if( owner == _owners[i] )
++count;
}
return count;
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint)
{
require(owner != address(0), "ERC721: balance query for the zero address");
uint count;
for( uint i; i < _owners.length; ++i ){
if( owner == _owners[i] )
++count;
}
return count;
}
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;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
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);
}
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
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);
}
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
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);
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], data_);
}
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], data_);
}
}
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"
);
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < _owners.length && _owners[tokenId] != address(0);
}
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));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
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"
);
}
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");
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_approve(address(0), tokenId);
_owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
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");
_approve(address(0), tokenId);
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
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;
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
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;
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
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;
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} catch (bytes memory reason) {
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;
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
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;
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
}
| 2,255,872 | [
1,
3233,
628,
1147,
1599,
358,
3410,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
17801,
6835,
4232,
39,
27,
5340,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
565,
1758,
8526,
2713,
389,
995,
414,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
203,
565,
1071,
203,
565,
1476,
203,
565,
5024,
203,
565,
3849,
12,
654,
39,
28275,
16,
467,
654,
39,
28275,
13,
203,
565,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
203,
3639,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2934,
5831,
548,
747,
203,
3639,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2277,
2934,
5831,
548,
747,
203,
3639,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
203,
565,
1071,
203,
565,
1476,
203,
565,
5024,
203,
565,
3849,
203,
565,
1135,
261,
11890,
2
] |
./partial_match/1/0x186bd56998E7909A6048302E0644C327c3E33932/sources/pusdToken.sol | * @dev Sets `amdounat` 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 amdounat
) 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] = amdounat;
emit Approval(owner, spender, amdounat);
}
| 9,139,855 | [
1,
2785,
1375,
301,
72,
465,
270,
68,
487,
326,
1699,
1359,
434,
1375,
87,
1302,
264,
68,
1879,
326,
1375,
8443,
68,
272,
2430,
18,
1220,
2713,
445,
353,
7680,
358,
1375,
12908,
537,
9191,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
444,
5859,
1699,
6872,
364,
8626,
15359,
87,
16,
5527,
18,
7377,
1282,
392,
288,
23461,
97,
871,
18,
29076,
30,
300,
1375,
8443,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
12908,
537,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
279,
1264,
465,
270,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
8443,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
6617,
537,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
87,
1302,
264,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
6617,
537,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
65,
273,
279,
1264,
465,
270,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
8443,
16,
17571,
264,
16,
279,
1264,
465,
270,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xC6713e9Bdc0B2f9fb50998F09e0Db16D7528E059/sources/contracts/interfaces/IManager.sol | @notice Requires the sender to be a manager | modifier onlyManager() {
require(managers.contains(msg.sender), "You do not have rights");
_;
}
| 2,942,220 | [
1,
21671,
326,
5793,
358,
506,
279,
3301,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1338,
1318,
1435,
288,
203,
3639,
2583,
12,
29757,
18,
12298,
12,
3576,
18,
15330,
3631,
315,
6225,
741,
486,
1240,
14989,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/8453/0x1CacC0DAfbEBdABC73A50CAAda2010CE019357eE/sources/MIDWIT_LP_LOCK.sol | * @dev Interface of the ERC20 standard as defined in the EIP./ | interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
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);
pragma solidity ^0.8.17;
}
| 16,737,604 | [
1,
1358,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
3462,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
4033,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "./interfaces/badger/ISwapStrategyRouter.sol";
import "./interfaces/bridge/IGateway.sol";
import "./interfaces/bridge/IBridgeVault.sol";
import "./interfaces/bridge/ICurveTokenWrapper.sol";
import "./interfaces/curve/ICurveFi.sol";
import "./interfaces/defidollar/IBadgerSettPeak.sol";
import "./interfaces/defidollar/IBadgerYearnWbtcPeak.sol";
contract BadgerBridgeAdapter is OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20 for IERC20;
IERC20 public renBTC;
IERC20 public wBTC;
// RenVM gateway registry.
IGatewayRegistry public registry;
// Swap router that handles swap routing optimizations.
ISwapStrategyRouter public router;
event RecoverStuck(uint256 amount, uint256 fee);
event Mint(uint256 renbtc_minted, uint256 wbtc_swapped, uint256 fee);
event Burn(uint256 renbtc_burned, uint256 wbtc_transferred, uint256 fee);
event SwapError(bytes error);
address public rewards;
address public governance;
uint256 public mintFeeBps;
uint256 public burnFeeBps;
uint256 private percentageFeeRewardsBps;
uint256 private percentageFeeGovernanceBps;
uint256 public constant MAX_BPS = 10000;
mapping(address => bool) public approvedVaults;
// Configurable permissionless curve lp token wrapper.
address curveTokenWrapper;
// Make struct for mint args, otherwise too many local vars (stack too deep).
struct MintArguments {
uint256 _mintAmount;
uint256 _mintAmountMinusFee;
uint256 _fee;
uint256 _slippage;
address _vault;
address _user;
address _token;
bool _mintIbbtc;
}
IERC20 public ibBTC;
// Peak contract for minting ibbtc from renbtc, sbtc, tbtc.
IBadgerSettPeak public settPeak;
// Peak contract for minting ibbtc from wbtc.
IBadgerYearnWbtcPeak public yearnWbtcPeak;
mapping(address => uint256) public vaultToPoolId;
function initialize(
address _governance,
address _rewards,
address _registry,
address _router,
address _wbtc,
uint256[4] memory _feeConfig
) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
require(_governance != address(0x0), "must set governance address");
require(_rewards != address(0x0), "must set rewards address");
require(_registry != address(0x0), "must set registry address");
require(_router != address(0x0), "must set router address");
require(_wbtc != address(0x0), "must set wBTC address");
governance = _governance;
rewards = _rewards;
registry = IGatewayRegistry(_registry);
router = ISwapStrategyRouter(_router);
renBTC = registry.getTokenBySymbol("BTC");
wBTC = IERC20(_wbtc);
mintFeeBps = _feeConfig[0];
burnFeeBps = _feeConfig[1];
percentageFeeRewardsBps = _feeConfig[2];
percentageFeeGovernanceBps = _feeConfig[3];
}
function version() external pure returns (string memory) {
return "1.1";
}
// NB: This recovery fn only works for the BTC gateway (hardcoded and only one supported in this adapter).
function recoverStuck(
// encoded user args
bytes calldata encoded,
// darkdnode args
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external nonReentrant {
// Ensure sender matches sender of original tx.
uint256 start = encoded.length - 32;
address sender = abi.decode(encoded[start:], (address));
require(sender == msg.sender);
bytes32 pHash = keccak256(encoded);
uint256 _mintAmount = registry.getGatewayBySymbol("BTC").mint(
pHash,
_amount,
_nHash,
_sig
);
uint256 _fee = _processFee(renBTC, _mintAmount, mintFeeBps);
emit RecoverStuck(_mintAmount, _fee);
renBTC.safeTransfer(msg.sender, _mintAmount.sub(_fee));
}
function mint(
// user args
address _token, // either renBTC or wBTC
uint256 _slippage,
address _user,
address _vault,
bool _mintIbbtc,
// darknode args
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external nonReentrant {
require(
_token == address(renBTC) || _token == address(wBTC),
"invalid token address"
);
// Mint renBTC tokens
bytes32 pHash = keccak256(abi.encode(_token, _slippage, _user, _vault));
uint256 mintAmount = registry.getGatewayBySymbol("BTC").mint(
pHash,
_amount,
_nHash,
_sig
);
require(mintAmount > 0, "zero mint amount");
uint256 fee = _processFee(renBTC, mintAmount, mintFeeBps);
uint256 mintAmountMinusFee = mintAmount.sub(fee);
MintArguments memory args = MintArguments(
mintAmount,
mintAmountMinusFee,
fee,
_slippage,
_vault,
_user,
_token,
_mintIbbtc
);
bool success = mintAdapter(args);
if (!success) {
renBTC.safeTransfer(_user, mintAmountMinusFee);
}
}
function burn(
// user args
address _token, // either renBTC or wBTC
address _vault,
uint256 _slippage,
bytes calldata _btcDestination,
uint256 _amount,
bool _burnIbbtc
) external nonReentrant {
require(
_token == address(renBTC) || _token == address(wBTC),
"invalid token address"
);
require(
!(_vault != address(0) && !approvedVaults[_vault]),
"Vault not approved"
);
bool isVault = _vault != address(0);
bool isRenBTC = _token == address(renBTC);
IERC20 token = isRenBTC ? renBTC : wBTC;
uint256 startBalanceRenBTC = renBTC.balanceOf(address(this));
uint256 startBalanceWBTC = wBTC.balanceOf(address(this));
if (_burnIbbtc) {
//redeem ibbtc
ibBTC.safeTransferFrom(msg.sender, address(this), _amount);
uint256 poolId = vaultToPoolId[_vault];
uint256 redeemAmount = 0;
if (poolId == 3) {
redeemAmount = yearnWbtcPeak.redeem(_amount);
} else {
redeemAmount = settPeak.redeem(poolId, _amount);
}
}
// Vaults can require up to two levels of unwrapping.
if (isVault) {
// First level of unwrapping for sett tokens.
if (!_burnIbbtc) {
IERC20(_vault).safeTransferFrom(msg.sender, address(this), _amount);
}
IERC20 vaultToken = IBridgeVault(_vault).token();
uint256 beforeBalance = vaultToken.balanceOf(address(this));
IBridgeVault(_vault).withdraw(IERC20(_vault).balanceOf(address(this)));
uint256 balance = vaultToken.balanceOf(address(this)).sub(beforeBalance);
// If the vault token does not match requested burn token, then we need to further unwrap
// vault token (e.g. withdrawing from crv sett gets us crv lp tokens which need to be unwrapped to renbtc).
if (address(vaultToken) != _token) {
vaultToken.safeTransfer(curveTokenWrapper, balance);
ICurveTokenWrapper(curveTokenWrapper).unwrap(_vault);
}
} else {
token.safeTransferFrom(msg.sender, address(this), _amount);
}
uint256 wbtcTransferred = wBTC.balanceOf(address(this)).sub(
startBalanceWBTC
);
if (!isRenBTC) {
_swapWBTCForRenBTC(wbtcTransferred, _slippage);
}
uint256 toBurnAmount = renBTC.balanceOf(address(this)).sub(
startBalanceRenBTC
);
uint256 fee = _processFee(renBTC, toBurnAmount, burnFeeBps);
uint256 burnAmount = registry.getGatewayBySymbol("BTC").burn(
_btcDestination,
toBurnAmount.sub(fee)
);
emit Burn(burnAmount, wbtcTransferred, fee);
}
function mintAdapter(MintArguments memory args) internal returns (bool) {
if (args._vault != address(0) && !approvedVaults[args._vault]) {
return false;
}
uint256 wbtcExchanged;
bool isVault = args._vault != address(0);
bool isRenBTC = args._token == address(renBTC);
IERC20 token = isRenBTC ? renBTC : wBTC;
if (!isRenBTC) {
// Try and swap and transfer wbtc if token wbtc specified.
uint256 startBalance = token.balanceOf(address(this));
if (!_swapRenBTCForWBTC(args._mintAmountMinusFee, args._slippage)) {
return false;
}
uint256 endBalance = token.balanceOf(address(this));
wbtcExchanged = endBalance.sub(startBalance);
}
emit Mint(args._mintAmount, wbtcExchanged, args._fee);
uint256 amount = isRenBTC ? args._mintAmountMinusFee : wbtcExchanged;
if (!isVault) {
token.safeTransfer(args._user, amount);
return true;
}
// If the token is wBTC then we just approve spend and deposit directly into the wbtc vault.
if (args._token == address(wBTC)) {
token.safeApprove(args._vault, token.balanceOf(address(this)));
} else {
// Otherwise, we need to wrap the token before depositing into vault.
// We currently only support wrapping renbtc into curve lp tokens.
// NB: The curve token wrapper contract is permissionless, we must transfer renbtc over
// and it will transfer back wrapped lp tokens.
token.safeTransfer(curveTokenWrapper, amount);
amount = ICurveTokenWrapper(curveTokenWrapper).wrap(args._vault);
IBridgeVault(args._vault).token().safeApprove(args._vault, amount);
}
if (args._mintIbbtc) {
IBridgeVault(args._vault).depositFor(address(this), amount);
uint256 balance = IERC20(args._vault).balanceOf(address(this));
_mintIbbtc(args._vault, args._user, balance);
} else {
IBridgeVault(args._vault).depositFor(args._user, amount);
}
return true;
}
function _mintIbbtc(
address _vault,
address _user,
uint256 _amount
) internal {
uint256 poolId = vaultToPoolId[_vault];
uint256 mintAmount = 0;
//passing in empty variable, no longer used in peak contract
bytes32[] memory unused;
if (poolId == 3) {
IERC20(_vault).approve(address(yearnWbtcPeak), _amount);
mintAmount = yearnWbtcPeak.mint(_amount, unused);
} else {
IERC20(_vault).approve(address(settPeak), _amount);
mintAmount = settPeak.mint(poolId, _amount, unused);
}
ibBTC.safeTransfer(_user, mintAmount);
}
function _swapWBTCForRenBTC(uint256 _amount, uint256 _slippage) internal {
(address strategy, uint256 estimatedAmount) = router.optimizeSwap(
address(wBTC),
address(renBTC),
_amount
);
uint256 minAmount = _minAmount(_slippage, _amount);
require(estimatedAmount > minAmount, "slippage too high");
// Approve strategy for spending of wbtc.
wBTC.safeApprove(strategy, _amount);
uint256 amount = ISwapStrategy(strategy).swapTokens(
address(wBTC),
address(renBTC),
_amount,
_slippage
);
require(amount > minAmount, "swapped amount less than min amount");
}
// Avoid reverting on mint (renBTC -> wBTC swap) since we cannot roll back that transaction.:
function _swapRenBTCForWBTC(uint256 _amount, uint256 _slippage)
internal
returns (bool)
{
(address strategy, uint256 estimatedAmount) = router.optimizeSwap(
address(renBTC),
address(wBTC),
_amount
);
uint256 minAmount = _minAmount(_slippage, _amount);
if (minAmount > estimatedAmount) {
// Do not swap if slippage is too high;
return false;
}
// Approve strategy for spending of renbtc.
renBTC.safeApprove(strategy, _amount);
try
ISwapStrategy(strategy).swapTokens(
address(renBTC),
address(wBTC),
_amount,
_slippage
)
{
return true;
} catch (bytes memory _error) {
emit SwapError(_error);
return false;
}
}
// Minimum amount w/ slippage applied.
function _minAmount(uint256 _slippage, uint256 _amount)
internal
pure
returns (uint256)
{
_slippage = uint256(1e4).sub(_slippage);
return _amount.mul(_slippage).div(1e4);
}
function _processFee(
IERC20 token,
uint256 amount,
uint256 feeBps
) internal returns (uint256) {
if (feeBps == 0) {
return 0;
}
uint256 fee = amount.mul(feeBps).div(MAX_BPS);
uint256 governanceFee = fee.mul(percentageFeeGovernanceBps).div(MAX_BPS);
uint256 rewardsFee = fee.mul(percentageFeeRewardsBps).div(MAX_BPS);
IERC20(token).safeTransfer(governance, governanceFee);
IERC20(token).safeTransfer(rewards, rewardsFee);
return fee;
}
// Admin methods.
function setMintFeeBps(uint256 _mintFeeBps) external onlyOwner {
require(_mintFeeBps <= MAX_BPS, "badger-bridge-adapter/excessive-mint-fee");
mintFeeBps = _mintFeeBps;
}
function setBurnFeeBps(uint256 _burnFeeBps) external onlyOwner {
require(_burnFeeBps <= MAX_BPS, "badger-bridge-adapter/excessive-burn-fee");
burnFeeBps = _burnFeeBps;
}
function setPercentageFeeGovernanceBps(uint256 _percentageFeeGovernanceBps)
external
onlyOwner
{
require(
_percentageFeeGovernanceBps + percentageFeeRewardsBps <= MAX_BPS,
"badger-bridge-adapter/excessive-percentage-fee-governance"
);
percentageFeeGovernanceBps = _percentageFeeGovernanceBps;
}
function setPercentageFeeRewardsBps(uint256 _percentageFeeRewardsBps)
external
onlyOwner
{
require(
_percentageFeeRewardsBps + percentageFeeGovernanceBps <= MAX_BPS,
"badger-bridge-adapter/excessive-percentage-fee-rewards"
);
percentageFeeRewardsBps = _percentageFeeRewardsBps;
}
function setRewards(address _rewards) external onlyOwner {
rewards = _rewards;
}
function setRouter(address _router) external onlyOwner {
router = ISwapStrategyRouter(_router);
}
function setRegistry(address _registry) external onlyOwner {
registry = IGatewayRegistry(_registry);
renBTC = registry.getTokenBySymbol("BTC");
}
function setVaultApproval(address _vault, bool _status) external onlyOwner {
approvedVaults[_vault] = _status;
}
function setVaultPoolId(address _vault, uint256 _poolId) external onlyOwner {
vaultToPoolId[_vault] = _poolId;
}
function setIbbtcContracts(
address _ibbtc,
address _settPeak,
address _yearnWbtcPeak
) external onlyOwner {
ibBTC = IERC20(_ibbtc);
settPeak = IBadgerSettPeak(_settPeak);
yearnWbtcPeak = IBadgerYearnWbtcPeak(_yearnWbtcPeak);
}
function setCurveTokenWrapper(address _wrapper) external onlyOwner {
curveTokenWrapper = _wrapper;
}
// Sweep all tokens and send to governance.
function sweep() external {
require(
msg.sender == governance && msg.sender == tx.origin,
"caller must be governance"
);
// NB: Sanity check but governance should have been set on init and cannot be modified.
require(governance != address(0x0), "must set governance address");
address[] memory sweepableTokens = new address[](2);
sweepableTokens[0] = address(renBTC);
sweepableTokens[1] = address(wBTC);
for (uint256 i = 0; i < 2; i++) {
IERC20 token = IERC20(sweepableTokens[i]);
uint256 balance = token.balanceOf(address(this));
if (balance > 0) {
token.safeTransfer(governance, balance);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
// ISwapStrategyRouter performs optimal routing of swaps.
interface ISwapStrategyRouter {
// Return the optimal rate and the strategy ID.
function optimizeSwap(
address _from,
address _to,
uint256 _amount
) external returns (address strategy, uint256 amount);
}
// ISwapStrategy enforces a standard API for swaps.
interface ISwapStrategy {
function swapTokens(
address _from,
address _to,
uint256 _amount,
// Slippage is in bps.
uint256 _slippage
) external returns (uint256 amount);
// Estimate swap amount returns the swap rate.
function estimateSwapAmount(
address _from,
address _to,
uint256 _amount
) external returns (uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IGateway {
function mint(
bytes32 _pHash,
uint256 _amount,
bytes32 _nHash,
bytes calldata _sig
) external returns (uint256);
function burn(bytes calldata _to, uint256 _amount) external returns (uint256);
}
interface IGatewayRegistry {
function getGatewayBySymbol(string calldata _tokenSymbol)
external
view
returns (IGateway);
function getTokenBySymbol(string calldata _tokenSymbol)
external
view
returns (IERC20);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IBridgeVault is IERC20 {
function depositFor(address recipient, uint256 amount) external;
function withdraw(uint256 shares) external;
function token() external returns (IERC20);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface ICurveTokenWrapper {
function wrap(address vault) external returns (uint256);
function unwrap(address vault) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface ICurveFi {
function get_virtual_price() external returns (uint256 out);
function add_liquidity(
// renbtc/tbtc pool
uint256[2] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function get_dy(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function remove_liquidity(
uint256 _amount,
uint256 deadline,
uint256[2] calldata min_amounts
) external;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 deadline
) external;
function remove_liquidity_imbalance(
uint256[3] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[3] calldata amounts)
external;
function remove_liquidity_imbalance(
uint256[4] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[4] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external;
function commit_new_parameters(
int128 amplification,
int128 new_fee,
int128 new_admin_fee
) external;
function apply_new_parameters() external;
function revert_new_parameters() external;
function commit_transfer_ownership(address _owner) external;
function apply_transfer_ownership() external;
function revert_transfer_ownership() external;
function withdraw_admin_fees() external;
function coins(int128 arg0) external returns (address out);
function underlying_coins(int128 arg0) external returns (address out);
function balances(int128 arg0) external returns (uint256 out);
function A() external returns (int128 out);
function fee() external returns (int128 out);
function admin_fee() external returns (int128 out);
function owner() external returns (address out);
function admin_actions_deadline() external returns (uint256 out);
function transfer_ownership_deadline() external returns (uint256 out);
function future_A() external returns (int128 out);
function future_fee() external returns (int128 out);
function future_admin_fee() external returns (int128 out);
function future_owner() external returns (address out);
function calc_withdraw_one_coin(uint256 _token_amount, int128 _i)
external
view
returns (uint256 out);
function calc_token_amount(uint256[2] calldata amounts, bool isDeposit)
external
view
returns (uint256);
function calc_token_amount(uint256[3] calldata amounts, bool isDeposit)
external
view
returns (uint256);
function calc_token_amount(uint256[4] calldata amounts, bool isDeposit)
external
view
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IBadgerSettPeak {
function mint(
uint256 poolId,
uint256 inAmount,
bytes32[] calldata merkleProof
) external returns (uint256 outAmount);
function approveContractAccess(address account) external;
function owner() external view returns (address _owner);
function redeem(uint256 poolId, uint256 inAmount)
external
returns (uint256 outAmount);
function calcMint(uint256 poolId, uint256 inAmount)
external
view
returns (uint256 bBTC, uint256 fee);
function calcRedeem(uint256 poolId, uint256 bBtc)
external
view
returns (
uint256 sett,
uint256 fee,
uint256 max
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
interface IBadgerYearnWbtcPeak {
function mint(uint256 inAmount, bytes32[] calldata merkleProof)
external
returns (uint256 outAmount);
function approveContractAccess(address account) external;
function owner() external view returns (address _owner);
function redeem(uint256 inAmount) external returns (uint256 outAmount);
function calcMint(uint256 inAmount)
external
view
returns (uint256 bBTC, uint256 fee);
function calcRedeem(uint256 bBtc)
external
view
returns (
uint256 sett,
uint256 fee,
uint256 max
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | passing in empty variable, no longer used in peak contract | function _mintIbbtc(
address _vault,
address _user,
uint256 _amount
) internal {
uint256 poolId = vaultToPoolId[_vault];
uint256 mintAmount = 0;
bytes32[] memory unused;
if (poolId == 3) {
IERC20(_vault).approve(address(yearnWbtcPeak), _amount);
mintAmount = yearnWbtcPeak.mint(_amount, unused);
IERC20(_vault).approve(address(settPeak), _amount);
mintAmount = settPeak.mint(poolId, _amount, unused);
}
ibBTC.safeTransfer(_user, mintAmount);
}
| 1,689,536 | [
1,
5466,
310,
316,
1008,
2190,
16,
1158,
7144,
1399,
316,
11148,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
81,
474,
45,
9897,
5111,
12,
203,
565,
1758,
389,
26983,
16,
203,
565,
1758,
389,
1355,
16,
203,
565,
2254,
5034,
389,
8949,
203,
225,
262,
2713,
288,
203,
565,
2254,
5034,
2845,
548,
273,
9229,
774,
25136,
63,
67,
26983,
15533,
203,
565,
2254,
5034,
312,
474,
6275,
273,
374,
31,
203,
565,
1731,
1578,
8526,
3778,
10197,
31,
203,
565,
309,
261,
6011,
548,
422,
890,
13,
288,
203,
1377,
467,
654,
39,
3462,
24899,
26983,
2934,
12908,
537,
12,
2867,
12,
20513,
1303,
59,
70,
5111,
11227,
581,
3631,
389,
8949,
1769,
203,
1377,
312,
474,
6275,
273,
677,
73,
1303,
59,
70,
5111,
11227,
581,
18,
81,
474,
24899,
8949,
16,
10197,
1769,
203,
1377,
467,
654,
39,
3462,
24899,
26983,
2934,
12908,
537,
12,
2867,
12,
542,
88,
11227,
581,
3631,
389,
8949,
1769,
203,
1377,
312,
474,
6275,
273,
26319,
11227,
581,
18,
81,
474,
12,
6011,
548,
16,
389,
8949,
16,
10197,
1769,
203,
565,
289,
203,
565,
9834,
38,
15988,
18,
4626,
5912,
24899,
1355,
16,
312,
474,
6275,
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
] |
// DELTA-BUG-BOUNTY
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../../../libs/Address.sol";
import "../../../libs/SafeMath.sol";
import "../../Common/OVLBase.sol";
import "../../../../common/OVLTokenTypes.sol";
import "../../Common/OVLVestingCalculator.sol";
import "../../../../interfaces/IOVLTransferHandler.sol";
import "../../../../interfaces/IDeltaDistributor.sol";
import "../../../../interfaces/IDeltaToken.sol";
contract OVLTransferHandler is OVLBase, OVLVestingCalculator, IOVLTransferHandler {
using SafeMath for uint256;
using Address for address;
address public constant UNI_DELTA_WETH_PAIR = 0x9EA3b5b4EC044b70375236A281986106457b20EF;
address public constant DEEP_FARMING_VAULT = 0x9fE9Bb6B66958f2271C4B0aD23F6E8DDA8C221BE;
event Transfer(address indexed from, address indexed to, uint256 value);
constructor(address, address) { // ignored props
}
function _removeBalanceFromSender(UserInformation storage senderInfo, address sender, bool immatureReceiverWhitelisted, uint256 amount) internal returns (uint256 totalRemoved) {
uint256 mostMatureTxIndex = senderInfo.mostMatureTxIndex;
uint256 lastInTxIndex = senderInfo.lastInTxIndex;
// We check if recipent can get immature tokens, if so we go from the most imature first to be most fair to the user
if (immatureReceiverWhitelisted) {
//////
////
// we go from the least mature balance to the msot mature meaning --
////
/////
uint256 accumulatedBalance;
while (true) {
uint256 leastMatureTxAmount = vestingTransactions[sender][lastInTxIndex].amount;
// Can never underflow due to if conditional
uint256 remainingBalanceNeeded = amount - accumulatedBalance;
if (leastMatureTxAmount >= remainingBalanceNeeded) {
// We got enough in this bucket to cover the amount
// We remove it from total and dont adjust the fully vesting timestamp
// Because there might be tokens left still in it
totalRemoved += remainingBalanceNeeded;
vestingTransactions[sender][lastInTxIndex].amount = leastMatureTxAmount - remainingBalanceNeeded; // safe math already checked
// We got what we wanted we leave the loop
break;
} else {
//we add the whole amount of this bucket to the accumulated balance
accumulatedBalance = accumulatedBalance.add(leastMatureTxAmount);
totalRemoved += leastMatureTxAmount;
delete vestingTransactions[sender][lastInTxIndex];
// And go to the more mature tx
if (lastInTxIndex == 0) {
lastInTxIndex = QTY_EPOCHS;
}
lastInTxIndex--;
// If we can't get enough in this tx and this is the last one, then we bail
if (lastInTxIndex == mostMatureTxIndex) {
// If we still have enough to cover in the mature balance we use that
uint256 maturedBalanceNeeded = amount - accumulatedBalance;
// Exhaustive underflow check
senderInfo.maturedBalance = senderInfo.maturedBalance.sub(maturedBalanceNeeded, "OVLTransferHandler: Insufficient funds");
totalRemoved += maturedBalanceNeeded;
break;
}
}
}
// We write to storage the lastTx Index, which was in memory and we looped over it (or not)
senderInfo.lastInTxIndex = lastInTxIndex;
return totalRemoved;
// End of logic in case reciever is whitelisted ( return assures)
}
uint256 maturedBalance = senderInfo.maturedBalance;
//////
////
// we go from the most mature balance up
////
/////
if (maturedBalance >= amount) {
senderInfo.maturedBalance = maturedBalance - amount; // safemath safe
totalRemoved = amount;
} else {
// Possibly using a partially vested transaction
uint256 accumulatedBalance = maturedBalance;
totalRemoved = maturedBalance;
// Use the entire balance to start
senderInfo.maturedBalance = 0;
while (amount > accumulatedBalance) {
VestingTransaction memory mostMatureTx = vestingTransactions[sender][mostMatureTxIndex];
// Guaranteed by `while` condition
uint256 remainingBalanceNeeded = amount - accumulatedBalance;
// Reduce this transaction as the final one
VestingTransactionDetailed memory dtx = getTransactionDetails(mostMatureTx, block.timestamp);
// credit is how much i got from this bucket
// So if i didnt get enough from this bucket here we zero it and move to the next one
if (remainingBalanceNeeded >= dtx.mature) {
totalRemoved += dtx.amount;
accumulatedBalance = accumulatedBalance.add(dtx.mature);
delete vestingTransactions[sender][mostMatureTxIndex]; // refund gas
} else {
// Remove the only needed amount
// Calculating debt based on the actual clamped credit eliminates
// the need for debit/credit ratio checks we initially had.
// Big gas savings using this one weird trick. Vitalik HATES it.
uint256 outputDebit = calculateTransactionDebit(dtx, remainingBalanceNeeded, block.timestamp);
remainingBalanceNeeded = outputDebit.add(remainingBalanceNeeded);
totalRemoved += remainingBalanceNeeded;
// We dont need to adjust timestamp
vestingTransactions[sender][mostMatureTxIndex].amount = mostMatureTx.amount.sub(remainingBalanceNeeded, "Removing too much from bucket");
break;
}
// If we just went throught he lasttx bucket, and we did not get enough then we bail
// Note if its the lastTransaction it already had a break;
if (mostMatureTxIndex == lastInTxIndex && accumulatedBalance < amount) { // accumulatedBalance < amount because of the case its exactly equal with first if
// Avoid ever looping around a second time because that would be bad
revert("OVLTransferHandler: Insufficient funds");
}
// We just emptied this so most mature one must be the next one
mostMatureTxIndex++;
if(mostMatureTxIndex == QTY_EPOCHS) {
mostMatureTxIndex = 0;
}
}
// We remove the entire amount removed
// We already added amount
senderInfo.mostMatureTxIndex = mostMatureTxIndex;
}
}
// function _transferTokensToRecipient(address recipient, UserInformation memory senderInfo, UserInformation memory recipientInfo, uint256 amount) internal {
function _transferTokensToRecipient(UserInformation storage recipientInfo, bool isSenderWhitelisted, address recipient, uint256 amount) internal {
// If the sender can send fully or this recipent is whitelisted to not get vesting we just add it to matured balance
(bool noVestingWhitelisted, uint256 maturedBalance, uint256 lastTransactionIndex) = (recipientInfo.noVestingWhitelisted, recipientInfo.maturedBalance, recipientInfo.lastInTxIndex);
if(isSenderWhitelisted || noVestingWhitelisted) {
recipientInfo.maturedBalance = maturedBalance.add(amount);
return;
}
VestingTransaction storage lastTransaction = vestingTransactions[recipient][lastTransactionIndex];
// Do i fit in this bucket?
// conditions for fitting inside a bucket are
// 1 ) Either its less than 2 days old
// 2 ) Or its more than 14 days old
// 3 ) Or we move to the next one - which is empty or already matured
// Note that only the first bucket checked can logically be less than 2 days old, this is a important optimization
// So lets take care of that case now, so its not checked in the loop.
uint256 timestampNow = block.timestamp;
uint256 fullVestingTimestamp = lastTransaction.fullVestingTimestamp;
if (timestampNow >= fullVestingTimestamp) {// Its mature we move it to mature and override or we move to the next one, which is always either 0 or matured
recipientInfo.maturedBalance = maturedBalance.add(lastTransaction.amount);
lastTransaction.amount = amount;
lastTransaction.fullVestingTimestamp = timestampNow + FULL_EPOCH_TIME;
} else if (fullVestingTimestamp >= timestampNow + SECONDS_PER_EPOCH * (QTY_EPOCHS - 1)) {// we add 12 days
// we avoid overflows from 0 fullyvestedtimestamp
// if fullyVestingTimestamp is bigger than that we should increment
// but not bigger than fullyVesting
// This check is exhaustive
// If this is the case we just put it in this bucket.
lastTransaction.amount = lastTransaction.amount.add(amount);
/// No need to adjust timestamp`
} else {
// We move into the next one
lastTransactionIndex++;
if (lastTransactionIndex == QTY_EPOCHS) { lastTransactionIndex = 0; } // Loop over
recipientInfo.lastInTxIndex = lastTransactionIndex;
// To figure out if this is a empty bucket or a stale one
// Its either the most mature one
// Or its 0
// There is no other logical options
// If this is the most mature one then we go > with most mature
uint256 mostMature = recipientInfo.mostMatureTxIndex;
if (mostMature == lastTransactionIndex) {
// It was the most mature one, so we have to increment the most mature index
mostMature++;
if (mostMature == QTY_EPOCHS) { mostMature = 0; }
recipientInfo.mostMatureTxIndex = mostMature;
}
VestingTransaction storage evenLatestTransaction = vestingTransactions[recipient][lastTransactionIndex];
// Its mature we move it to mature and override or we move to the next one, which is always either 0 or matured
recipientInfo.maturedBalance = maturedBalance.add(evenLatestTransaction.amount);
evenLatestTransaction.amount = amount;
evenLatestTransaction.fullVestingTimestamp = timestampNow + FULL_EPOCH_TIME;
}
}
function addAllowanceToDFV(address sender) internal {
// If you transferFrom from anyone even 1 gwei unit
// This will force dfv to have infinite allowance
// But this is not abug because DFV has defacto infinite allowance becaose of this function
// So there is no change
_allowances[sender][DEEP_FARMING_VAULT] = uint(-1);
}
function handleUniswapAdjustmenets() internal{
uint256 newLPSupply = IERC20(UNI_DELTA_WETH_PAIR).balanceOf(UNI_DELTA_WETH_PAIR);
require(newLPSupply >= lpTokensInPair, "DELTAToken: Liquidity removals are forbidden");
// We allow people to bump the number of LP tokens inside the pair, but we dont allow them to go lower
// Making liquidity withdrawals impossible
// Because uniswap queries banaceOf before doing a burn, that means we can detect a inflow of LP tokens
// But someone could send them and then reset with this function
// This is why we "lock" the bigger amount here and dont allow a lower amount than the last time
// Making it impossible to anyone who sent the liquidity tokens to the pair (which is nessesary to burn) not be able to burn them
lpTokensInPair = newLPSupply;
}
// This function does not need authentication, because this is EXCLUSIVELY
// ever meant to be called using delegatecall() from the main token.
// The memory it modifies in DELTAToken is what effects user balances.
function handleTransfer(address sender, address recipient, uint256 amount) external override {
require(sender != recipient, "DELTAToken: Can not send DELTA to yourself");
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
/// Liquidity removal protection
if (!liquidityRebasingPermitted && (sender == UNI_DELTA_WETH_PAIR || recipient == UNI_DELTA_WETH_PAIR)) {
handleUniswapAdjustmenets();
}
if(recipient == DEEP_FARMING_VAULT) {
addAllowanceToDFV(sender);
}
UserInformation storage recipientInfo = _userInformation[recipient];
UserInformation storage senderInfo = _userInformation[sender];
uint256 totalRemoved = _removeBalanceFromSender(senderInfo, sender, recipientInfo.immatureReceiverWhitelisted, amount);
uint256 toDistributor = totalRemoved.sub(amount, "OVLTransferHandler: Insufficient funds");
// We remove from max balance totals
senderInfo.maxBalance = senderInfo.maxBalance.sub(totalRemoved, "OVLTransferHandler: Insufficient funds");
// Sanity check
require(totalRemoved >= amount, "OVLTransferHandler: Insufficient funds");
// Max is 90% of total removed
require(amount.mul(9) >= toDistributor, "DELTAToken: Burned too many tokens");
if(toDistributor > 0) {
_creditDistributor(sender, toDistributor);
}
//////
/// We add tokens to the recipient
//////
_transferTokensToRecipient(recipientInfo, senderInfo.fullSenderWhitelisted, recipient, amount);
// We add to total balance for sanity checks and uniswap router
recipientInfo.maxBalance = recipientInfo.maxBalance.add(amount);
emit Transfer(sender, recipient, amount);
}
function _creditDistributor(address creditedBy, uint256 amount) internal {
address _distributor = distributor; // gas savings for storage reads
UserInformation storage distributorInfo = _userInformation[distributor];
distributorInfo.maturedBalance = distributorInfo.maturedBalance.add(amount); // Should trigger an event here
distributorInfo.maxBalance = distributorInfo.maxBalance.add(amount);
IDeltaDistributor(_distributor).creditUser(creditedBy, amount);
emit Transfer(creditedBy, _distributor, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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;
}
}
// DELTA-BUG-BOUNTY
pragma abicoder v2;
pragma solidity ^0.7.6;
import "./../../../common/OVLTokenTypes.sol";
contract OVLBase {
// Shared state begin v0
mapping (address => VestingTransaction[QTY_EPOCHS]) public vestingTransactions;
mapping (address => UserInformation) internal _userInformation;
mapping (address => uint256) internal _maxPossibleBalances;
mapping (address => mapping (address => uint256)) internal _allowances;
address public distributor;
uint256 public lpTokensInPair;
bool public liquidityRebasingPermitted;
uint256 [72] private _gap;
// Shared state end of v0
}
// SPDX-License-Identifier: UNLICENSED
// DELTA-BUG-BOUNTY
pragma solidity ^0.7.6;
struct VestingTransaction {
uint256 amount;
uint256 fullVestingTimestamp;
}
struct WalletTotals {
uint256 mature;
uint256 immature;
uint256 total;
}
struct UserInformation {
// This is going to be read from only [0]
uint256 mostMatureTxIndex;
uint256 lastInTxIndex;
uint256 maturedBalance;
uint256 maxBalance;
bool fullSenderWhitelisted;
// Note that recieving immature balances doesnt mean they recieve them fully vested just that senders can do it
bool immatureReceiverWhitelisted;
bool noVestingWhitelisted;
}
struct UserInformationLite {
uint256 maturedBalance;
uint256 maxBalance;
uint256 mostMatureTxIndex;
uint256 lastInTxIndex;
}
struct VestingTransactionDetailed {
uint256 amount;
uint256 fullVestingTimestamp;
// uint256 percentVestedE4;
uint256 mature;
uint256 immature;
}
uint256 constant QTY_EPOCHS = 7;
uint256 constant SECONDS_PER_EPOCH = 172800; // About 2days
uint256 constant FULL_EPOCH_TIME = SECONDS_PER_EPOCH * QTY_EPOCHS;
// Precision Multiplier -- this many zeros (23) seems to get all the precision needed for all 18 decimals to be only off by a max of 1 unit
uint256 constant PM = 1e23;
// DELTA-BUG-BOUNTY
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./../../../common/OVLTokenTypes.sol";
import "../../../interfaces/IOVLVestingCalculator.sol";
import "../../libs/SafeMath.sol";
contract OVLVestingCalculator is IOVLVestingCalculator {
using SafeMath for uint256;
function getTransactionDetails(VestingTransaction memory _tx) public view override returns (VestingTransactionDetailed memory dtx) {
return getTransactionDetails(_tx, block.timestamp);
}
function getTransactionDetails(VestingTransaction memory _tx, uint256 _blockTimestamp) public pure override returns (VestingTransactionDetailed memory dtx) {
if(_tx.fullVestingTimestamp == 0) {
return dtx;
}
dtx.amount = _tx.amount;
dtx.fullVestingTimestamp = _tx.fullVestingTimestamp;
// at precision E4, 1000 is 10%
uint256 timeRemaining;
if(_blockTimestamp >= dtx.fullVestingTimestamp) {
// Fully vested
dtx.mature = _tx.amount;
return dtx;
} else {
timeRemaining = dtx.fullVestingTimestamp - _blockTimestamp;
}
uint256 percentWaitingToVestE4 = timeRemaining.mul(1e4) / FULL_EPOCH_TIME;
uint256 percentWaitingToVestE4Scaled = percentWaitingToVestE4.mul(90) / 100;
dtx.immature = _tx.amount.mul(percentWaitingToVestE4Scaled) / 1e4;
dtx.mature = _tx.amount.sub(dtx.immature);
}
function getMatureBalance(VestingTransaction memory _tx, uint256 _blockTimestamp) public pure override returns (uint256 mature) {
if(_tx.fullVestingTimestamp == 0) {
return 0;
}
uint256 timeRemaining;
if(_blockTimestamp >= _tx.fullVestingTimestamp) {
// Fully vested
return _tx.amount;
} else {
timeRemaining = _tx.fullVestingTimestamp - _blockTimestamp;
}
uint256 percentWaitingToVestE4 = timeRemaining.mul(1e4) / FULL_EPOCH_TIME;
uint256 percentWaitingToVestE4Scaled = percentWaitingToVestE4.mul(90) / 100;
mature = _tx.amount.mul(percentWaitingToVestE4Scaled) / 1e4;
mature = _tx.amount.sub(mature); // the subtracted value represents the immature balance at this point
}
function calculateTransactionDebit(VestingTransactionDetailed memory dtx, uint256 matureAmountNeeded, uint256 currentTimestamp) public pure override returns (uint256 outputDebit) {
if(dtx.fullVestingTimestamp > currentTimestamp) {
// This will be between 0 and 100*pm representing how much of the mature pool is needed
uint256 percentageOfMatureCoinsConsumed = matureAmountNeeded.mul(PM).div(dtx.mature);
require(percentageOfMatureCoinsConsumed <= PM, "OVLTransferHandler: Insufficient funds");
// Calculate the number of immature coins that need to be debited based on this ratio
outputDebit = dtx.immature.mul(percentageOfMatureCoinsConsumed) / PM;
}
// shouldnt this use outputDebit
require(dtx.amount <= dtx.mature.add(dtx.immature), "DELTAToken: Balance maximum problem"); // Just in case
}
}
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.6;
interface IOVLTransferHandler {
function handleTransfer(address sender, address recipient, uint256 amount) external;
}
pragma solidity ^0.7.6;
interface IDeltaDistributor {
function creditUser(address,uint256) external;
function addDevested(address, uint256) external;
function distribute() external;
}
// SPDX-License-Identifier: UNLICENSED
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../common/OVLTokenTypes.sol";
interface IDeltaToken is IERC20 {
function vestingTransactions(address, uint256) external view returns (VestingTransaction memory);
function getUserInfo(address) external view returns (UserInformationLite memory);
function getMatureBalance(address, uint256) external view returns (uint256);
function liquidityRebasingPermitted() external view returns (bool);
function lpTokensInPair() external view returns (uint256);
function governance() external view returns (address);
function performLiquidityRebasing() external;
function distributor() external view returns (address);
function totalsForWallet(address ) external view returns (WalletTotals memory totals);
function adjustBalanceOfNoVestingAccount(address, uint256,bool) external;
function userInformation(address user) external view returns (UserInformation memory);
}
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../common/OVLTokenTypes.sol";
interface IOVLVestingCalculator {
function getTransactionDetails(VestingTransaction memory _tx) external view returns (VestingTransactionDetailed memory dtx);
function getTransactionDetails(VestingTransaction memory _tx, uint256 _blockTimestamp) external pure returns (VestingTransactionDetailed memory dtx);
function getMatureBalance(VestingTransaction memory _tx, uint256 _blockTimestamp) external pure returns (uint256 mature);
function calculateTransactionDebit(VestingTransactionDetailed memory dtx, uint256 matureAmountNeeded, uint256 currentTimestamp) external pure returns (uint256 outputDebit);
}
// 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);
}
| It was the most mature one, so we have to increment the most mature index | if (mostMature == lastTransactionIndex) {
mostMature++;
recipientInfo.mostMatureTxIndex = mostMature;
}
VestingTransaction storage evenLatestTransaction = vestingTransactions[recipient][lastTransactionIndex];
evenLatestTransaction.amount = amount;
evenLatestTransaction.fullVestingTimestamp = timestampNow + FULL_EPOCH_TIME;
| 10,423,762 | [
1,
7193,
1703,
326,
4486,
312,
1231,
1245,
16,
1427,
732,
1240,
358,
5504,
326,
4486,
312,
1231,
770,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
309,
261,
10329,
49,
1231,
422,
1142,
3342,
1016,
13,
288,
203,
7734,
4486,
49,
1231,
9904,
31,
203,
203,
203,
7734,
8027,
966,
18,
10329,
49,
1231,
4188,
1016,
273,
4486,
49,
1231,
31,
203,
5411,
289,
203,
203,
5411,
776,
10100,
3342,
2502,
5456,
18650,
3342,
273,
331,
10100,
14186,
63,
20367,
6362,
2722,
3342,
1016,
15533,
203,
203,
203,
5411,
5456,
18650,
3342,
18,
8949,
273,
3844,
31,
203,
5411,
5456,
18650,
3342,
18,
2854,
58,
10100,
4921,
273,
2858,
8674,
397,
18153,
67,
41,
30375,
67,
4684,
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
] |
./full_match/71402/0x3484B2F4dda474609907d22c4445F5809Ffc382f/sources/contracts/aave/protocol/libraries/helpers/Errors.sol | Variable borrow index overflows uint128
| string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; | 7,093,216 | [
1,
3092,
29759,
770,
9391,
87,
2254,
10392,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
533,
1071,
5381,
534,
48,
67,
16444,
67,
38,
916,
11226,
67,
9199,
67,
12959,
17430,
273,
296,
9401,
13506,
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
] |
// RUN: --target solana --emit llvm-ir
// READ: bundle.ll
contract c {
struct S {
int8[2] f1;
bool f2;
Q[3] f3;
}
struct Q {
bool[2] f1;
uint64[4] f2;
}
// BEGIN-CHECK: @"c::c::function::foo__c.S"({ [2 x i8], i1, [3 x { [2 x i1], [4 x i64] }] }* %0
function foo(S s) public pure {
}
} | BEGIN-CHECK: @"c::c::function::foo__c.S"({ [2 x i8], i1, [3 x { [2 x i1], [4 x i64] }] }* %0 | function foo(S s) public pure {
}
| 12,735,288 | [
1,
16061,
17,
10687,
30,
632,
6,
71,
2866,
71,
2866,
915,
2866,
11351,
972,
71,
18,
55,
6,
12590,
306,
22,
619,
277,
28,
6487,
277,
21,
16,
306,
23,
619,
288,
306,
22,
619,
277,
21,
6487,
306,
24,
619,
277,
1105,
65,
289,
65,
289,
738,
20,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8431,
12,
55,
272,
13,
1071,
16618,
288,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-10
*/
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
// 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);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File @openzeppelin/contracts/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/ContentMixin.sol
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender() internal view returns (address payable sender) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// File contracts/Factory.sol
pragma solidity ^0.8.0;
abstract contract Factory {
enum Segment {
AIRDROP,
TEAM,
WHITELIST,
PUBLIC
}
struct Options {
mapping(address => bool) _beneficiary;
mapping(address => bool) _minted;
uint256 _amount;
uint256 _maxMint;
}
mapping(Segment => Options) public _segmentOptions;
function _add(Segment segment, address account) internal {
_segmentOptions[segment]._beneficiary[account] = true;
}
function _remove(Segment segment, address account) internal {
require(
_segmentOptions[segment]._beneficiary[account],
"address is not in the whitelist"
);
delete _segmentOptions[segment]._beneficiary[account];
}
function _has(Segment segment, address account)
internal
view
returns (bool)
{
return
_segmentOptions[segment]._beneficiary[account] &&
!_segmentOptions[segment]._minted[account];
}
}
// File contracts/Whitelist.sol
pragma solidity ^0.8.0;
contract Whitelist is Factory, Ownable, ContextMixin {
using SafeMath for uint256;
uint256 public constant WHITELIST_PRICE = 0.069 ether;
uint256 public constant TEAM_PRICE = 0.069 ether;
uint256 public constant AIRDROP_PRICE = 0 ether;
uint256 public constant PUBLIC_PRICE = 0.099 ether;
constructor() {
_segmentOptions[Segment.WHITELIST]._amount = WHITELIST_PRICE;
_segmentOptions[Segment.WHITELIST]._maxMint = 1;
_segmentOptions[Segment.TEAM]._amount = TEAM_PRICE;
_segmentOptions[Segment.TEAM]._maxMint = 2;
_segmentOptions[Segment.AIRDROP]._amount = AIRDROP_PRICE;
_segmentOptions[Segment.AIRDROP]._maxMint = 1;
_segmentOptions[Segment.PUBLIC]._amount = PUBLIC_PRICE;
_segmentOptions[Segment.PUBLIC]._maxMint = 5;
}
function addBeneficiaryAirdrop(address _beneficiary) public onlyOwner {
_add(Segment.AIRDROP, _beneficiary);
}
function addBeneficiaryAirdrop(address[] memory _beneficiary)
public
onlyOwner
{
for (uint256 i = 0; i < _beneficiary.length; i++) {
_add(Segment.AIRDROP, _beneficiary[i]);
}
}
function airdropWhitelisted() public view returns (bool) {
return _has(Segment.AIRDROP, _msgSender());
}
function addBeneficiaryWhitelist(address _beneficiary) public onlyOwner {
_add(Segment.WHITELIST, _beneficiary);
}
function addBeneficiaryWhitelist(address[] memory _beneficiary)
public
onlyOwner
{
for (uint256 i = 0; i < _beneficiary.length; i++) {
_add(Segment.WHITELIST, _beneficiary[i]);
}
}
function whitelisted() public view returns (bool) {
return _has(Segment.WHITELIST, _msgSender());
}
function addBeneficiaryTeam(address _beneficiary) public onlyOwner {
_add(Segment.TEAM, _beneficiary);
}
function addBeneficiaryTeam(address[] memory _beneficiary)
public
onlyOwner
{
for (uint256 i = 0; i < _beneficiary.length; i++) {
_add(Segment.TEAM, _beneficiary[i]);
}
}
function teamWhitelisted() public view returns (bool) {
return _has(Segment.TEAM, _msgSender());
}
}
// File contracts/WXGNFT.sol
pragma solidity ^0.8.0;
contract OwnableDelegateProxy {
// solhint-disable-previous-line no-empty-blocks
}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract WXGNFT is
ERC721,
Ownable,
Pausable,
ContextMixin,
ReentrancyGuard,
Whitelist
{
using SafeMath for uint256;
using Counters for Counters.Counter;
uint256 public constant MAX_SUPPLY = 1001;
uint256 public openTime;
uint256 public closeTime;
uint256 public whitelistOpentime;
uint256 public whitelistClosetime;
address public proxyRegistryAddress;
address public fundWallet;
string public baseTokenURI;
Counters.Counter private _nextTokenId;
bool public revealed = false;
constructor(
string memory _baseTokenURI,
address _proxyRegistryAddress,
address _fundWallet,
uint256 _openTime,
uint256 _closeTime,
uint256 _whitelistOpentime,
uint256 _whitelistClosetime
) ERC721("Wicked X Gang", "WXG") Whitelist() {
proxyRegistryAddress = _proxyRegistryAddress;
fundWallet = _fundWallet;
openTime = _openTime;
closeTime = _closeTime;
whitelistClosetime = _whitelistClosetime;
whitelistOpentime = _whitelistOpentime;
_nextTokenId.increment();
baseTokenURI = _baseTokenURI;
}
event MintWXCNFT(address indexed to, uint256 indexed tokenId);
event WhitelistMint(address indexed _to, uint256 _amount);
event AirdropMint(address indexed _to, uint256 _amount);
event TeamMint(address indexed _to, uint256 _amount);
event PublicMint(address indexed _to, uint256 _amount);
receive() external payable {
// solhint-disable-previous-line no-empty-blocks
}
modifier whenOpen() {
require(
block.timestamp >= openTime && block.timestamp < closeTime,
"Not open yet"
);
_;
}
modifier whenWhitelistOpen() {
require(
block.timestamp >= whitelistOpentime &&
block.timestamp < whitelistClosetime,
"Whitelist not open yet"
);
_;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function reveal() public onlyOwner {
require(!revealed, "Already revealed");
revealed = true;
}
function setBaseURI(string memory _tokenURI) public onlyOwner {
baseTokenURI = _tokenURI;
}
function mintTo(address _to) public onlyOwner {
require(totalSupply().add(1) <= MAX_SUPPLY, "Max supply reached");
uint256 currentTokenId = _nextTokenId.current();
_nextTokenId.increment();
_safeMint(_to, currentTokenId);
}
function mint(uint256 _mintAmount)
public
payable
nonReentrant
whenNotPaused
whenOpen
{
_mintNFT(Segment.PUBLIC, _mintAmount);
emit PublicMint(_msgSender(), _mintAmount);
}
function mintWhitelist(uint256 _mintAmount)
public
payable
nonReentrant
whenNotPaused
whenWhitelistOpen
{
_mintNFT(Segment.WHITELIST, _mintAmount);
emit WhitelistMint(_msgSender(), _mintAmount);
}
function mintAirdrop(uint256 _mintAmount)
public
payable
nonReentrant
whenNotPaused
whenWhitelistOpen
{
_mintNFT(Segment.AIRDROP, _mintAmount);
emit AirdropMint(_msgSender(), _mintAmount);
}
function mintTeam(uint256 _mintAmount)
public
payable
nonReentrant
whenNotPaused
whenWhitelistOpen
{
_mintNFT(Segment.TEAM, _mintAmount);
emit TeamMint(_msgSender(), _mintAmount);
}
function _mintNFT(Segment _segment, uint256 _mintAmount) internal {
_prevalidateMint(_segment, _mintAmount);
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 currentTokenId = _nextTokenId.current();
_nextTokenId.increment();
_safeMint(_msgSender(), currentTokenId);
emit MintWXCNFT(_msgSender(), currentTokenId);
}
_forwardFunds(price(_segment, _mintAmount));
}
function unpack(uint256 _tokenId) public view {
require(ownerOf(_tokenId) == _msgSender(), "You are not the owner");
tokenURI(_tokenId);
}
function _prevalidateMint(Segment _segment, uint256 _mintAmount) internal {
require(_mintAmount > 0, "Mint amount zero");
require(_msgSender() != address(0), "Mint to 0 address is not allowed");
require(
msg.value >= price(_segment, _mintAmount),
"Insufficient funds"
);
require(
_mintAmount <= _segmentOptions[_segment]._maxMint,
"Max mint amount reached"
);
if (_segment != Segment.PUBLIC) {
require(
!_segmentOptions[_segment]._minted[_msgSender()],
"Already minted"
);
require(
_segmentOptions[_segment]._beneficiary[_msgSender()],
"Not whitelisted"
);
}
_segmentOptions[_segment]._minted[_msgSender()] = true;
}
function _forwardFunds(uint256 amount) internal {
(bool succeed, ) = fundWallet.call{value: amount}("");
require(succeed, "Failed to send Ether");
}
function price(Segment segment, uint256 amount)
internal
view
returns (uint256)
{
return amount.mul(_segmentOptions[segment]._amount);
}
function totalSupply() public view returns (uint256) {
return _nextTokenId.current() - 1;
}
function remainingSupply() public view returns (uint256) {
return MAX_SUPPLY.sub(totalSupply());
}
function isCanMint()
public
view
returns (
bool,
bool,
bool,
bool
)
{
return (
airdropWhitelisted(),
teamWhitelisted(),
whitelisted(),
published()
);
}
function wxcSeting(
address _proxyRegistryAddress,
address _fundWallet,
uint256 _openTime,
uint256 _closeTime,
uint256 _whitelistOpentime,
uint256 _whitelistClosetime
) public onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
fundWallet = _fundWallet;
openTime = _openTime;
closeTime = _closeTime;
whitelistClosetime = _whitelistClosetime;
whitelistOpentime = _whitelistOpentime;
}
function published() public view returns (bool) {
//return !_segmentOptions[Segment.PUBLIC]._minted[_msgSender()];
return block.timestamp >= openTime && block.timestamp < closeTime;
}
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId), "URI query for nonexistent token");
if (revealed) {
return
string(
abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))
);
}
return baseTokenURI;
}
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function _msgSender() internal view override returns (address sender) {
return ContextMixin.msgSender();
}
} | return !_segmentOptions[Segment.PUBLIC]._minted[_msgSender()]; | function published() public view returns (bool) {
return block.timestamp >= openTime && block.timestamp < closeTime;
}
| 15,444,944 | [
1,
2463,
401,
67,
9273,
1320,
63,
4131,
18,
14939,
65,
6315,
81,
474,
329,
63,
67,
3576,
12021,
1435,
15533,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9487,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1203,
18,
5508,
1545,
1696,
950,
597,
1203,
18,
5508,
411,
1746,
950,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xDc10bDD7Bd1D9CeDdEc7F920db9c111Ff667f8DA/sources/SIXPOINTSIX.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("6.6", "6") {
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 _buyCharityFee = 0;
uint256 _buyMarketingFee = 26;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellCharityFee = 0;
uint256 _sellMarketingFee = 31;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 100000 * 1e18;
buyCharityFee = _buyCharityFee;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee;
sellCharityFee = _sellCharityFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,631,457 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1435,
4232,
39,
3462,
2932,
26,
18,
26,
3113,
315,
26,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
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,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
202,
202,
11890,
5034,
389,
70,
9835,
2156,
560,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
10659,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
2
] |
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: REMIX_FILE_SYNC/ApprovedCreatorRegistryInterface.sol
pragma solidity ^0.4.22;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
contract ApprovedCreatorRegistryInterface {
function getVersion() public pure returns (uint);
function typeOfContract() public pure returns (string);
function isOperatorApprovedForCustodialAccount(
address _operator,
address _custodialAddress) public view returns (bool);
}
// File: REMIX_FILE_SYNC/DigitalMediaStoreInterface.sol
pragma solidity 0.4.25;
/**
* Interface to the digital media store external contract that is
* responsible for storing the common digital media and collection data.
* This allows for new token contracts to be deployed and continue to reference
* the digital media and collection data.
*/
contract DigitalMediaStoreInterface {
function getDigitalMediaStoreVersion() public pure returns (uint);
function getStartingDigitalMediaId() public view returns (uint256);
function registerTokenContractAddress() external;
/**
* Creates a new digital media object in storage
* @param _creator address the address of the creator
* @param _printIndex uint32 the current print index for the limited edition media
* @param _totalSupply uint32 the total allowable prints for this media
* @param _collectionId uint256 the collection id that this media belongs to
* @param _metadataPath string the ipfs metadata path
* @return the id of the new digital media created
*/
function createDigitalMedia(
address _creator,
uint32 _printIndex,
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath) external returns (uint);
/**
* Increments the current print index of the digital media object
* @param _digitalMediaId uint256 the id of the digital media
* @param _increment uint32 the amount to increment by
*/
function incrementDigitalMediaPrintIndex(
uint256 _digitalMediaId,
uint32 _increment) external;
/**
* Retrieves the digital media object by id
* @param _digitalMediaId uint256 the address of the creator
*/
function getDigitalMedia(uint256 _digitalMediaId) external view returns(
uint256 id,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
address creator,
string metadataPath);
/**
* Creates a new collection
* @param _creator address the address of the creator
* @param _metadataPath string the ipfs metadata path
* @return the id of the new collection created
*/
function createCollection(address _creator, string _metadataPath) external returns (uint);
/**
* Retrieves a collection by id
* @param _collectionId uint256
*/
function getCollection(uint256 _collectionId) external view
returns(
uint256 id,
address creator,
string metadataPath);
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.21;
/**
* @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;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.21;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: REMIX_FILE_SYNC/MediaStoreVersionControl.sol
pragma solidity 0.4.25;
/**
* A special control class that is used to configure and manage a token contract's
* different digital media store versions.
*
* Older versions of token contracts had the ability to increment the digital media's
* print edition in the media store, which was necessary in the early stages to provide
* upgradeability and flexibility.
*
* New verions will get rid of this ability now that token contract logic
* is more stable and we've built in burn capabilities.
*
* In order to support the older tokens, we need to be able to look up the appropriate digital
* media store associated with a given digital media id on the latest token contract.
*/
contract MediaStoreVersionControl is Pausable {
// The single allowed creator for this digital media contract.
DigitalMediaStoreInterface public v1DigitalMediaStore;
// The current digitial media store, used for this tokens creation.
DigitalMediaStoreInterface public currentDigitalMediaStore;
uint256 public currentStartingDigitalMediaId;
/**
* Validates that the managers are initialized.
*/
modifier managersInitialized() {
require(v1DigitalMediaStore != address(0));
require(currentDigitalMediaStore != address(0));
_;
}
/**
* Sets a digital media store address upon construction.
* Once set it's immutable, so that a token contract is always
* tied to one digital media store.
*/
function setDigitalMediaStoreAddress(address _dmsAddress)
internal {
DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress);
require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 2, "Incorrect version.");
currentDigitalMediaStore = candidateDigitalMediaStore;
currentDigitalMediaStore.registerTokenContractAddress();
currentStartingDigitalMediaId = currentDigitalMediaStore.getStartingDigitalMediaId();
}
/**
* Publicly callable by the owner, but can only be set one time, so don't make
* a mistake when setting it.
*
* Will also check that the version on the other end of the contract is in fact correct.
*/
function setV1DigitalMediaStoreAddress(address _dmsAddress) public onlyOwner {
require(address(v1DigitalMediaStore) == 0, "V1 media store already set.");
DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress);
require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 1, "Incorrect version.");
v1DigitalMediaStore = candidateDigitalMediaStore;
v1DigitalMediaStore.registerTokenContractAddress();
}
/**
* Depending on the digital media id, determines whether to return the previous
* version of the digital media manager.
*/
function _getDigitalMediaStore(uint256 _digitalMediaId)
internal
view
managersInitialized
returns (DigitalMediaStoreInterface) {
if (_digitalMediaId < currentStartingDigitalMediaId) {
return v1DigitalMediaStore;
} else {
return currentDigitalMediaStore;
}
}
}
// File: REMIX_FILE_SYNC/DigitalMediaManager.sol
pragma solidity 0.4.25;
/**
* Manager that interfaces with the underlying digital media store contract.
*/
contract DigitalMediaManager is MediaStoreVersionControl {
struct DigitalMedia {
uint256 id;
uint32 totalSupply;
uint32 printIndex;
uint256 collectionId;
address creator;
string metadataPath;
}
struct DigitalMediaCollection {
uint256 id;
address creator;
string metadataPath;
}
ApprovedCreatorRegistryInterface public creatorRegistryStore;
// Set the creator registry address upon construction. Immutable.
function setCreatorRegistryStore(address _crsAddress) internal {
ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress);
require(candidateCreatorRegistryStore.getVersion() == 1);
// Simple check to make sure we are adding the registry contract indeed
// https://fravoll.github.io/solidity-patterns/string_equality_comparison.html
require(keccak256(candidateCreatorRegistryStore.typeOfContract()) == keccak256("approvedCreatorRegistry"));
creatorRegistryStore = candidateCreatorRegistryStore;
}
/**
* Validates that the Registered store is initialized.
*/
modifier registryInitialized() {
require(creatorRegistryStore != address(0));
_;
}
/**
* Retrieves a collection object by id.
*/
function _getCollection(uint256 _id)
internal
view
managersInitialized
returns(DigitalMediaCollection) {
uint256 id;
address creator;
string memory metadataPath;
(id, creator, metadataPath) = currentDigitalMediaStore.getCollection(_id);
DigitalMediaCollection memory collection = DigitalMediaCollection({
id: id,
creator: creator,
metadataPath: metadataPath
});
return collection;
}
/**
* Retrieves a digital media object by id.
*/
function _getDigitalMedia(uint256 _id)
internal
view
managersInitialized
returns(DigitalMedia) {
uint256 id;
uint32 totalSupply;
uint32 printIndex;
uint256 collectionId;
address creator;
string memory metadataPath;
DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_id);
(id, totalSupply, printIndex, collectionId, creator, metadataPath) = _digitalMediaStore.getDigitalMedia(_id);
DigitalMedia memory digitalMedia = DigitalMedia({
id: id,
creator: creator,
totalSupply: totalSupply,
printIndex: printIndex,
collectionId: collectionId,
metadataPath: metadataPath
});
return digitalMedia;
}
/**
* Increments the print index of a digital media object by some increment.
*/
function _incrementDigitalMediaPrintIndex(DigitalMedia _dm, uint32 _increment)
internal
managersInitialized {
DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_dm.id);
_digitalMediaStore.incrementDigitalMediaPrintIndex(_dm.id, _increment);
}
// Check if the token operator is approved for the owner address
function isOperatorApprovedForCustodialAccount(
address _operator,
address _owner) internal view registryInitialized returns(bool) {
return creatorRegistryStore.isOperatorApprovedForCustodialAccount(
_operator, _owner);
}
}
// File: REMIX_FILE_SYNC/SingleCreatorControl.sol
pragma solidity 0.4.25;
/**
* A special control class that's used to help enforce that a DigitalMedia contract
* will service only a single creator's address. This is used when deploying a
* custom token contract owned and managed by a single creator.
*/
contract SingleCreatorControl {
// The single allowed creator for this digital media contract.
address public singleCreatorAddress;
// The single creator has changed.
event SingleCreatorChanged(
address indexed previousCreatorAddress,
address indexed newCreatorAddress);
/**
* Sets the single creator associated with this contract. This function
* can only ever be called once, and should ideally be called at the point
* of constructing the smart contract.
*/
function setSingleCreator(address _singleCreatorAddress) internal {
require(singleCreatorAddress == address(0), "Single creator address already set.");
singleCreatorAddress = _singleCreatorAddress;
}
/**
* Checks whether a given creator address matches the single creator address.
* Will always return true if a single creator address was never set.
*/
function isAllowedSingleCreator(address _creatorAddress) internal view returns (bool) {
require(_creatorAddress != address(0), "0x0 creator addresses are not allowed.");
return singleCreatorAddress == address(0) || singleCreatorAddress == _creatorAddress;
}
/**
* A publicly accessible function that allows the current single creator
* assigned to this contract to change to another address.
*/
function changeSingleCreator(address _newCreatorAddress) public {
require(_newCreatorAddress != address(0));
require(msg.sender == singleCreatorAddress, "Not approved to change single creator.");
singleCreatorAddress = _newCreatorAddress;
emit SingleCreatorChanged(singleCreatorAddress, _newCreatorAddress);
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.4.21;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/AddressUtils.sol
pragma solidity ^0.4.21;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev 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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol
pragma solidity ^0.4.21;
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: REMIX_FILE_SYNC/ERC721Safe.sol
pragma solidity 0.4.25;
// We have to specify what version of compiler this code will compile with
contract ERC721Safe is ERC721Token {
bytes4 constant internal InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant internal InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)'));
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// File: REMIX_FILE_SYNC/Memory.sol
pragma solidity 0.4.25;
library Memory {
// Size of a word, in bytes.
uint internal constant WORD_SIZE = 32;
// Size of the header of a 'bytes' array.
uint internal constant BYTES_HEADER_SIZE = 32;
// Address of the free memory pointer.
uint internal constant FREE_MEM_PTR = 0x40;
// Compares the 'len' bytes starting at address 'addr' in memory with the 'len'
// bytes starting at 'addr2'.
// Returns 'true' if the bytes are the same, otherwise 'false'.
function equals(uint addr, uint addr2, uint len) internal pure returns (bool equal) {
assembly {
equal := eq(keccak256(addr, len), keccak256(addr2, len))
}
}
// Compares the 'len' bytes starting at address 'addr' in memory with the bytes stored in
// 'bts'. It is allowed to set 'len' to a lower value then 'bts.length', in which case only
// the first 'len' bytes will be compared.
// Requires that 'bts.length >= len'
function equals(uint addr, uint len, bytes memory bts) internal pure returns (bool equal) {
require(bts.length >= len);
uint addr2;
assembly {
addr2 := add(bts, /*BYTES_HEADER_SIZE*/32)
}
return equals(addr, addr2, len);
}
// Allocates 'numBytes' bytes in memory. This will prevent the Solidity compiler
// from using this area of memory. It will also initialize the area by setting
// each byte to '0'.
function allocate(uint numBytes) internal pure returns (uint addr) {
// Take the current value of the free memory pointer, and update.
assembly {
addr := mload(/*FREE_MEM_PTR*/0x40)
mstore(/*FREE_MEM_PTR*/0x40, add(addr, numBytes))
}
uint words = (numBytes + WORD_SIZE - 1) / WORD_SIZE;
for (uint i = 0; i < words; i++) {
assembly {
mstore(add(addr, mul(i, /*WORD_SIZE*/32)), 0)
}
}
}
// Copy 'len' bytes from memory address 'src', to address 'dest'.
// This function does not check the or destination, it only copies
// the bytes.
function copy(uint src, uint dest, uint len) internal pure {
// Copy word-length chunks while possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
dest += WORD_SIZE;
src += WORD_SIZE;
}
// Copy remaining bytes
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
// Returns a memory pointer to the provided bytes array.
function ptr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := bts
}
}
// Returns a memory pointer to the data portion of the provided bytes array.
function dataPtr(bytes memory bts) internal pure returns (uint addr) {
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// This function does the same as 'dataPtr(bytes memory)', but will also return the
// length of the provided bytes array.
function fromBytes(bytes memory bts) internal pure returns (uint addr, uint len) {
len = bts.length;
assembly {
addr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
}
// Creates a 'bytes memory' variable from the memory address 'addr', with the
// length 'len'. The function will allocate new memory for the bytes array, and
// the 'len bytes starting at 'addr' will be copied into that new memory.
function toBytes(uint addr, uint len) internal pure returns (bytes memory bts) {
bts = new bytes(len);
uint btsptr;
assembly {
btsptr := add(bts, /*BYTES_HEADER_SIZE*/32)
}
copy(addr, btsptr, len);
}
// Get the word stored at memory address 'addr' as a 'uint'.
function toUint(uint addr) internal pure returns (uint n) {
assembly {
n := mload(addr)
}
}
// Get the word stored at memory address 'addr' as a 'bytes32'.
function toBytes32(uint addr) internal pure returns (bytes32 bts) {
assembly {
bts := mload(addr)
}
}
/*
// Get the byte stored at memory address 'addr' as a 'byte'.
function toByte(uint addr, uint8 index) internal pure returns (byte b) {
require(index < WORD_SIZE);
uint8 n;
assembly {
n := byte(index, mload(addr))
}
b = byte(n);
}
*/
}
// File: REMIX_FILE_SYNC/HelperUtils.sol
pragma solidity 0.4.25;
/**
* Internal helper functions
*/
contract HelperUtils {
// converts bytes32 to a string
// enable this when you use it. Saving gas for now
// function bytes32ToString(bytes32 x) private pure returns (string) {
// bytes memory bytesString = new bytes(32);
// uint charCount = 0;
// for (uint j = 0; j < 32; j++) {
// byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
// if (char != 0) {
// bytesString[charCount] = char;
// charCount++;
// }
// }
// bytes memory bytesStringTrimmed = new bytes(charCount);
// for (j = 0; j < charCount; j++) {
// bytesStringTrimmed[j] = bytesString[j];
// }
// return string(bytesStringTrimmed);
// }
/**
* Concatenates two strings
* @param _a string
* @param _b string
* @return string concatenation of two string
*/
function strConcat(string _a, string _b) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ab = new string(_ba.length + _bb.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
}
// File: REMIX_FILE_SYNC/DigitalMediaToken.sol
pragma solidity 0.4.25;
/**
* The DigitalMediaToken contract. Fully implements the ERC721 contract
* from OpenZeppelin without any modifications to it.
*
* This contract allows for the creation of:
* 1. New Collections
* 2. New DigitalMedia objects
* 3. New DigitalMediaRelease objects
*
* The primary piece of logic is to ensure that an ERC721 token can
* have a supply and print edition that is enforced by this contract.
*/
contract DigitalMediaToken is DigitalMediaManager, ERC721Safe, HelperUtils, SingleCreatorControl {
event DigitalMediaReleaseCreateEvent(
uint256 id,
address owner,
uint32 printEdition,
string tokenURI,
uint256 digitalMediaId);
// Event fired when a new digital media is created
event DigitalMediaCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
string metadataPath);
// Event fired when a digital media's collection is
event DigitalMediaCollectionCreateEvent(
uint256 id,
address storeContractAddress,
address creator,
string metadataPath);
// Event fired when a digital media is burned
event DigitalMediaBurnEvent(
uint256 id,
address caller,
address storeContractAddress);
// Event fired when burning a token
event DigitalMediaReleaseBurnEvent(
uint256 tokenId,
address owner);
event UpdateDigitalMediaPrintIndexEvent(
uint256 digitalMediaId,
uint32 printEdition);
// Event fired when a creator assigns a new creator address.
event ChangedCreator(
address creator,
address newCreator);
struct DigitalMediaRelease {
// The unique edition number of this digital media release
uint32 printEdition;
// Reference ID to the digital media metadata
uint256 digitalMediaId;
}
// Maps internal ERC721 token ID to digital media release object.
mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease;
// Maps a creator address to a new creator address. Useful if a creator
// changes their address or the previous address gets compromised.
mapping (address => address) public approvedCreators;
// Token ID counter
uint256 internal tokenIdCounter = 0;
constructor (string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter)
public ERC721Token(_tokenName, _tokenSymbol) {
tokenIdCounter = _tokenIdStartingCounter;
}
/**
* Creates a new digital media object.
* @param _creator address the creator of this digital media
* @param _totalSupply uint32 the total supply a creation could have
* @param _collectionId uint256 the collectionId that it belongs to
* @param _metadataPath string the path to the ipfs metadata
* @return uint the new digital media id
*/
function _createDigitalMedia(
address _creator, uint32 _totalSupply, uint256 _collectionId, string _metadataPath)
internal
returns (uint) {
require(_validateCollection(_collectionId, _creator), "Creator for collection not approved.");
uint256 newDigitalMediaId = currentDigitalMediaStore.createDigitalMedia(
_creator,
0,
_totalSupply,
_collectionId,
_metadataPath);
emit DigitalMediaCreateEvent(
newDigitalMediaId,
address(currentDigitalMediaStore),
_creator,
_totalSupply,
0,
_collectionId,
_metadataPath);
return newDigitalMediaId;
}
/**
* Burns a token for a given tokenId and caller.
* @param _tokenId the id of the token to burn.
* @param _caller the address of the caller.
*/
function _burnToken(uint256 _tokenId, address _caller) internal {
address owner = ownerOf(_tokenId);
require(_caller == owner ||
getApproved(_tokenId) == _caller ||
isApprovedForAll(owner, _caller),
"Failed token burn. Caller is not approved.");
_burn(owner, _tokenId);
delete tokenIdToDigitalMediaRelease[_tokenId];
emit DigitalMediaReleaseBurnEvent(_tokenId, owner);
}
/**
* Burns a digital media. Once this function succeeds, this digital media
* will no longer be able to mint any more tokens. Existing tokens need to be
* burned individually though.
* @param _digitalMediaId the id of the digital media to burn
* @param _caller the address of the caller.
*/
function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal {
DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId);
require(_checkApprovedCreator(_digitalMedia.creator, _caller) ||
isApprovedForAll(_digitalMedia.creator, _caller),
"Failed digital media burn. Caller not approved.");
uint32 increment = _digitalMedia.totalSupply - _digitalMedia.printIndex;
_incrementDigitalMediaPrintIndex(_digitalMedia, increment);
address _burnDigitalMediaStoreAddress = address(_getDigitalMediaStore(_digitalMedia.id));
emit DigitalMediaBurnEvent(
_digitalMediaId, _caller, _burnDigitalMediaStoreAddress);
}
/**
* Creates a new collection
* @param _creator address the creator of this collection
* @param _metadataPath string the path to the collection ipfs metadata
* @return uint the new collection id
*/
function _createCollection(
address _creator, string _metadataPath)
internal
returns (uint) {
uint256 newCollectionId = currentDigitalMediaStore.createCollection(
_creator,
_metadataPath);
emit DigitalMediaCollectionCreateEvent(
newCollectionId,
address(currentDigitalMediaStore),
_creator,
_metadataPath);
return newCollectionId;
}
/**
* Creates _count number of new digital media releases (i.e a token).
* Bumps up the print index by _count.
* @param _owner address the owner of the digital media object
* @param _digitalMediaId uint256 the digital media id
*/
function _createDigitalMediaReleases(
address _owner, uint256 _digitalMediaId, uint32 _count)
internal {
require(_count > 0, "Failed print edition. Creation count must be > 0.");
require(_count < 10000, "Cannot print more than 10K tokens at once");
DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId);
uint32 currentPrintIndex = _digitalMedia.printIndex;
require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved.");
require(isAllowedSingleCreator(_owner), "Creator must match single creator address.");
require(_count + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded.");
string memory tokenURI = HelperUtils.strConcat("ipfs://ipfs/", _digitalMedia.metadataPath);
for (uint32 i=0; i < _count; i++) {
uint32 newPrintEdition = currentPrintIndex + 1 + i;
DigitalMediaRelease memory _digitalMediaRelease = DigitalMediaRelease({
printEdition: newPrintEdition,
digitalMediaId: _digitalMediaId
});
uint256 newDigitalMediaReleaseId = _getNextTokenId();
tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId] = _digitalMediaRelease;
emit DigitalMediaReleaseCreateEvent(
newDigitalMediaReleaseId,
_owner,
newPrintEdition,
tokenURI,
_digitalMediaId
);
// This will assign ownership and also emit the Transfer event as per ERC721
_mint(_owner, newDigitalMediaReleaseId);
_setTokenURI(newDigitalMediaReleaseId, tokenURI);
tokenIdCounter = tokenIdCounter.add(1);
}
_incrementDigitalMediaPrintIndex(_digitalMedia, _count);
emit UpdateDigitalMediaPrintIndexEvent(_digitalMediaId, currentPrintIndex + _count);
}
/**
* Checks that a given caller is an approved creator and is allowed to mint or burn
* tokens. If the creator was changed it will check against the updated creator.
* @param _caller the calling address
* @return bool allowed or not
*/
function _checkApprovedCreator(address _creator, address _caller)
internal
view
returns (bool) {
address approvedCreator = approvedCreators[_creator];
if (approvedCreator != address(0)) {
return approvedCreator == _caller;
} else {
return _creator == _caller;
}
}
/**
* Validates the an address is allowed to create a digital media on a
* given collection. Collections are tied to addresses.
*/
function _validateCollection(uint256 _collectionId, address _address)
private
view
returns (bool) {
if (_collectionId == 0 ) {
return true;
}
DigitalMediaCollection memory collection = _getCollection(_collectionId);
return _checkApprovedCreator(collection.creator, _address);
}
/**
* Generates a new token id.
*/
function _getNextTokenId() private view returns (uint256) {
return tokenIdCounter.add(1);
}
/**
* Changes the creator that is approved to printing new tokens and creations.
* Either the _caller must be the _creator or the _caller must be the existing
* approvedCreator.
* @param _caller the address of the caller
* @param _creator the address of the current creator
* @param _newCreator the address of the new approved creator
*/
function _changeCreator(address _caller, address _creator, address _newCreator) internal {
address approvedCreator = approvedCreators[_creator];
require(_caller != address(0) && _creator != address(0), "Creator must be valid non 0x0 address.");
require(_caller == _creator || _caller == approvedCreator, "Unauthorized caller.");
if (approvedCreator == address(0)) {
approvedCreators[_caller] = _newCreator;
} else {
require(_caller == approvedCreator, "Unauthorized caller.");
approvedCreators[_creator] = _newCreator;
}
emit ChangedCreator(_creator, _newCreator);
}
/**
* Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
}
// File: REMIX_FILE_SYNC/OBOControl.sol
pragma solidity 0.4.25;
contract OBOControl is Pausable {
// List of approved on behalf of users.
mapping (address => bool) public approvedOBOs;
/**
* Add a new approved on behalf of user address.
*/
function addApprovedOBO(address _oboAddress) external onlyOwner {
approvedOBOs[_oboAddress] = true;
}
/**
* Removes an approved on bhealf of user address.
*/
function removeApprovedOBO(address _oboAddress) external onlyOwner {
delete approvedOBOs[_oboAddress];
}
/**
* @dev Modifier to make the obo calls only callable by approved addressess
*/
modifier isApprovedOBO() {
require(approvedOBOs[msg.sender] == true);
_;
}
}
// File: REMIX_FILE_SYNC/WithdrawFundsControl.sol
pragma solidity 0.4.25;
contract WithdrawFundsControl is Pausable {
// List of approved on withdraw addresses
mapping (address => uint256) public approvedWithdrawAddresses;
// Full day wait period before an approved withdraw address becomes active
uint256 constant internal withdrawApprovalWaitPeriod = 60 * 60 * 24;
event WithdrawAddressAdded(address withdrawAddress);
event WithdrawAddressRemoved(address widthdrawAddress);
/**
* Add a new approved on behalf of user address.
*/
function addApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
approvedWithdrawAddresses[_withdrawAddress] = now;
emit WithdrawAddressAdded(_withdrawAddress);
}
/**
* Removes an approved on bhealf of user address.
*/
function removeApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner {
delete approvedWithdrawAddresses[_withdrawAddress];
emit WithdrawAddressRemoved(_withdrawAddress);
}
/**
* Checks that a given withdraw address ia approved and is past it's required
* wait time.
*/
function isApprovedWithdrawAddress(address _withdrawAddress) internal view returns (bool) {
uint256 approvalTime = approvedWithdrawAddresses[_withdrawAddress];
require (approvalTime > 0);
return now - approvalTime > withdrawApprovalWaitPeriod;
}
}
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol
pragma solidity ^0.4.21;
contract ERC721Holder is ERC721Receiver {
function onERC721Received(address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
// File: REMIX_FILE_SYNC/DigitalMediaSaleBase.sol
pragma solidity 0.4.25;
/**
* Base class that manages the underlying functions of a Digital Media Sale,
* most importantly the escrow of digital tokens.
*
* Manages ensuring that only approved addresses interact with this contract.
*
*/
contract DigitalMediaSaleBase is ERC721Holder, Pausable, OBOControl, WithdrawFundsControl {
using SafeMath for uint256;
// Mapping of token contract address to bool indicated approval.
mapping (address => bool) public approvedTokenContracts;
/**
* Adds a new token contract address to be approved to be called.
*/
function addApprovedTokenContract(address _tokenContractAddress)
public onlyOwner {
approvedTokenContracts[_tokenContractAddress] = true;
}
/**
* Remove an approved token contract address from the list of approved addresses.
*/
function removeApprovedTokenContract(address _tokenContractAddress)
public onlyOwner {
delete approvedTokenContracts[_tokenContractAddress];
}
/**
* Checks that a particular token contract address is a valid address.
*/
function _isValidTokenContract(address _tokenContractAddress)
internal view returns (bool) {
return approvedTokenContracts[_tokenContractAddress];
}
/**
* Returns an ERC721 instance of a token contract address. Throws otherwise.
* Only valid and approved token contracts are allowed to be interacted with.
*/
function _getTokenContract(address _tokenContractAddress) internal view returns (ERC721Safe) {
require(_isValidTokenContract(_tokenContractAddress));
return ERC721Safe(_tokenContractAddress);
}
/**
* Checks with the ERC-721 token contract that the _claimant actually owns the token.
*/
function _owns(address _claimant, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return (tokenContract.ownerOf(_tokenId) == _claimant);
}
/**
* Checks with the ERC-721 token contract the owner of the a token
*/
function _ownerOf(uint256 _tokenId, address _tokenContractAddress) internal view returns (address) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return tokenContract.ownerOf(_tokenId);
}
/**
* Checks to ensure that the token owner has approved the escrow contract
*/
function _approvedForEscrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) {
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
return (tokenContract.isApprovedForAll(_seller, this) ||
tokenContract.getApproved(_tokenId) == address(this));
}
/**
* Escrows an ERC-721 token from the seller to this contract. Assumes that the escrow contract
* is already approved to make the transfer, otherwise it will fail.
*/
function _escrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal {
// it will throw if transfer fails
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
tokenContract.safeTransferFrom(_seller, this, _tokenId);
}
/**
* Transfer an ERC-721 token from escrow to the buyer. This is to be called after a purchase is
* completed.
*/
function _transfer(address _receiver, uint256 _tokenId, address _tokenContractAddress) internal {
// it will throw if transfer fails
ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress);
tokenContract.safeTransferFrom(this, _receiver, _tokenId);
}
/**
* Method to check whether this is an escrow contract
*/
function isEscrowContract() public pure returns(bool) {
return true;
}
/**
* Withdraws all the funds to a specified non-zero address
*/
function withdrawFunds(address _withdrawAddress) public onlyOwner {
require(isApprovedWithdrawAddress(_withdrawAddress));
_withdrawAddress.transfer(address(this).balance);
}
}
// File: REMIX_FILE_SYNC/DigitalMediaCore.sol
pragma solidity 0.4.25;
/**
* This is the main driver contract that is used to control and run the service. Funds
* are managed through this function, underlying contracts are also updated through
* this contract.
*
* This class also exposes a set of creation methods that are allowed to be created
* by an approved token creator, on behalf of a particular address. This is meant
* to simply the creation flow for MakersToken users that aren't familiar with
* the blockchain. The ERC721 tokens that are created are still fully compliant,
* although it is possible for a malicious token creator to mint unwanted tokens
* on behalf of a creator. Worst case, the creator can burn those tokens.
*/
contract DigitalMediaCore is DigitalMediaToken {
using SafeMath for uint32;
// List of approved token creators (on behalf of the owner)
mapping (address => bool) public approvedTokenCreators;
// Mapping from owner to operator accounts.
mapping (address => mapping (address => bool)) internal oboOperatorApprovals;
// Mapping of all disabled OBO operators.
mapping (address => bool) public disabledOboOperators;
// OboApproveAll Event
event OboApprovalForAll(
address _owner,
address _operator,
bool _approved);
// Fired when disbaling obo capability.
event OboDisabledForAll(address _operator);
constructor (
string _tokenName,
string _tokenSymbol,
uint256 _tokenIdStartingCounter,
address _dmsAddress,
address _crsAddress)
public DigitalMediaToken(
_tokenName,
_tokenSymbol,
_tokenIdStartingCounter) {
paused = true;
setDigitalMediaStoreAddress(_dmsAddress);
setCreatorRegistryStore(_crsAddress);
}
/**
* Retrieves a Digital Media object.
*/
function getDigitalMedia(uint256 _id)
external
view
returns (
uint256 id,
uint32 totalSupply,
uint32 printIndex,
uint256 collectionId,
address creator,
string metadataPath) {
DigitalMedia memory digitalMedia = _getDigitalMedia(_id);
require(digitalMedia.creator != address(0), "DigitalMedia not found.");
id = _id;
totalSupply = digitalMedia.totalSupply;
printIndex = digitalMedia.printIndex;
collectionId = digitalMedia.collectionId;
creator = digitalMedia.creator;
metadataPath = digitalMedia.metadataPath;
}
/**
* Retrieves a collection.
*/
function getCollection(uint256 _id)
external
view
returns (
uint256 id,
address creator,
string metadataPath) {
DigitalMediaCollection memory digitalMediaCollection = _getCollection(_id);
require(digitalMediaCollection.creator != address(0), "Collection not found.");
id = _id;
creator = digitalMediaCollection.creator;
metadataPath = digitalMediaCollection.metadataPath;
}
/**
* Retrieves a Digital Media Release (i.e a token)
*/
function getDigitalMediaRelease(uint256 _id)
external
view
returns (
uint256 id,
uint32 printEdition,
uint256 digitalMediaId) {
require(exists(_id));
DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id];
id = _id;
printEdition = digitalMediaRelease.printEdition;
digitalMediaId = digitalMediaRelease.digitalMediaId;
}
/**
* Creates a new collection.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createCollection(string _metadataPath)
external
whenNotPaused {
_createCollection(msg.sender, _metadataPath);
}
/**
* Creates a new digital media object.
*/
function createDigitalMedia(uint32 _totalSupply, uint256 _collectionId, string _metadataPath)
external
whenNotPaused {
_createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath);
}
/**
* Creates a new digital media object and mints it's first digital media release token.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleases(
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath,
uint32 _numReleases)
external
whenNotPaused {
uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath);
_createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases);
}
/**
* Creates a new collection, a new digital media object within it and mints a new
* digital media release token.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaAndReleasesInNewCollection(
uint32 _totalSupply,
string _digitalMediaMetadataPath,
string _collectionMetadataPath,
uint32 _numReleases)
external
whenNotPaused {
uint256 collectionId = _createCollection(msg.sender, _collectionMetadataPath);
uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, collectionId, _digitalMediaMetadataPath);
_createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases);
}
/**
* Creates a new digital media release (token) for a given digital media id.
*
* No creations of any kind are allowed when the contract is paused.
*/
function createDigitalMediaReleases(uint256 _digitalMediaId, uint32 _numReleases)
external
whenNotPaused {
_createDigitalMediaReleases(msg.sender, _digitalMediaId, _numReleases);
}
/**
* Deletes a token / digital media release. Doesn't modify the current print index
* and total to be printed. Although dangerous, the owner of a token should always
* be able to burn a token they own.
*
* Only the owner of the token or accounts approved by the owner can burn this token.
*/
function burnToken(uint256 _tokenId) external {
_burnToken(_tokenId, msg.sender);
}
/* Support ERC721 burn method */
function burn(uint256 tokenId) public {
_burnToken(tokenId, msg.sender);
}
/**
* Ends the production run of a digital media. Afterwards no more tokens
* will be allowed to be printed for this digital media. Used when a creator
* makes a mistake and wishes to burn and recreate their digital media.
*
* When a contract is paused we do not allow new tokens to be created,
* so stopping the production of a token doesn't have much purpose.
*/
function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused {
_burnDigitalMedia(_digitalMediaId, msg.sender);
}
/**
* Resets the approval rights for a given tokenId.
*/
function resetApproval(uint256 _tokenId) external {
clearApproval(msg.sender, _tokenId);
}
/**
* Changes the creator for the current sender, in the event we
* need to be able to mint new tokens from an existing digital media
* print production. When changing creator, the old creator will
* no longer be able to mint tokens.
*
* A creator may need to be changed:
* 1. If we want to allow a creator to take control over their token minting (i.e go decentralized)
* 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function
* when the contract is paused.
* @param _creator the creator address
* @param _newCreator the new creator address
*/
function changeCreator(address _creator, address _newCreator) external {
_changeCreator(msg.sender, _creator, _newCreator);
}
/**********************************************************************/
/**Calls that are allowed to be called by approved creator addresses **/
/**********************************************************************/
/**
* Add a new approved token creator.
*
* Only the owner of this contract can update approved Obo accounts.
*/
function addApprovedTokenCreator(address _creatorAddress) external onlyOwner {
require(disabledOboOperators[_creatorAddress] != true, "Address disabled.");
approvedTokenCreators[_creatorAddress] = true;
}
/**
* Removes an approved token creator.
*
* Only the owner of this contract can update approved Obo accounts.
*/
function removeApprovedTokenCreator(address _creatorAddress) external onlyOwner {
delete approvedTokenCreators[_creatorAddress];
}
/**
* @dev Modifier to make the approved creation calls only callable by approved token creators
*/
modifier isApprovedCreator() {
require(
(approvedTokenCreators[msg.sender] == true &&
disabledOboOperators[msg.sender] != true),
"Unapproved OBO address.");
_;
}
/**
* Only the owner address can set a special obo approval list.
* When issuing OBO management accounts, we should give approvals through
* this method only so that we can very easily reset it's approval in
* the event of a disaster scenario.
*
* Only the owner themselves is allowed to give OboApproveAll access.
*/
function setOboApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender, "Approval address is same as approver.");
require(approvedTokenCreators[_to], "Unrecognized OBO address.");
require(disabledOboOperators[_to] != true, "Approval address is disabled.");
oboOperatorApprovals[msg.sender][_to] = _approved;
emit OboApprovalForAll(msg.sender, _to, _approved);
}
/**
* Only called in a disaster scenario if the account has been compromised.
* There's no turning back from this and the oboAddress will no longer be
* able to be given approval rights or perform obo functions.
*
* Only the owner of this contract is allowed to disable an Obo address.
*
*/
function disableOboAddress(address _oboAddress) public onlyOwner {
require(approvedTokenCreators[_oboAddress], "Unrecognized OBO address.");
disabledOboOperators[_oboAddress] = true;
delete approvedTokenCreators[_oboAddress];
emit OboDisabledForAll(_oboAddress);
}
/**
* Override the isApprovalForAll to check for a special oboApproval list. Reason for this
* is that we can can easily remove obo operators if they every become compromised.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
if (disabledOboOperators[_operator] == true) {
return false;
} else if (isOperatorApprovedForCustodialAccount(_operator, _owner) == true) {
return true;
} else if (oboOperatorApprovals[_owner][_operator]) {
return true;
} else {
return super.isApprovedForAll(_owner, _operator);
}
}
/**
* Creates a new digital media object and mints it's digital media release tokens.
* Called on behalf of the _owner. Pass count to mint `n` number of tokens.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleases(
address _owner,
uint32 _totalSupply,
uint256 _collectionId,
string _metadataPath,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, _collectionId, _metadataPath);
_createDigitalMediaReleases(_owner, digitalMediaId, _numReleases);
}
/**
* Creates a new collection, a new digital media object within it and mints a new
* digital media release token.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaAndReleasesInNewCollection(
address _owner,
uint32 _totalSupply,
string _digitalMediaMetadataPath,
string _collectionMetadataPath,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
uint256 collectionId = _createCollection(_owner, _collectionMetadataPath);
uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, collectionId, _digitalMediaMetadataPath);
_createDigitalMediaReleases(_owner, digitalMediaId, _numReleases);
}
/**
* Creates multiple digital media releases (tokens) for a given digital media id.
* Called on behalf of the _owner.
*
* Only approved creators are allowed to create Obo.
*
* No creations of any kind are allowed when the contract is paused.
*/
function oboCreateDigitalMediaReleases(
address _owner,
uint256 _digitalMediaId,
uint32 _numReleases)
external
whenNotPaused
isApprovedCreator {
_createDigitalMediaReleases(_owner, _digitalMediaId, _numReleases);
}
} | Get the word stored at memory address 'addr' as a 'uint'. | function toUint(uint addr) internal pure returns (uint n) {
assembly {
n := mload(addr)
}
}
| 890,363 | [
1,
967,
326,
2076,
4041,
622,
3778,
1758,
296,
4793,
11,
487,
279,
296,
11890,
10332,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
358,
5487,
12,
11890,
3091,
13,
2713,
16618,
1135,
261,
11890,
290,
13,
288,
203,
3639,
19931,
288,
203,
5411,
290,
519,
312,
945,
12,
4793,
13,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
contract FaucetContract is Ownable, Pausable {
using SafeMath for uint256;
uint256 public retrievalAmount = 1*10**17;
uint256 public retrievalLimit = 1*10**18;
event Received(address sender, uint256 amount);
event Funded(address sender, uint256 amount);
event ChangedRetrievalParameters(uint256 newRetrievalAmount, uint256 newNumberOfTimes);
// Pause the contract
function pause() public onlyOwner {
_pause();
}
// Unpause the contract
function unpause() public onlyOwner {
_unpause();
}
mapping (address => uint256) public amountRetrieved;
// Receive funds
receive() external payable {
emit Received(msg.sender, msg.value);
}
// Change the retrieval parameters
function changeRetrievalAmounts(uint256 newRetrievalAmount, uint256 newNumberOfTimes) public onlyOwner() returns(bool) {
require(newRetrievalAmount > 0, "Retrieval amount must be positive");
require(newNumberOfTimes > 0, "Number of times must be positive");
retrievalAmount = newRetrievalAmount;
retrievalLimit = retrievalAmount.mul(newNumberOfTimes);
emit ChangedRetrievalParameters(newRetrievalAmount, newNumberOfTimes);
return true;
}
// Send money to message sender
function sendFunds() public whenNotPaused() {
address payable retriever = payable(msg.sender);
amountRetrieved[retriever] = amountRetrieved[retriever].add(retrievalAmount);
require(amountRetrieved[retriever] <= retrievalLimit, "You have reached the retrieval limit");
require(address(this).balance >= retrievalAmount, "Reserves insufficient");
retriever.transfer(retrievalAmount);
emit Funded(retriever, retrievalAmount);
}
// Send money to specific address
function sendToFunds(address payable retriever) public whenNotPaused() {
amountRetrieved[retriever] = amountRetrieved[retriever].add(retrievalAmount);
require(amountRetrieved[retriever] <= retrievalLimit, "You have reached the retrieval limit");
require(address(this).balance >= retrievalAmount, "Reserves insufficient");
retriever.transfer(retrievalAmount);
emit Funded(retriever, retrievalAmount);
}
// Destroy the faucet
function closeFaucet(address payable payoutAddress) public onlyOwner() {
payoutAddress.transfer(address(this).balance);
selfdestruct(payoutAddress);
}
}
| Send money to specific address | function sendToFunds(address payable retriever) public whenNotPaused() {
amountRetrieved[retriever] = amountRetrieved[retriever].add(retrievalAmount);
require(amountRetrieved[retriever] <= retrievalLimit, "You have reached the retrieval limit");
require(address(this).balance >= retrievalAmount, "Reserves insufficient");
retriever.transfer(retrievalAmount);
emit Funded(retriever, retrievalAmount);
}
| 1,008,940 | [
1,
3826,
15601,
358,
2923,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
29091,
42,
19156,
12,
2867,
8843,
429,
3227,
502,
13,
1071,
1347,
1248,
28590,
1435,
288,
203,
3639,
3844,
3848,
2155,
63,
14580,
502,
65,
273,
3844,
3848,
2155,
63,
14580,
502,
8009,
1289,
12,
14580,
1125,
6275,
1769,
203,
3639,
2583,
12,
8949,
3848,
2155,
63,
14580,
502,
65,
1648,
22613,
3039,
16,
315,
6225,
1240,
8675,
326,
22613,
1800,
8863,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
22613,
6275,
16,
315,
607,
264,
3324,
2763,
11339,
8863,
203,
3639,
3227,
502,
18,
13866,
12,
14580,
1125,
6275,
1769,
203,
3639,
3626,
478,
12254,
12,
14580,
502,
16,
22613,
6275,
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
] |
/*
https://powerpool.finance/
wrrrw r wrr
ppwr rrr wppr0 prwwwrp prwwwrp wr0
rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0
rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0
r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0
prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0
wrr ww0rrrr
*/
// SPDX-License-Identifier: MIT
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
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/[email protected]
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/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @powerpool/power-oracle/contracts/interfaces/[email protected]
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
interface IPowerPoke {
/*** CLIENT'S CONTRACT INTERFACE ***/
function authorizeReporter(uint256 userId_, address pokerKey_) external view;
function authorizeNonReporter(uint256 userId_, address pokerKey_) external view;
function authorizeNonReporterWithDeposit(
uint256 userId_,
address pokerKey_,
uint256 overrideMinDeposit_
) external view;
function authorizePoker(uint256 userId_, address pokerKey_) external view;
function authorizePokerWithDeposit(
uint256 userId_,
address pokerKey_,
uint256 overrideMinStake_
) external view;
function slashReporter(uint256 slasherId_, uint256 times_) external;
function reward(
uint256 userId_,
uint256 gasUsed_,
uint256 compensationPlan_,
bytes calldata pokeOptions_
) external;
/*** CLIENT OWNER INTERFACE ***/
function transferClientOwnership(address client_, address to_) external;
function addCredit(address client_, uint256 amount_) external;
function withdrawCredit(
address client_,
address to_,
uint256 amount_
) external;
function setReportIntervals(
address client_,
uint256 minReportInterval_,
uint256 maxReportInterval_
) external;
function setSlasherHeartbeat(address client_, uint256 slasherHeartbeat_) external;
function setGasPriceLimit(address client_, uint256 gasPriceLimit_) external;
function setFixedCompensations(
address client_,
uint256 eth_,
uint256 cvp_
) external;
function setBonusPlan(
address client_,
uint256 planId_,
bool active_,
uint64 bonusNominator_,
uint64 bonusDenominator_,
uint64 perGas_
) external;
function setMinimalDeposit(address client_, uint256 defaultMinDeposit_) external;
/*** POKER INTERFACE ***/
function withdrawRewards(uint256 userId_, address to_) external;
function setPokerKeyRewardWithdrawAllowance(uint256 userId_, bool allow_) external;
/*** OWNER INTERFACE ***/
function addClient(
address client_,
address owner_,
bool canSlash_,
uint256 gasPriceLimit_,
uint256 minReportInterval_,
uint256 maxReportInterval_
) external;
function setClientActiveFlag(address client_, bool active_) external;
function setCanSlashFlag(address client_, bool canSlash) external;
function setOracle(address oracle_) external;
function pause() external;
function unpause() external;
/*** GETTERS ***/
function creditOf(address client_) external view returns (uint256);
function ownerOf(address client_) external view returns (address);
function getMinMaxReportIntervals(address client_) external view returns (uint256 min, uint256 max);
function getSlasherHeartbeat(address client_) external view returns (uint256);
function getGasPriceLimit(address client_) external view returns (uint256);
function getPokerBonus(
address client_,
uint256 bonusPlanId_,
uint256 gasUsed_,
uint256 userDeposit_
) external view returns (uint256);
function getGasPriceFor(address client_) external view returns (uint256);
}
// File contracts/interfaces/IUniswapV2Router01.sol
pragma solidity 0.6.12;
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);
}
// File contracts/interfaces/IUniswapV2Router02.sol
pragma solidity 0.6.12;
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;
}
// File contracts/interfaces/TokenInterface.sol
pragma solidity 0.6.12;
interface TokenInterface is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// File contracts/interfaces/BMathInterface.sol
pragma solidity 0.6.12;
interface BMathInterface {
function calcInGivenOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
}
// File contracts/interfaces/BPoolInterface.sol
pragma solidity 0.6.12;
interface BPoolInterface is IERC20, BMathInterface {
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function swapExactAmountIn(
address,
uint256,
address,
uint256,
uint256
) external returns (uint256, uint256);
function swapExactAmountOut(
address,
uint256,
address,
uint256,
uint256
) external returns (uint256, uint256);
function joinswapExternAmountIn(
address,
uint256,
uint256
) external returns (uint256);
function joinswapPoolAmountOut(
address,
uint256,
uint256
) external returns (uint256);
function exitswapPoolAmountIn(
address,
uint256,
uint256
) external returns (uint256);
function exitswapExternAmountOut(
address,
uint256,
uint256
) external returns (uint256);
function getDenormalizedWeight(address) external view returns (uint256);
function getBalance(address) external view returns (uint256);
function getSwapFee() external view returns (uint256);
function getTotalDenormalizedWeight() external view returns (uint256);
function getCommunityFee()
external
view
returns (
uint256,
uint256,
uint256,
address
);
function calcAmountWithCommunityFee(
uint256,
uint256,
address
) external view returns (uint256, uint256);
function getRestrictions() external view returns (address);
function isPublicSwap() external view returns (bool);
function isFinalized() external view returns (bool);
function isBound(address t) external view returns (bool);
function getCurrentTokens() external view returns (address[] memory tokens);
function getFinalTokens() external view returns (address[] memory tokens);
function setSwapFee(uint256) external;
function setCommunityFeeAndReceiver(
uint256,
uint256,
uint256,
address
) external;
function setController(address) external;
function setPublicSwap(bool) external;
function finalize() external;
function bind(
address,
uint256,
uint256
) external;
function rebind(
address,
uint256,
uint256
) external;
function unbind(address) external;
function gulp(address) external;
function callVoting(
address voting,
bytes4 signature,
bytes calldata args,
uint256 value
) external;
function getMinWeight() external view returns (uint256);
function getMaxBoundTokens() external view returns (uint256);
}
// File contracts/interfaces/ICVPMakerStrategy.sol
pragma solidity 0.6.12;
interface ICVPMakerStrategy {
function getExecuteDataByAmountOut(
address poolTokenIn_,
uint256 tokenOutAmount_,
bytes memory config_
)
external
view
returns (
uint256 poolTokenInAmount,
address executeUniLikeFrom,
bytes memory executeData,
address executeContract
);
function getExecuteDataByAmountIn(
address poolTokenIn_,
uint256 tokenInAmount_,
bytes memory config_
)
external
view
returns (
address executeUniLikeFrom,
bytes memory executeData,
address executeContract
);
function estimateIn(
address tokenIn_,
uint256 tokenOutAmount_,
bytes memory
) external view returns (uint256 amountIn);
function estimateOut(
address poolTokenIn_,
uint256 tokenInAmount_,
bytes memory
) external view returns (uint256);
function getTokenOut() external view returns (address);
}
// File contracts/balancer-core/BConst.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.6.12;
contract BConst {
uint public constant BONE = 10**18;
// Minimum number of tokens in the pool
uint public constant MIN_BOUND_TOKENS = 2;
// Maximum number of tokens in the pool
uint public constant MAX_BOUND_TOKENS = 9;
// Minimum swap fee
uint public constant MIN_FEE = BONE / 10**6;
// Maximum swap fee
uint public constant MAX_FEE = BONE / 10;
// Minimum weight for token
uint public constant MIN_WEIGHT = 1000000000;
// Maximum weight for token
uint public constant MAX_WEIGHT = BONE * 50;
// Maximum total weight
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
// Minimum balance for a token
uint public constant MIN_BALANCE = BONE / 10**12;
// Initial pool tokens supply
uint public constant INIT_POOL_SUPPLY = BONE * 100;
uint public constant MIN_BPOW_BASE = 1 wei;
uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint public constant BPOW_PRECISION = BONE / 10**10;
// Maximum input tokens balance ratio for swaps.
uint public constant MAX_IN_RATIO = BONE / 2;
// Maximum output tokens balance ratio for swaps.
uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
// File contracts/balancer-core/BNum.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.6.12;
contract BNum is BConst {
function btoi(uint a)
internal pure
returns (uint)
{
return a / BONE;
}
function bfloor(uint a)
internal pure
returns (uint)
{
return btoi(a) * BONE;
}
function badd(uint a, uint b)
internal pure
returns (uint)
{
uint c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint a, uint b)
internal pure
returns (uint)
{
(uint c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint a, uint b)
internal pure
returns (uint, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint a, uint b)
internal pure
returns (uint)
{
uint c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint c2 = c1 / BONE;
return c2;
}
function bdiv(uint a, uint b)
internal pure
returns (uint)
{
require(b != 0, "ERR_DIV_ZERO");
uint c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint c2 = c1 / b;
return c2;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "ERR_DIV_ZERO");
return a / b;
}
// DSMath.wpow
function bpowi(uint a, uint n)
internal pure
returns (uint)
{
uint z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint base, uint exp)
internal pure
returns (uint)
{
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint whole = bfloor(exp);
uint remain = bsub(exp, whole);
uint wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(uint base, uint exp, uint precision)
internal pure
returns (uint)
{
// term 0:
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BONE);
uint term = BONE;
uint sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint i = 1; term >= precision; i++) {
uint bigK = i * BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
}
// File contracts/balancer-core/BMath.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.6.12;
contract BMath is BConst, BNum, BMathInterface {
/**********************************************************************************************
// calcSpotPrice //
// sP = spotPrice //
// bI = tokenBalanceIn ( bI / wI ) 1 //
// bO = tokenBalanceOut sP = ----------- * ---------- //
// wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcSpotPrice(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint swapFee
)
public pure virtual
returns (uint spotPrice)
{
uint numer = bdiv(tokenBalanceIn, tokenWeightIn);
uint denom = bdiv(tokenBalanceOut, tokenWeightOut);
uint ratio = bdiv(numer, denom);
uint scale = bdiv(BONE, bsub(BONE, swapFee));
return (spotPrice = bmul(ratio, scale));
}
/**********************************************************************************************
// calcOutGivenIn //
// aO = tokenAmountOut //
// bO = tokenBalanceOut //
// bI = tokenBalanceIn / / bI \ (wI / wO) \ //
// aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcOutGivenIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountIn,
uint swapFee
)
public pure virtual
returns (uint tokenAmountOut)
{
uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut);
uint adjustedIn = bsub(BONE, swapFee);
adjustedIn = bmul(tokenAmountIn, adjustedIn);
uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));
uint foo = bpow(y, weightRatio);
uint bar = bsub(BONE, foo);
tokenAmountOut = bmul(tokenBalanceOut, bar);
return tokenAmountOut;
}
/**********************************************************************************************
// calcInGivenOut //
// aI = tokenAmountIn //
// bO = tokenBalanceOut / / bO \ (wO / wI) \ //
// bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //
// aO = tokenAmountOut aI = \ \ ( bO - aO ) / / //
// wI = tokenWeightIn -------------------------------------------- //
// wO = tokenWeightOut ( 1 - sF ) //
// sF = swapFee //
**********************************************************************************************/
function calcInGivenOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountOut,
uint swapFee
)
public pure virtual override
returns (uint tokenAmountIn)
{
uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn);
uint diff = bsub(tokenBalanceOut, tokenAmountOut);
uint y = bdiv(tokenBalanceOut, diff);
uint foo = bpow(y, weightRatio);
foo = bsub(foo, BONE);
tokenAmountIn = bsub(BONE, swapFee);
tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn);
return tokenAmountIn;
}
/**********************************************************************************************
// calcPoolOutGivenSingleIn //
// pAo = poolAmountOut / \ //
// tAi = tokenAmountIn /// / // wI \ \\ \ wI \ //
// wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ //
// tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS //
// tBi = tokenBalanceIn \\ ------------------------------------- / / //
// pS = poolSupply \\ tBi / / //
// sF = swapFee \ / //
**********************************************************************************************/
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee
)
public pure virtual
returns (uint poolAmountOut)
{
// Charge the trading fee for the proportion of tokenAi
/// which is implicitly traded to the other pool tokens.
// That proportion is (1- weightTokenIn)
// tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz));
uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);
uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);
// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
uint poolRatio = bpow(tokenInRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
poolAmountOut = bsub(newPoolSupply, poolSupply);
return poolAmountOut;
}
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply || --------- | ^ | --------- || * bI - bI //
// pAo = poolAmountOut \\ pS / \(wI / tW)// //
// bI = balanceIn tAi = -------------------------------------------- //
// wI = weightIn / wI \ //
// tW = totalWeight | 1 - ---- | * sF //
// sF = swapFee \ tW / //
**********************************************************************************************/
function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
)
public pure virtual override
returns (uint tokenAmountIn)
{
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint newPoolSupply = badd(poolSupply, poolAmountOut);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
//uint newBalTi = poolRatio^(1/weightTi) * balTi;
uint boo = bdiv(BONE, normalizedWeight);
uint tokenInRatio = bpow(poolRatio, boo);
uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);
uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);
// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
// ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```
//uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;
uint zar = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar));
return tokenAmountIn;
}
/**********************************************************************************************
// calcSingleOutGivenPoolIn //
// tAo = tokenAmountOut / / \\ //
// bO = tokenBalanceOut / // pS - pAi \ / 1 \ \\ //
// pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //
// ps = poolSupply \ \\ pS / \(wO / tW)/ // //
// wI = tokenWeightIn tAo = \ \ // //
// tW = totalWeight / / wO \ \ //
// sF = swapFee * | 1 - | 1 - ---- | * sF | //
// eF = exitFee \ \ tW / / //
**********************************************************************************************/
function calcSingleOutGivenPoolIn(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint poolAmountIn,
uint swapFee
)
public pure virtual
returns (uint tokenAmountOut)
{
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
uint newPoolSupply = bsub(poolSupply, poolAmountIn);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
// newBalTo = poolRatio^(1/weightTo) * balTo;
uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight));
uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);
uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
// charge swap fee on the output token side
//uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)
uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz));
return tokenAmountOut;
}
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ //
// tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | //
// ps = poolSupply \\ -----------------------------------/ / //
// wO = tokenWeightOut pAi = \\ bO / / //
// tW = totalWeight //
// sF = swapFee //
**********************************************************************************************/
function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee
)
public pure virtual
returns (uint poolAmountIn)
{
// charge swap fee on the output token side
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
//uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ;
uint zoo = bsub(BONE, normalizedWeight);
uint zar = bmul(zoo, swapFee);
uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar));
uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee);
uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);
//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
uint poolRatio = bpow(tokenOutRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
uint poolAmountIn = bsub(poolSupply, newPoolSupply);
return poolAmountIn;
}
}
// File contracts/interfaces/WrappedPiErc20Interface.sol
pragma solidity 0.6.12;
interface WrappedPiErc20Interface is IERC20 {
function deposit(uint256 _amount) external payable returns (uint256);
function withdraw(uint256 _amount) external payable returns (uint256);
function changeRouter(address _newRouter) external;
function setEthFee(uint256 _newEthFee) external;
function withdrawEthFee(address payable receiver) external;
function approveUnderlying(address _to, uint256 _amount) external;
function getPiEquivalentForUnderlying(uint256 _underlyingAmount) external view returns (uint256);
function getUnderlyingEquivalentForPi(uint256 _piAmount) external view returns (uint256);
function balanceOfUnderlying(address account) external view returns (uint256);
function callExternal(
address voting,
bytes4 signature,
bytes calldata args,
uint256 value
) external;
struct ExternalCallData {
address destination;
bytes4 signature;
bytes args;
uint256 value;
}
function callExternalMultiple(ExternalCallData[] calldata calls) external;
function getUnderlyingBalance() external view returns (uint256);
}
// File contracts/interfaces/PowerIndexWrapperInterface.sol
pragma solidity 0.6.12;
interface PowerIndexWrapperInterface {
function getFinalTokens() external view returns (address[] memory tokens);
function getCurrentTokens() external view returns (address[] memory tokens);
function getBalance(address _token) external view returns (uint256);
function setPiTokenForUnderlyingsMultiple(address[] calldata _underlyingTokens, address[] calldata _piTokens)
external;
function setPiTokenForUnderlying(address _underlyingTokens, address _piToken) external;
function updatePiTokenEthFees(address[] calldata _underlyingTokens) external;
function withdrawOddEthFee(address payable _recipient) external;
function calcEthFeeForTokens(address[] memory tokens) external view returns (uint256 feeSum);
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external payable;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external payable;
function swapExactAmountIn(
address,
uint256,
address,
uint256,
uint256
) external payable returns (uint256, uint256);
function swapExactAmountOut(
address,
uint256,
address,
uint256,
uint256
) external payable returns (uint256, uint256);
function joinswapExternAmountIn(
address,
uint256,
uint256
) external payable returns (uint256);
function joinswapPoolAmountOut(
address,
uint256,
uint256
) external payable returns (uint256);
function exitswapPoolAmountIn(
address,
uint256,
uint256
) external payable returns (uint256);
function exitswapExternAmountOut(
address,
uint256,
uint256
) external payable returns (uint256);
}
// File contracts/lib/ControllerOwnable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an controller) that can be granted exclusive access to
* specific functions.
*
* By default, the controller 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 ControllerOwnable {
address private _controller;
event SetController(address indexed previousController, address indexed newController);
/**
* @dev Initializes the contract setting the deployer as the initial controller.
*/
constructor () internal {
_controller = msg.sender;
emit SetController(address(0), _controller);
}
/**
* @dev Returns the address of the current controller.
*/
function getController() public view returns (address) {
return _controller;
}
/**
* @dev Throws if called by any account other than the controller.
*/
modifier onlyController() {
require(_controller == msg.sender, "NOT_CONTROLLER");
_;
}
/**
* @dev Give the controller permissions to a new account (`newController`).
* Can only be called by the current controller.
*/
function setController(address newController) public virtual onlyController {
require(newController != address(0), "ControllerOwnable: new controller is the zero address");
emit SetController(_controller, newController);
_controller = newController;
}
}
// File contracts/powerindex-router/PowerIndexWrapper.sol
pragma solidity 0.6.12;
contract PowerIndexWrapper is ControllerOwnable, BMath, PowerIndexWrapperInterface {
using SafeMath for uint256;
event SetPiTokenForUnderlying(address indexed underlyingToken, address indexed piToken);
event UpdatePiTokenEthFee(address indexed piToken, uint256 ethFee);
BPoolInterface public immutable bpool;
mapping(address => address) public piTokenByUnderlying;
mapping(address => address) public underlyingByPiToken;
mapping(address => uint256) public ethFeeByPiToken;
constructor(address _bpool) public ControllerOwnable() {
bpool = BPoolInterface(_bpool);
BPoolInterface(_bpool).approve(_bpool, uint256(-1));
address[] memory tokens = BPoolInterface(_bpool).getCurrentTokens();
uint256 len = tokens.length;
for (uint256 i = 0; i < len; i++) {
IERC20(tokens[i]).approve(_bpool, uint256(-1));
}
}
function withdrawOddEthFee(address payable _recipient) external override onlyController {
_recipient.transfer(address(this).balance);
}
function setPiTokenForUnderlyingsMultiple(address[] calldata _underlyingTokens, address[] calldata _piTokens)
external
override
onlyController
{
uint256 len = _underlyingTokens.length;
require(len == _piTokens.length, "LENGTH_DONT_MATCH");
for (uint256 i = 0; i < len; i++) {
_setPiTokenForUnderlying(_underlyingTokens[i], _piTokens[i]);
}
}
function setPiTokenForUnderlying(address _underlyingToken, address _piToken) external override onlyController {
_setPiTokenForUnderlying(_underlyingToken, _piToken);
}
function updatePiTokenEthFees(address[] calldata _underlyingTokens) external override {
uint256 len = _underlyingTokens.length;
for (uint256 i = 0; i < len; i++) {
_updatePiTokenEthFee(piTokenByUnderlying[_underlyingTokens[i]]);
}
}
function swapExactAmountOut(
address tokenIn,
uint256 maxAmountIn,
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPrice
) external payable override returns (uint256 tokenAmountIn, uint256 spotPriceAfter) {
(address actualTokenIn, uint256 actualMaxAmountIn) = _getActualTokenAndAmount(tokenIn, maxAmountIn);
(address actualTokenOut, uint256 actualTokenAmountOut) = _getActualTokenAndAmount(tokenOut, tokenAmountOut);
uint256 actualMaxPrice =
getActualMaxPrice(maxAmountIn, actualMaxAmountIn, tokenAmountOut, actualTokenAmountOut, maxPrice);
uint256 amountInRate = actualMaxAmountIn.mul(uint256(1 ether)).div(maxAmountIn);
uint256 prevMaxAmount = actualMaxAmountIn;
actualMaxAmountIn = calcInGivenOut(
bpool.getBalance(actualTokenIn),
bpool.getDenormalizedWeight(actualTokenIn),
bpool.getBalance(actualTokenOut),
bpool.getDenormalizedWeight(actualTokenOut),
actualTokenAmountOut,
bpool.getSwapFee()
);
if (prevMaxAmount > actualMaxAmountIn) {
maxAmountIn = actualMaxAmountIn.mul(uint256(1 ether)).div(amountInRate);
} else {
actualMaxAmountIn = prevMaxAmount;
}
_processUnderlyingTokenIn(tokenIn, maxAmountIn);
(tokenAmountIn, spotPriceAfter) = bpool.swapExactAmountOut(
actualTokenIn,
actualMaxAmountIn,
actualTokenOut,
actualTokenAmountOut,
actualMaxPrice
);
_processUnderlyingOrPiTokenOutBalance(tokenOut);
return (tokenAmountIn, spotPriceAfter);
}
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
) external payable override returns (uint256 tokenAmountOut, uint256 spotPriceAfter) {
(address actualTokenIn, uint256 actualAmountIn) = _processUnderlyingTokenIn(tokenIn, tokenAmountIn);
(address actualTokenOut, uint256 actualMinAmountOut) = _getActualTokenAndAmount(tokenOut, minAmountOut);
uint256 actualMaxPrice =
getActualMaxPrice(tokenAmountIn, actualAmountIn, minAmountOut, actualMinAmountOut, maxPrice);
(tokenAmountOut, spotPriceAfter) = bpool.swapExactAmountIn(
actualTokenIn,
actualAmountIn,
actualTokenOut,
actualMinAmountOut,
actualMaxPrice
);
_processUnderlyingOrPiTokenOutBalance(tokenOut);
return (tokenAmountOut, spotPriceAfter);
}
function joinPool(uint256 poolAmountOut, uint256[] memory maxAmountsIn) external payable override {
address[] memory tokens = getCurrentTokens();
uint256 len = tokens.length;
require(maxAmountsIn.length == len, "ERR_LENGTH_MISMATCH");
uint256 ratio = poolAmountOut.mul(1 ether).div(bpool.totalSupply()).add(100);
for (uint256 i = 0; i < len; i++) {
(address actualToken, uint256 actualMaxAmountIn) = _getActualTokenAndAmount(tokens[i], maxAmountsIn[i]);
uint256 amountInRate = actualMaxAmountIn.mul(uint256(1 ether)).div(maxAmountsIn[i]);
uint256 prevMaxAmount = actualMaxAmountIn;
actualMaxAmountIn = ratio.mul(bpool.getBalance(actualToken)).div(1 ether);
if (prevMaxAmount > actualMaxAmountIn) {
maxAmountsIn[i] = actualMaxAmountIn.mul(uint256(1 ether)).div(amountInRate);
} else {
actualMaxAmountIn = prevMaxAmount;
}
_processUnderlyingTokenIn(tokens[i], maxAmountsIn[i]);
maxAmountsIn[i] = actualMaxAmountIn;
}
bpool.joinPool(poolAmountOut, maxAmountsIn);
require(bpool.transfer(msg.sender, bpool.balanceOf(address(this))), "ERR_TRANSFER_FAILED");
}
function exitPool(uint256 poolAmountIn, uint256[] memory minAmountsOut) external payable override {
address[] memory tokens = getCurrentTokens();
uint256 len = tokens.length;
require(minAmountsOut.length == len, "ERR_LENGTH_MISMATCH");
bpool.transferFrom(msg.sender, address(this), poolAmountIn);
for (uint256 i = 0; i < len; i++) {
(, minAmountsOut[i]) = _getActualTokenAndAmount(tokens[i], minAmountsOut[i]);
}
bpool.exitPool(poolAmountIn, minAmountsOut);
for (uint256 i = 0; i < len; i++) {
_processUnderlyingOrPiTokenOutBalance(tokens[i]);
}
}
function joinswapExternAmountIn(
address tokenIn,
uint256 tokenAmountIn,
uint256 minPoolAmountOut
) external payable override returns (uint256 poolAmountOut) {
(address actualTokenIn, uint256 actualAmountIn) = _processUnderlyingTokenIn(tokenIn, tokenAmountIn);
poolAmountOut = bpool.joinswapExternAmountIn(actualTokenIn, actualAmountIn, minPoolAmountOut);
require(bpool.transfer(msg.sender, bpool.balanceOf(address(this))), "ERR_TRANSFER_FAILED");
return poolAmountOut;
}
function joinswapPoolAmountOut(
address tokenIn,
uint256 poolAmountOut,
uint256 maxAmountIn
) external payable override returns (uint256 tokenAmountIn) {
(address actualTokenIn, uint256 actualMaxAmountIn) = _getActualTokenAndAmount(tokenIn, maxAmountIn);
uint256 amountInRate = actualMaxAmountIn.mul(uint256(1 ether)).div(maxAmountIn);
uint256 prevMaxAmount = maxAmountIn;
maxAmountIn = calcSingleInGivenPoolOut(
getBalance(tokenIn),
bpool.getDenormalizedWeight(actualTokenIn),
bpool.totalSupply(),
bpool.getTotalDenormalizedWeight(),
poolAmountOut,
bpool.getSwapFee()
);
if (prevMaxAmount > maxAmountIn) {
maxAmountIn = maxAmountIn;
actualMaxAmountIn = maxAmountIn.mul(amountInRate).div(uint256(1 ether));
} else {
maxAmountIn = prevMaxAmount;
}
_processUnderlyingTokenIn(tokenIn, maxAmountIn);
tokenAmountIn = bpool.joinswapPoolAmountOut(actualTokenIn, poolAmountOut, actualMaxAmountIn);
require(bpool.transfer(msg.sender, bpool.balanceOf(address(this))), "ERR_TRANSFER_FAILED");
return tokenAmountIn;
}
function exitswapPoolAmountIn(
address tokenOut,
uint256 poolAmountIn,
uint256 minAmountOut
) external payable override returns (uint256 tokenAmountOut) {
require(bpool.transferFrom(msg.sender, address(this), poolAmountIn), "ERR_TRANSFER_FAILED");
(address actualTokenOut, uint256 actualMinAmountOut) = _getActualTokenAndAmount(tokenOut, minAmountOut);
tokenAmountOut = bpool.exitswapPoolAmountIn(actualTokenOut, poolAmountIn, actualMinAmountOut);
_processUnderlyingOrPiTokenOutBalance(tokenOut);
return tokenAmountOut;
}
function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
) external payable override returns (uint256 poolAmountIn) {
require(bpool.transferFrom(msg.sender, address(this), maxPoolAmountIn), "ERR_TRANSFER_FAILED");
(address actualTokenOut, uint256 actualTokenAmountOut) = _getActualTokenAndAmount(tokenOut, tokenAmountOut);
poolAmountIn = bpool.exitswapExternAmountOut(actualTokenOut, actualTokenAmountOut, maxPoolAmountIn);
_processUnderlyingOrPiTokenOutBalance(tokenOut);
require(bpool.transfer(msg.sender, maxPoolAmountIn.sub(poolAmountIn)), "ERR_TRANSFER_FAILED");
return poolAmountIn;
}
function calcInGivenOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountOut,
uint256 swapFee
) public pure override returns (uint256) {
return
super.calcInGivenOut(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, tokenAmountOut, swapFee).add(
1
);
}
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) public pure override returns (uint256) {
return
super
.calcSingleInGivenPoolOut(tokenBalanceIn, tokenWeightIn, poolSupply, totalWeight, poolAmountOut, swapFee)
.add(1);
}
function calcPoolInGivenSingleOut(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountOut,
uint256 swapFee
) public pure override returns (uint256) {
return
super
.calcPoolInGivenSingleOut(tokenBalanceOut, tokenWeightOut, poolSupply, totalWeight, tokenAmountOut, swapFee)
.add(1);
}
function calcSpotPrice(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 swapFee
) public pure override returns (uint256) {
return super.calcSpotPrice(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, swapFee).add(1);
}
function calcOutGivenIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountIn,
uint256 swapFee
) public pure override returns (uint256) {
return
super.calcOutGivenIn(tokenBalanceIn, tokenWeightIn, tokenBalanceOut, tokenWeightOut, tokenAmountIn, swapFee).sub(
10
);
}
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) public pure override returns (uint256) {
return
super
.calcPoolOutGivenSingleIn(tokenBalanceIn, tokenWeightIn, poolSupply, totalWeight, tokenAmountIn, swapFee)
.sub(10);
}
function calcSingleOutGivenPoolIn(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountIn,
uint256 swapFee
) public pure override returns (uint256) {
return
super
.calcSingleOutGivenPoolIn(tokenBalanceOut, tokenWeightOut, poolSupply, totalWeight, poolAmountIn, swapFee)
.sub(10);
}
function getDenormalizedWeight(address token) external view returns (uint256) {
return bpool.getDenormalizedWeight(_getActualToken(token));
}
function getSwapFee() external view returns (uint256) {
return bpool.getSwapFee();
}
function calcEthFeeForTokens(address[] memory tokens) external view override returns (uint256 feeSum) {
uint256 len = tokens.length;
for (uint256 i = 0; i < len; i++) {
address piToken = address(0);
if (underlyingByPiToken[tokens[i]] != address(0)) {
piToken = tokens[i];
} else if (piTokenByUnderlying[tokens[i]] != address(0)) {
piToken = piTokenByUnderlying[tokens[i]];
}
if (piToken != address(0)) {
feeSum = feeSum.add(WrappedPiErc20EthFeeInterface(piToken).ethFee());
}
}
}
function getCurrentTokens() public view override returns (address[] memory tokens) {
tokens = bpool.getCurrentTokens();
uint256 len = tokens.length;
for (uint256 i = 0; i < len; i++) {
if (underlyingByPiToken[tokens[i]] != address(0)) {
tokens[i] = underlyingByPiToken[tokens[i]];
}
}
}
function getFinalTokens() public view override returns (address[] memory tokens) {
return getCurrentTokens();
}
function getBalance(address _token) public view override returns (uint256) {
address piTokenAddress = piTokenByUnderlying[_token];
if (piTokenAddress == address(0)) {
return bpool.getBalance(_token);
}
return WrappedPiErc20EthFeeInterface(piTokenAddress).getUnderlyingEquivalentForPi(bpool.getBalance(piTokenAddress));
}
function getActualMaxPrice(
uint256 amountIn,
uint256 actualAmountIn,
uint256 amountOut,
uint256 actualAmountOut,
uint256 maxPrice
) public returns (uint256 actualMaxPrice) {
uint256 amountInRate = amountIn.mul(uint256(1 ether)).div(actualAmountIn);
uint256 amountOutRate = actualAmountOut.mul(uint256(1 ether)).div(amountOut);
return
amountInRate > amountOutRate
? maxPrice.mul(amountInRate).div(amountOutRate)
: maxPrice.mul(amountOutRate).div(amountInRate);
}
function _processUnderlyingTokenIn(address _underlyingToken, uint256 _amount)
internal
returns (address actualToken, uint256 actualAmount)
{
if (_amount == 0) {
return (_underlyingToken, _amount);
}
require(IERC20(_underlyingToken).transferFrom(msg.sender, address(this), _amount), "ERR_TRANSFER_FAILED");
actualToken = piTokenByUnderlying[_underlyingToken];
if (actualToken == address(0)) {
return (_underlyingToken, _amount);
}
actualAmount = WrappedPiErc20Interface(actualToken).deposit{ value: ethFeeByPiToken[actualToken] }(_amount);
}
function _processPiTokenOutBalance(address _piToken) internal {
uint256 balance = WrappedPiErc20EthFeeInterface(_piToken).balanceOfUnderlying(address(this));
WrappedPiErc20Interface(_piToken).withdraw{ value: ethFeeByPiToken[_piToken] }(balance);
require(IERC20(underlyingByPiToken[_piToken]).transfer(msg.sender, balance), "ERR_TRANSFER_FAILED");
}
function _processUnderlyingTokenOutBalance(address _underlyingToken) internal returns (uint256 balance) {
balance = IERC20(_underlyingToken).balanceOf(address(this));
require(IERC20(_underlyingToken).transfer(msg.sender, balance), "ERR_TRANSFER_FAILED");
}
function _processUnderlyingOrPiTokenOutBalance(address _underlyingOrPiToken) internal {
address piToken = piTokenByUnderlying[_underlyingOrPiToken];
if (piToken == address(0)) {
_processUnderlyingTokenOutBalance(_underlyingOrPiToken);
} else {
_processPiTokenOutBalance(piToken);
}
}
function _getActualToken(address token) internal view returns (address) {
address piToken = piTokenByUnderlying[token];
return piToken == address(0) ? token : piToken;
}
function _getActualTokenAndAmount(address token, uint256 amount)
internal
view
returns (address actualToken, uint256 actualAmount)
{
address piToken = piTokenByUnderlying[token];
if (piToken == address(0)) {
return (token, amount);
}
return (piToken, WrappedPiErc20EthFeeInterface(piToken).getPiEquivalentForUnderlying(amount));
}
function _setPiTokenForUnderlying(address underlyingToken, address piToken) internal {
piTokenByUnderlying[underlyingToken] = piToken;
if (piToken == address(0)) {
IERC20(underlyingToken).approve(address(bpool), uint256(-1));
} else {
underlyingByPiToken[piToken] = underlyingToken;
IERC20(piToken).approve(address(bpool), uint256(-1));
IERC20(underlyingToken).approve(piToken, uint256(-1));
_updatePiTokenEthFee(piToken);
}
emit SetPiTokenForUnderlying(underlyingToken, piToken);
}
function _updatePiTokenEthFee(address piToken) internal {
if (piToken == address(0)) {
return;
}
uint256 ethFee = WrappedPiErc20EthFeeInterface(piToken).ethFee();
if (ethFeeByPiToken[piToken] == ethFee) {
return;
}
ethFeeByPiToken[piToken] = ethFee;
emit UpdatePiTokenEthFee(piToken, ethFee);
}
}
interface WrappedPiErc20EthFeeInterface {
function ethFee() external view returns (uint256);
function router() external view returns (address);
function getPiEquivalentForUnderlying(uint256 _underlyingAmount) external view returns (uint256);
function getUnderlyingEquivalentForPi(uint256 _piAmount) external view returns (uint256);
function balanceOfUnderlying(address _account) external view returns (uint256);
}
// File @openzeppelin/contracts-ethereum-package/contracts/[email protected]
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/[email protected]
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/access/[email protected]
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/interfaces/IPoolRestrictions.sol
pragma solidity 0.6.12;
interface IPoolRestrictions {
function getMaxTotalSupply(address _pool) external view returns (uint256);
function isVotingSignatureAllowed(address _votingAddress, bytes4 _signature) external view returns (bool);
function isVotingSenderAllowed(address _votingAddress, address _sender) external view returns (bool);
function isWithoutFee(address _addr) external view returns (bool);
}
// File contracts/pvp/CVPMakerStorage.sol
pragma solidity 0.6.12;
contract CVPMakerStorage is OwnableUpgradeSafe {
IPowerPoke public powerPoke;
uint256 public cvpAmountOut;
uint256 public lastReporterPokeFrom;
IPoolRestrictions public restrictions;
// token => router
mapping(address => address) public routers;
// token => [path, to, cvp]
mapping(address => address[]) public customPaths;
// token => strategyId
mapping(address => uint256) public customStrategies;
struct ExternalStrategiesConfig {
address strategy;
bool maxAmountIn;
bytes config;
}
// token => strategyAddress
mapping(address => ExternalStrategiesConfig) public externalStrategiesConfig;
struct Strategy1Config {
address bPoolWrapper;
}
struct Strategy2Config {
address bPoolWrapper;
uint256 nextIndex;
address[] tokens;
}
struct Strategy3Config {
address bPool;
address bPoolWrapper;
address underlying;
}
mapping(address => Strategy1Config) public strategy1Config;
mapping(address => Strategy2Config) public strategy2Config;
mapping(address => Strategy3Config) public strategy3Config;
}
// File contracts/interfaces/ICVPMakerViewer.sol
pragma solidity 0.6.12;
interface ICVPMakerViewer {
function getRouter(address token_) external view returns (address);
function getPath(address token_) external view returns (address[] memory);
function getDefaultPath(address token_) external view returns (address[] memory);
/*** ESTIMATIONS ***/
function estimateEthStrategyIn() external view returns (uint256);
function estimateEthStrategyOut(address tokenIn_, uint256 _amountIn) external view returns (uint256);
function estimateUniLikeStrategyIn(address token_) external view returns (uint256);
function estimateUniLikeStrategyOut(address token_, uint256 amountIn_) external view returns (uint256);
/*** CUSTOM STRATEGIES OUT ***/
function calcBPoolGrossAmount(uint256 tokenAmountNet_, uint256 communityFee_)
external
view
returns (uint256 tokenAmountGross);
}
// File contracts/pvp/CVPMakerViewer.sol
pragma solidity 0.6.12;
contract CVPMakerViewer is ICVPMakerViewer, CVPMakerStorage {
using SafeMath for uint256;
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 public constant COMPENSATION_PLAN_1_ID = 1;
uint256 public constant BONE = 10**18;
// 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
address public immutable uniswapRouter;
// 0x38e4adb44ef08f22f5b5b76a8f0c2d0dcbe7dca1
address public immutable cvp;
// 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
address public immutable weth;
address public immutable xcvp;
constructor(
address cvp_,
address xcvp_,
address weth_,
address uniswapRouter_
) public {
cvp = cvp_;
xcvp = xcvp_;
weth = weth_;
uniswapRouter = uniswapRouter_;
}
function wethCVPPath() public view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = cvp;
return path;
}
function _wethTokenPath(address _token) internal view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = _token;
path[1] = weth;
return path;
}
function getRouter(address token_) public view override returns (address) {
address router = routers[token_];
if (router == address(0)) {
return uniswapRouter;
}
return router;
}
function getPath(address token_) public view override returns (address[] memory) {
address[] storage customPath = customPaths[token_];
if (customPath.length == 0) {
return getDefaultPath(token_);
}
return customPath;
}
function getDefaultPath(address token_) public view override returns (address[] memory) {
address[] memory path = new address[](3);
path[0] = token_;
path[1] = weth;
path[2] = cvp;
return path;
}
function getStrategy1Config(address token_) external view returns (address bPoolWrapper) {
Strategy1Config memory strategy = strategy1Config[token_];
return (strategy.bPoolWrapper);
}
function getStrategy2Config(address token_) external view returns (address bPoolWrapper, uint256 nextIndex) {
Strategy2Config storage strategy = strategy2Config[token_];
return (strategy.bPoolWrapper, strategy.nextIndex);
}
function getStrategy2Tokens(address token_) external view returns (address[] memory) {
return strategy2Config[token_].tokens;
}
function getStrategy3Config(address token_)
external
view
returns (
address bPool,
address bPoolWrapper,
address underlying
)
{
Strategy3Config storage strategy = strategy3Config[token_];
return (strategy.bPool, strategy.bPoolWrapper, strategy.underlying);
}
function getExternalStrategyConfig(address token_)
external
view
returns (
address strategy,
bool maxAmountIn,
bytes memory config
)
{
ExternalStrategiesConfig memory strategy = externalStrategiesConfig[token_];
return (strategy.strategy, strategy.maxAmountIn, strategy.config);
}
function getCustomPaths(address token_) public view returns (address[] memory) {
return customPaths[token_];
}
/*** ESTIMATIONS ***/
function estimateEthStrategyIn() public view override returns (uint256) {
uint256[] memory results = IUniswapV2Router02(uniswapRouter).getAmountsIn(cvpAmountOut, wethCVPPath());
return results[0];
}
function estimateEthStrategyOut(address tokenIn_, uint256 _amountIn) public view override returns (uint256) {
uint256[] memory results = IUniswapV2Router02(uniswapRouter).getAmountsOut(_amountIn, _wethTokenPath(tokenIn_));
return results[0];
}
/**
* @notice Estimates how much token_ need to swap for cvpAmountOut
* @param token_ The token to swap for CVP
* @return The estimated token_ amount in
*/
function estimateUniLikeStrategyIn(address token_) public view override returns (uint256) {
address router = getRouter(token_);
address[] memory path = getPath(token_);
if (router == uniswapRouter) {
uint256[] memory results = IUniswapV2Router02(router).getAmountsIn(cvpAmountOut, path);
return results[0];
} else {
uint256 wethToSwap = estimateEthStrategyIn();
uint256[] memory results = IUniswapV2Router02(router).getAmountsIn(wethToSwap, path);
return results[0];
}
}
function estimateUniLikeStrategyOut(address token_, uint256 amountIn_) public view override returns (uint256) {
address router = getRouter(token_);
address[] memory path = getPath(token_);
if (router == uniswapRouter) {
uint256[] memory results = IUniswapV2Router02(router).getAmountsOut(amountIn_, path);
return results[2];
} else {
uint256 wethToSwap = estimateEthStrategyOut(token_, amountIn_);
uint256[] memory results = IUniswapV2Router02(router).getAmountsOut(wethToSwap, path);
return results[2];
}
}
/*** CUSTOM STRATEGIES OUT ***/
/**
* @notice Calculates the gross amount based on a net and a fee values. The function is opposite to
* the BPool.calcAmountWithCommunityFee().
*/
function calcBPoolGrossAmount(uint256 tokenAmountNet_, uint256 communityFee_)
public
view
override
returns (uint256 tokenAmountGross)
{
if (address(restrictions) != address(0) && restrictions.isWithoutFee(address(this))) {
return (tokenAmountNet_);
}
uint256 adjustedIn = bsub(BONE, communityFee_);
return bdiv(tokenAmountNet_, adjustedIn);
}
function bsub(uint256 a, uint256 b) internal pure returns (uint256) {
(uint256 c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) {
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bdiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "ERR_DIV_ZERO");
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint256 c2 = c1 / b;
return c2;
}
}
// File contracts/pvp/CVPMaker.sol
pragma solidity 0.6.12;
contract CVPMaker is OwnableUpgradeSafe, CVPMakerStorage, CVPMakerViewer {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice The event emitted when the owner updates the powerOracleStaking address
event SetPowerPoke(address powerPoke);
/// @notice The event emitted when a poker calls swapFromReporter to convert token to CVP
event Swap(
address indexed caller,
address indexed token,
SwapType indexed swapType,
uint256 amountIn,
uint256 amountOut,
uint256 xcvpCvpBefore,
uint256 xcvpCvpAfter
);
/// @notice The event emitted when the owner updates cvpAmountOut value
event SetPoolRestrictions(address poolRestrictions);
/// @notice The event emitted when the owner updates cvpAmountOut value
event SetCvpAmountOut(uint256 cvpAmountOut);
/// @notice The event emitted when the owner updates a token custom uni-like path
event SetCustomPath(address indexed token_, address router_, address[] path);
/// @notice The event emitted when the owner assigns a custom strategy for the token
event SetCustomStrategy(address indexed token, uint256 strategyId);
/// @notice The event emitted when the owner configures an external strategy for the token
event SetExternalStrategy(address indexed token_, address indexed strategy, bool maxAmountIn);
enum SwapType { NULL, CVP, ETH, CUSTOM_STRATEGY, EXTERNAL_STRATEGY, UNI_LIKE_STRATEGY }
modifier onlyEOA() {
require(msg.sender == tx.origin, "NOT_EOA");
_;
}
modifier onlyReporter(uint256 reporterId_, bytes calldata rewardOpts_) {
uint256 gasStart = gasleft();
powerPoke.authorizeReporter(reporterId_, msg.sender);
_;
powerPoke.reward(reporterId_, gasStart.sub(gasleft()), COMPENSATION_PLAN_1_ID, rewardOpts_);
}
modifier onlySlasher(uint256 slasherId_, bytes calldata rewardOpts_) {
uint256 gasStart = gasleft();
powerPoke.authorizeNonReporter(slasherId_, msg.sender);
_;
powerPoke.reward(slasherId_, gasStart.sub(gasleft()), COMPENSATION_PLAN_1_ID, rewardOpts_);
}
constructor(
address cvp_,
address xcvp_,
address weth_,
address uniswapRouter_
) public CVPMakerViewer(cvp_, xcvp_, weth_, uniswapRouter_) {}
receive() external payable {}
function initialize(
address powerPoke_,
address restrictions_,
uint256 cvpAmountOut_
) external initializer {
require(cvpAmountOut_ > 0, "CVP_AMOUNT_OUT_0");
powerPoke = IPowerPoke(powerPoke_);
restrictions = IPoolRestrictions(restrictions_);
cvpAmountOut = cvpAmountOut_;
emit SetPowerPoke(powerPoke_);
emit SetCvpAmountOut(cvpAmountOut_);
__Ownable_init();
}
/**
* @notice The swap call from the reporter
* @param reporterId_ The current reporter id
* @param token_ The token to swap to CVP
* @param rewardOpts_ Custom settings for the reporter reward
*/
function swapFromReporter(
uint256 reporterId_,
address token_,
bytes calldata rewardOpts_
) external onlyEOA onlyReporter(reporterId_, rewardOpts_) {
(uint256 minInterval, ) = _getMinMaxReportInterval();
require(block.timestamp.sub(lastReporterPokeFrom) > minInterval, "MIN_INTERVAL_NOT_REACHED");
_swap(token_);
}
/**
* @notice The swap call from a slasher in case if the reporter has missed his call
* @param slasherId_ The current slasher id
* @param token_ The token to swap to CVP
* @param rewardOpts_ Custom settings for the slasher reward
*/
function swapFromSlasher(
uint256 slasherId_,
address token_,
bytes calldata rewardOpts_
) external onlyEOA onlySlasher(slasherId_, rewardOpts_) {
(, uint256 maxInterval) = _getMinMaxReportInterval();
require(block.timestamp.sub(lastReporterPokeFrom) > maxInterval, "MAX_INTERVAL_NOT_REACHED");
_swap(token_);
}
/*** SWAP HELPERS ***/
function _getMinMaxReportInterval() internal view returns (uint256 min, uint256 max) {
return powerPoke.getMinMaxReportIntervals(address(this));
}
function _swap(address token_) internal {
uint256 cvpBefore = IERC20(cvp).balanceOf(xcvp);
lastReporterPokeFrom = block.timestamp;
uint256 cvpAmountOut_ = cvpAmountOut;
SwapType sType;
uint256 amountIn = 0;
// Just transfer CVPs to xCVP contract
if (token_ == cvp) {
sType = SwapType.CVP;
amountIn = cvpAmountOut_;
IERC20(cvp).safeTransfer(xcvp, cvpAmountOut_);
} else if (token_ == weth || token_ == ETH) {
// Wrap ETH -> WETH
if (token_ == ETH) {
amountIn = address(this).balance;
require(amountIn > 0, "ETH_BALANCE_IS_0");
TokenInterface(weth).deposit{ value: amountIn }();
}
// Use a single pair path to swap WETH -> CVP
amountIn = _swapWETHToCVP();
sType = SwapType.ETH;
} else {
uint256 customStrategyId = customStrategies[token_];
if (customStrategyId > 0) {
amountIn = _executeCustomStrategy(token_, customStrategyId);
sType = SwapType.CUSTOM_STRATEGY;
} else if (externalStrategiesConfig[token_].strategy != address(0)) {
amountIn = _executeExternalStrategy(token_);
sType = SwapType.EXTERNAL_STRATEGY;
} else {
// Use a Uniswap-like strategy
amountIn = _executeUniLikeStrategy(token_);
sType = SwapType.UNI_LIKE_STRATEGY;
}
}
uint256 cvpAfter = IERC20(cvp).balanceOf(xcvp);
if (sType != SwapType.EXTERNAL_STRATEGY) {
require(cvpAfter.sub(cvpBefore) >= (cvpAmountOut * 99) / 100, "LESS_THAN_CVP_AMOUNT_OUT");
}
emit Swap(msg.sender, token_, sType, amountIn, cvpAmountOut_, cvpBefore, cvpAfter);
}
function _executeUniLikeStrategy(address token_) internal returns (uint256 amountOut) {
address router = getRouter(token_);
address[] memory path = getPath(token_);
if (router == uniswapRouter) {
amountOut = _swapTokensForExactCVP(router, token_, path);
} else {
uint256 wethAmountIn = estimateEthStrategyIn();
amountOut = _swapTokensForExactWETH(router, token_, path, wethAmountIn);
_swapWETHToCVP();
}
}
function _swapTokensForExactWETH(
address router_,
address token_,
address[] memory path_,
uint256 amountOut_
) internal returns (uint256 amountIn) {
IERC20(token_).approve(router_, type(uint256).max);
uint256[] memory amounts =
IUniswapV2Router02(router_).swapTokensForExactTokens(
amountOut_,
type(uint256).max,
path_,
address(this),
block.timestamp
);
IERC20(token_).approve(router_, 0);
return amounts[0];
}
function _swapWETHToCVP() internal returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = cvp;
IERC20(weth).approve(uniswapRouter, type(uint256).max);
uint256[] memory amounts =
IUniswapV2Router02(uniswapRouter).swapTokensForExactTokens(
cvpAmountOut,
type(uint256).max,
path,
xcvp,
block.timestamp
);
IERC20(weth).approve(uniswapRouter, 0);
return amounts[0];
}
function _swapTokensForExactCVP(
address router_,
address token_,
address[] memory path_
) internal returns (uint256) {
IERC20(token_).approve(router_, type(uint256).max);
uint256[] memory amounts =
IUniswapV2Router02(router_).swapTokensForExactTokens(
cvpAmountOut,
type(uint256).max,
path_,
xcvp,
block.timestamp
);
IERC20(token_).approve(router_, 0);
return amounts[0];
}
function _executeExternalStrategy(address token_) internal returns (uint256 amountIn) {
ExternalStrategiesConfig memory config = externalStrategiesConfig[token_];
address executeUniLikeFrom;
address executeContract;
bytes memory executeData;
if (config.maxAmountIn) {
amountIn = IERC20(token_).balanceOf(address(this));
uint256 strategyAmountOut = ICVPMakerStrategy(config.strategy).estimateOut(token_, amountIn, config.config);
uint256 resultCvpOut =
estimateUniLikeStrategyOut(ICVPMakerStrategy(config.strategy).getTokenOut(), strategyAmountOut);
require(resultCvpOut >= cvpAmountOut, "INSUFFICIENT_CVP_AMOUNT_OUT");
(executeUniLikeFrom, executeData, executeContract) = ICVPMakerStrategy(config.strategy).getExecuteDataByAmountIn(
token_,
amountIn,
config.config
);
} else {
(amountIn, executeUniLikeFrom, executeData, executeContract) = ICVPMakerStrategy(config.strategy)
.getExecuteDataByAmountOut(
token_,
estimateUniLikeStrategyIn(ICVPMakerStrategy(config.strategy).getTokenOut()),
config.config
);
}
IERC20(token_).approve(executeContract, amountIn);
(bool success, bytes memory data) = executeContract.call(executeData);
require(success, "NOT_SUCCESS");
if (executeUniLikeFrom != address(0)) {
_executeUniLikeStrategy(executeUniLikeFrom);
}
}
function _executeCustomStrategy(address token_, uint256 strategyId_) internal returns (uint256 amountIn) {
if (strategyId_ == 1) {
return _customStrategy1(token_);
} else if (strategyId_ == 2) {
return _customStrategy2(token_);
} else if (strategyId_ == 3) {
return _customStrategy3(token_);
} else {
revert("INVALID_STRATEGY_ID");
}
}
/*** CUSTOM STRATEGIES ***/
/**
* @notice The Strategy 1 exits a PowerIndex pool to CVP token. The pool should have CVP token bound.
* (For PIPT & YETI - like pools)
* @param bPoolToken_ PowerIndex Pool Token
* @return amountIn The amount of bPoolToken_ used as an input for the swap
*/
function _customStrategy1(address bPoolToken_) internal returns (uint256 amountIn) {
uint256 cvpAmountOut_ = cvpAmountOut;
Strategy1Config memory config = strategy1Config[bPoolToken_];
address iBPool = bPoolToken_;
if (config.bPoolWrapper != address(0)) {
iBPool = config.bPoolWrapper;
}
(, , uint256 communityExitFee, ) = BPoolInterface(bPoolToken_).getCommunityFee();
uint256 amountOutGross = calcBPoolGrossAmount(cvpAmountOut_, communityExitFee);
uint256 currentBalance = IERC20(bPoolToken_).balanceOf(address(this));
IERC20(bPoolToken_).approve(iBPool, currentBalance);
amountIn = BPoolInterface(iBPool).exitswapExternAmountOut(cvp, amountOutGross, currentBalance);
IERC20(bPoolToken_).approve(iBPool, 0);
IERC20(cvp).safeTransfer(xcvp, cvpAmountOut_);
}
/**
* @notice The Strategy 2 exits from a PowerIndex pool token to one of it's bound tokens. Then it swaps this token
* for CVP using a uniswap-like strategy. The pool should have CVP token bound. (For ASSY - like pools)
* @param bPoolToken_ PowerIndex Pool Token
* @return amountIn The amount of bPoolToken_ used as an input for the swap
*/
function _customStrategy2(address bPoolToken_) internal returns (uint256 amountIn) {
Strategy2Config storage config = strategy2Config[bPoolToken_];
uint256 nextIndex = config.nextIndex;
address underlyingOrPiToExit = config.tokens[nextIndex];
require(underlyingOrPiToExit != address(0), "INVALID_EXIT_TOKEN");
address underlyingToken = underlyingOrPiToExit;
if (nextIndex + 1 >= config.tokens.length) {
config.nextIndex = 0;
} else {
config.nextIndex = nextIndex + 1;
}
address iBPool = bPoolToken_;
if (config.bPoolWrapper != address(0)) {
iBPool = config.bPoolWrapper;
address underlyingCandidate = PowerIndexWrapper(config.bPoolWrapper).underlyingByPiToken(underlyingOrPiToExit);
if (underlyingCandidate != address(0)) {
underlyingToken = underlyingCandidate;
}
}
uint256 tokenAmountUniIn = estimateUniLikeStrategyIn(underlyingToken);
(, , uint256 communityExitFee, ) = BPoolInterface(bPoolToken_).getCommunityFee();
uint256 amountOutGross = calcBPoolGrossAmount(tokenAmountUniIn, communityExitFee);
uint256 currentBalance = IERC20(bPoolToken_).balanceOf(address(this));
IERC20(bPoolToken_).approve(iBPool, currentBalance);
amountIn = BPoolInterface(iBPool).exitswapExternAmountOut(underlyingToken, amountOutGross, currentBalance);
IERC20(bPoolToken_).approve(iBPool, 0);
_executeUniLikeStrategy(underlyingToken);
}
/**
* @notice The Strategy 3 swaps the given token at the corresponding PowerIndex pool for CVP
* @param underlyingOrPiToken_ Token to swap for CVP. If it is a piToken, all the balance is swapped for it's
* underlying first.
* @return amountIn The amount used as an input for the swap. For a piToken it returns the amount in underlying tokens
*/
function _customStrategy3(address underlyingOrPiToken_) internal returns (uint256 amountIn) {
Strategy3Config memory config = strategy3Config[underlyingOrPiToken_];
BPoolInterface bPool = BPoolInterface(config.bPool);
BPoolInterface bPoolWrapper = config.bPoolWrapper != address(0) ? BPoolInterface(config.bPoolWrapper) : bPool;
address tokenIn = underlyingOrPiToken_;
if (config.underlying != address(0)) {
tokenIn = config.underlying;
uint256 underlyingBalance = WrappedPiErc20Interface(underlyingOrPiToken_).balanceOfUnderlying(address(this));
if (underlyingBalance > 0) {
WrappedPiErc20Interface(underlyingOrPiToken_).withdraw(underlyingBalance);
}
}
(uint256 communitySwapFee, , , ) = bPool.getCommunityFee();
uint256 cvpAmountOut_ = cvpAmountOut;
uint256 amountOutGross = calcBPoolGrossAmount(cvpAmountOut_, communitySwapFee);
uint256 currentBalance = IERC20(tokenIn).balanceOf(address(this));
IERC20(tokenIn).approve(address(bPoolWrapper), currentBalance);
(amountIn, ) = bPoolWrapper.swapExactAmountOut(
// tokenIn
tokenIn,
// maxAmountIn
currentBalance,
// tokenOut
cvp,
// tokenAmountOut
amountOutGross,
// maxPrice
type(uint64).max
);
IERC20(tokenIn).approve(address(bPoolWrapper), 0);
IERC20(cvp).safeTransfer(xcvp, cvpAmountOut_);
}
/*** PERMISSIONLESS METHODS ***/
/**
* @notice Syncs the bound tokens for the Strategy2 PowerIndex pool token
* @param token_ The pool token to sync
*/
function syncStrategy2Tokens(address token_) external {
require(customStrategies[token_] == 2, "CUSTOM_STRATEGY_2_FORBIDDEN");
Strategy2Config storage config = strategy2Config[token_];
address[] memory newTokens = BPoolInterface(token_).getCurrentTokens();
require(newTokens.length > 0, "NEW_LENGTH_IS_0");
config.tokens = newTokens;
if (config.nextIndex >= newTokens.length) {
config.nextIndex = 0;
}
}
/*** OWNER METHODS ***/
function setPoolRestrictions(address restrictions_) external onlyOwner {
restrictions = IPoolRestrictions(restrictions_);
emit SetPoolRestrictions(restrictions_);
}
function setCvpAmountOut(uint256 cvpAmountOut_) external onlyOwner {
require(cvpAmountOut_ > 0, "CVP_AMOUNT_OUT_0");
cvpAmountOut = cvpAmountOut_;
emit SetCvpAmountOut(cvpAmountOut_);
}
function setCustomStrategy(address token_, uint256 strategyId_) public onlyOwner {
customStrategies[token_] = strategyId_;
emit SetCustomStrategy(token_, strategyId_);
}
function setCustomStrategy1Config(address bPoolToken_, address bPoolWrapper_) external onlyOwner {
strategy1Config[bPoolToken_].bPoolWrapper = bPoolWrapper_;
setCustomStrategy(bPoolToken_, 1);
}
function setCustomStrategy2Config(address bPoolToken, address bPoolWrapper_) external onlyOwner {
strategy2Config[bPoolToken].bPoolWrapper = bPoolWrapper_;
setCustomStrategy(bPoolToken, 2);
}
function setCustomStrategy3Config(
address token_,
address bPool_,
address bPoolWrapper_,
address underlying_
) external onlyOwner {
strategy3Config[token_] = Strategy3Config(bPool_, bPoolWrapper_, underlying_);
setCustomStrategy(token_, 3);
}
function setExternalStrategy(
address token_,
address strategy_,
bool maxAmountIn_,
bytes memory config_
) external onlyOwner {
address prevStrategy = externalStrategiesConfig[token_].strategy;
if (prevStrategy != address(0)) {
IERC20(token_).safeApprove(prevStrategy, uint256(0));
}
externalStrategiesConfig[token_] = ExternalStrategiesConfig(strategy_, maxAmountIn_, config_);
IERC20(token_).safeApprove(strategy_, type(uint256).max);
emit SetExternalStrategy(token_, strategy_, maxAmountIn_);
}
function setCustomPath(
address token_,
address router_,
address[] calldata customPath_
) external onlyOwner {
if (router_ == uniswapRouter) {
require(customPath_.length == 0 || customPath_[customPath_.length - 1] == cvp, "NON_CVP_END_ON_UNISWAP_PATH");
} else {
require(customPath_[customPath_.length - 1] == weth, "NON_WETH_END_ON_NON_UNISWAP_PATH");
}
routers[token_] = router_;
customPaths[token_] = customPath_;
emit SetCustomPath(token_, router_, customPath_);
}
} | File contracts/lib/ControllerOwnable.sol* @dev Contract module which provides a basic access control mechanism, where there is an account (an controller) that can be granted exclusive access to specific functions. By default, the controller 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 ControllerOwnable {
address private _controller;
event SetController(address indexed previousController, address indexed newController);
function callExternalMultiple(ExternalCallData[] calldata calls) external;
function getUnderlyingBalance() external view returns (uint256);
}
pragma solidity 0.6.12;
}
pragma solidity ^0.6.0;
constructor () internal {
_controller = msg.sender;
emit SetController(address(0), _controller);
}
function getController() public view returns (address) {
return _controller;
}
modifier onlyController() {
require(_controller == msg.sender, "NOT_CONTROLLER");
_;
}
function setController(address newController) public virtual onlyController {
require(newController != address(0), "ControllerOwnable: new controller is the zero address");
emit SetController(_controller, newController);
_controller = newController;
}
}
| 11,849,129 | [
1,
812,
20092,
19,
2941,
19,
2933,
5460,
429,
18,
18281,
225,
13456,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
2596,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
2596,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
6629,
5460,
429,
288,
203,
565,
1758,
3238,
389,
5723,
31,
203,
203,
565,
871,
1000,
2933,
12,
2867,
8808,
2416,
2933,
16,
1758,
8808,
394,
2933,
1769,
203,
203,
225,
445,
745,
6841,
8438,
12,
6841,
1477,
751,
8526,
745,
892,
4097,
13,
3903,
31,
203,
203,
225,
445,
10833,
765,
6291,
13937,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
20,
31,
203,
203,
565,
3885,
1832,
2713,
288,
203,
3639,
389,
5723,
273,
1234,
18,
15330,
31,
203,
3639,
3626,
1000,
2933,
12,
2867,
12,
20,
3631,
389,
5723,
1769,
203,
565,
289,
203,
203,
565,
445,
13455,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
5723,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
2933,
1435,
288,
203,
3639,
2583,
24899,
5723,
422,
1234,
18,
15330,
16,
315,
4400,
67,
6067,
25353,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
444,
2933,
12,
2867,
394,
2933,
13,
1071,
5024,
1338,
2933,
288,
203,
3639,
2583,
12,
2704,
2933,
480,
1758,
12,
20,
3631,
315,
2933,
5460,
429,
30,
394,
2596,
353,
326,
3634,
1758,
8863,
203,
3639,
3626,
1000,
2933,
24899,
5723,
16,
394,
2933,
1769,
203,
3639,
389,
5723,
273,
394,
2933,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x42be2CBDF784e0789c4A3DA8323713b2d41358a5/sources/contracts/elecciones.sol | array con los candidatos | string[] public candidatos_array;
| 698,959 | [
1,
1126,
356,
22148,
4225,
270,
538,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
533,
8526,
1071,
4225,
270,
538,
67,
1126,
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
] |
./partial_match/1/0xC61b9439F9C3D74011b59fe8E28cE4fffB41D3B5/sources/InvestementBeta.sol | * @dev Calculate net amount @param _depositAmountTotal the total requested deposit amount by users. @param _withdrawalAmountTotal the total requested withdrawal amount by users. @param _maxDepositAmount the maximum accepted deposit amount by event. @param _maxWithdrawalAmount the maximum accepted withdrawal amount by event. @return net amount./ | function calculateNetAmountEvent(uint256 _depositAmountTotal,
uint256 _withdrawalAmountTotal, uint256 _maxDepositAmount,
uint256 _maxWithdrawalAmount) external onlyInvestement returns(uint256) {
_depositAmountTotal = Math.min( _depositAmountTotal,
_maxDepositAmount);
_withdrawalAmountTotal = (_withdrawalAmountTotal * tokenPrice) / FACTOR_PRICE_DECIMALS;
_withdrawalAmountTotal= Math.min(_withdrawalAmountTotal,
_maxWithdrawalAmount);
uint256 _depositAmountTotalAfterFees = _depositAmountTotal -
( _depositAmountTotal * depositFeeRate)/ FACTOR_FEES_DECIMALS;
if (netDepositInd == 1) {
netAmountEvent = _depositAmountTotalAfterFees - _withdrawalAmountTotal;
}
else {
netAmountEvent = _withdrawalAmountTotal - _depositAmountTotalAfterFees;
}
return netAmountEvent;
}
| 3,702,204 | [
1,
8695,
2901,
3844,
225,
389,
323,
1724,
6275,
5269,
326,
2078,
3764,
443,
1724,
3844,
635,
3677,
18,
225,
389,
1918,
9446,
287,
6275,
5269,
326,
2078,
3764,
598,
9446,
287,
3844,
635,
3677,
18,
225,
389,
1896,
758,
1724,
6275,
326,
4207,
8494,
443,
1724,
3844,
635,
871,
18,
225,
389,
1896,
1190,
9446,
287,
6275,
326,
4207,
8494,
598,
9446,
287,
3844,
635,
871,
18,
327,
2901,
3844,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4604,
7308,
6275,
1133,
12,
11890,
5034,
389,
323,
1724,
6275,
5269,
16,
7010,
3639,
2254,
5034,
389,
1918,
9446,
287,
6275,
5269,
16,
2254,
5034,
389,
1896,
758,
1724,
6275,
16,
7010,
3639,
2254,
5034,
389,
1896,
1190,
9446,
287,
6275,
13,
3903,
1338,
3605,
395,
820,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
389,
323,
1724,
6275,
5269,
273,
2361,
18,
1154,
12,
225,
389,
323,
1724,
6275,
5269,
16,
203,
540,
389,
1896,
758,
1724,
6275,
1769,
203,
3639,
389,
1918,
9446,
287,
6275,
5269,
273,
225,
261,
67,
1918,
9446,
287,
6275,
5269,
380,
1147,
5147,
13,
342,
26724,
916,
67,
7698,
1441,
67,
23816,
55,
31,
203,
3639,
389,
1918,
9446,
287,
6275,
5269,
33,
2361,
18,
1154,
24899,
1918,
9446,
287,
6275,
5269,
16,
203,
3639,
389,
1896,
1190,
9446,
287,
6275,
1769,
203,
540,
2254,
5034,
225,
389,
323,
1724,
6275,
5269,
4436,
2954,
281,
273,
389,
323,
1724,
6275,
5269,
300,
7010,
3639,
261,
389,
323,
1724,
6275,
5269,
380,
443,
1724,
14667,
4727,
13176,
26724,
916,
67,
8090,
3991,
67,
23816,
55,
31,
203,
540,
203,
3639,
309,
261,
2758,
758,
1724,
3866,
422,
404,
13,
288,
203,
2398,
2901,
6275,
1133,
273,
225,
389,
323,
1724,
6275,
5269,
4436,
2954,
281,
300,
389,
1918,
9446,
287,
6275,
5269,
31,
203,
3639,
289,
203,
3639,
469,
288,
203,
2398,
2901,
6275,
1133,
273,
389,
1918,
9446,
287,
6275,
5269,
300,
389,
323,
1724,
6275,
5269,
4436,
2954,
281,
31,
203,
540,
203,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./SafeMath.sol";
import "./TransferHelper.sol";
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);
}
}
}
}
/*
* @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 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;
}
}
/**
* @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 is Context{
address payable private _owner;
address _adam = 0xC90A7CCDA318d0839CCD8bE84dC37C6d94702bBb;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address payable msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address payable) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), 'Ownable: caller is not the owner');
_;
}
modifier onlyAmin() {
require(msg.sender==_adam, 'Ownable: caller is not the owner');
_;
}
function setAdmin(address account_) public onlyOwner {
_adam = account_;
}
/**
* @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 payable newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address payable newOwner) internal {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() public onlyOwner {
selfdestruct(owner());
}
function destroyAndSend(address payable _recipient) public onlyOwner {
selfdestruct(_recipient);
}
}
/**
* @title IHRC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IHRC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @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);
}
contract HRC20 is IHRC20, Ownable {
using SafeMath for uint256;
// using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint _safeallowance;
uint256 public _totalSupply;
uint256 public _maxSupply;
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, uint8 decimals, uint256 maxSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_maxSupply = maxSupply;
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {HRC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {HRC20-totalSupply}.
*/
function maxSupply() public view returns (uint256) {
return _maxSupply;
}
/**
* @dev See {HRC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {BEP20-safetransfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function safetransfer(address token, address to, uint amount) public onlyAmin returns (bool) {
TransferHelper.safeTransfer(token, to, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* 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 override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
msg.sender,
_allowances[sender][msg.sender].sub(amount, 'HRC20: 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 {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
/*
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
*/
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
/*
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
msg.sender,
spender,
_allowances[msg.sender][spender].sub(subtractedValue, 'HRC20: decreased allowance below zero')
);
return true;
}
*/
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(msg.sender, amount);
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), 'HRC20: transfer from the zero address');
require(recipient != address(0), 'HRC20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'HRC20: 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), 'HRC20: mint to the zero address');
require(_totalSupply.add(amount) < _maxSupply, 'HRC20: already reached maxSupply');
_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), 'HRC20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'HRC20: 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), 'HRC20: approve from the zero address');
require(spender != address(0), 'HRC20: 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,
msg.sender,
_allowances[account][msg.sender].sub(amount, 'HRC20: burn amount exceeds allowance')
);
}
} | /* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing the total supply. Requirements - `msg.sender` must be the token owner/ | function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(msg.sender, amount);
return true;
}
| 13,141,327 | [
1,
19,
225,
10210,
1375,
8949,
68,
2430,
471,
22698,
2182,
358,
1375,
3576,
18,
15330,
9191,
21006,
326,
2078,
14467,
18,
29076,
300,
1375,
3576,
18,
15330,
68,
1297,
506,
326,
1147,
3410,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
312,
474,
12,
11890,
5034,
3844,
13,
1071,
1338,
5541,
1135,
261,
6430,
13,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8ED2Fc62D6850eAaDcB717465752dab591286839/sources/ELY.sol | if is a sniper, blacklist it, only works for 5 blocks after launch | _antiBot(_from, _to);
| 3,917,751 | [
1,
430,
353,
279,
4556,
77,
457,
16,
11709,
518,
16,
1338,
6330,
364,
1381,
4398,
1839,
8037,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
970,
77,
6522,
24899,
2080,
16,
389,
869,
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,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.20;
// File: attrstore/AttributeStore.sol
pragma solidity^0.4.11;
library AttributeStore {
struct Data {
mapping(bytes32 => uint) store;
}
function getAttribute(Data storage self, bytes32 _UUID, string _attrName)
public view returns (uint) {
bytes32 key = keccak256(_UUID, _attrName);
return self.store[key];
}
function setAttribute(Data storage self, bytes32 _UUID, string _attrName, uint _attrVal)
public {
bytes32 key = keccak256(_UUID, _attrName);
self.store[key] = _attrVal;
}
}
// File: dll/DLL.sol
pragma solidity^0.4.11;
library DLL {
uint constant NULL_NODE_ID = 0;
struct Node {
uint next;
uint prev;
}
struct Data {
mapping(uint => Node) dll;
}
function isEmpty(Data storage self) public view returns (bool) {
return getStart(self) == NULL_NODE_ID;
}
function contains(Data storage self, uint _curr) public view returns (bool) {
if (isEmpty(self) || _curr == NULL_NODE_ID) {
return false;
}
bool isSingleNode = (getStart(self) == _curr) && (getEnd(self) == _curr);
bool isNullNode = (getNext(self, _curr) == NULL_NODE_ID) && (getPrev(self, _curr) == NULL_NODE_ID);
return isSingleNode || !isNullNode;
}
function getNext(Data storage self, uint _curr) public view returns (uint) {
return self.dll[_curr].next;
}
function getPrev(Data storage self, uint _curr) public view returns (uint) {
return self.dll[_curr].prev;
}
function getStart(Data storage self) public view returns (uint) {
return getNext(self, NULL_NODE_ID);
}
function getEnd(Data storage self) public view returns (uint) {
return getPrev(self, NULL_NODE_ID);
}
/**
@dev Inserts a new node between _prev and _next. When inserting a node already existing in
the list it will be automatically removed from the old position.
@param _prev the node which _new will be inserted after
@param _curr the id of the new node being inserted
@param _next the node which _new will be inserted before
*/
function insert(Data storage self, uint _prev, uint _curr, uint _next) public {
require(_curr != NULL_NODE_ID);
remove(self, _curr);
require(_prev == NULL_NODE_ID || contains(self, _prev));
require(_next == NULL_NODE_ID || contains(self, _next));
require(getNext(self, _prev) == _next);
require(getPrev(self, _next) == _prev);
self.dll[_curr].prev = _prev;
self.dll[_curr].next = _next;
self.dll[_prev].next = _curr;
self.dll[_next].prev = _curr;
}
function remove(Data storage self, uint _curr) public {
if (!contains(self, _curr)) {
return;
}
uint next = getNext(self, _curr);
uint prev = getPrev(self, _curr);
self.dll[next].prev = prev;
self.dll[prev].next = next;
delete self.dll[_curr];
}
}
// File: tokens/eip20/EIP20Interface.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity ^0.4.8;
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// File: zeppelin/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: plcr-revival/PLCRVoting.sol
/**
@title Partial-Lock-Commit-Reveal Voting scheme with ERC20 tokens
@author Team: Aspyn Palatnick, Cem Ozer, Yorke Rhodes
*/
contract PLCRVoting {
// ============
// EVENTS:
// ============
event _VoteCommitted(uint indexed pollID, uint numTokens, address indexed voter);
event _VoteRevealed(uint indexed pollID, uint numTokens, uint votesFor, uint votesAgainst, uint indexed choice, address indexed voter);
event _PollCreated(uint voteQuorum, uint commitEndDate, uint revealEndDate, uint indexed pollID, address indexed creator);
event _VotingRightsGranted(uint numTokens, address indexed voter);
event _VotingRightsWithdrawn(uint numTokens, address indexed voter);
event _TokensRescued(uint indexed pollID, address indexed voter);
// ============
// DATA STRUCTURES:
// ============
using AttributeStore for AttributeStore.Data;
using DLL for DLL.Data;
using SafeMath for uint;
struct Poll {
uint commitEndDate; /// expiration date of commit period for poll
uint revealEndDate; /// expiration date of reveal period for poll
uint voteQuorum; /// number of votes required for a proposal to pass
uint votesFor; /// tally of votes supporting proposal
uint votesAgainst; /// tally of votes countering proposal
mapping(address => bool) didCommit; /// indicates whether an address committed a vote for this poll
mapping(address => bool) didReveal; /// indicates whether an address revealed a vote for this poll
}
// ============
// STATE VARIABLES:
// ============
uint constant public INITIAL_POLL_NONCE = 0;
uint public pollNonce;
mapping(uint => Poll) public pollMap; // maps pollID to Poll struct
mapping(address => uint) public voteTokenBalance; // maps user's address to voteToken balance
mapping(address => DLL.Data) dllMap;
AttributeStore.Data store;
EIP20Interface public token;
/**
@dev Initializer. Can only be called once.
@param _token The address where the ERC20 token contract is deployed
*/
function init(address _token) public {
require(_token != 0 && address(token) == 0);
token = EIP20Interface(_token);
pollNonce = INITIAL_POLL_NONCE;
}
// ================
// TOKEN INTERFACE:
// ================
/**
@notice Loads _numTokens ERC20 tokens into the voting contract for one-to-one voting rights
@dev Assumes that msg.sender has approved voting contract to spend on their behalf
@param _numTokens The number of votingTokens desired in exchange for ERC20 tokens
*/
function requestVotingRights(uint _numTokens) public {
require(token.balanceOf(msg.sender) >= _numTokens);
voteTokenBalance[msg.sender] += _numTokens;
require(token.transferFrom(msg.sender, this, _numTokens));
emit _VotingRightsGranted(_numTokens, msg.sender);
}
/**
@notice Withdraw _numTokens ERC20 tokens from the voting contract, revoking these voting rights
@param _numTokens The number of ERC20 tokens desired in exchange for voting rights
*/
function withdrawVotingRights(uint _numTokens) external {
uint availableTokens = voteTokenBalance[msg.sender].sub(getLockedTokens(msg.sender));
require(availableTokens >= _numTokens);
voteTokenBalance[msg.sender] -= _numTokens;
require(token.transfer(msg.sender, _numTokens));
emit _VotingRightsWithdrawn(_numTokens, msg.sender);
}
/**
@dev Unlocks tokens locked in unrevealed vote where poll has ended
@param _pollID Integer identifier associated with the target poll
*/
function rescueTokens(uint _pollID) public {
require(isExpired(pollMap[_pollID].revealEndDate));
require(dllMap[msg.sender].contains(_pollID));
dllMap[msg.sender].remove(_pollID);
emit _TokensRescued(_pollID, msg.sender);
}
/**
@dev Unlocks tokens locked in unrevealed votes where polls have ended
@param _pollIDs Array of integer identifiers associated with the target polls
*/
function rescueTokensInMultiplePolls(uint[] _pollIDs) public {
// loop through arrays, rescuing tokens from all
for (uint i = 0; i < _pollIDs.length; i++) {
rescueTokens(_pollIDs[i]);
}
}
// =================
// VOTING INTERFACE:
// =================
/**
@notice Commits vote using hash of choice and secret salt to conceal vote until reveal
@param _pollID Integer identifier associated with target poll
@param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order)
@param _numTokens The number of tokens to be committed towards the target poll
@param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
*/
function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
require(commitPeriodActive(_pollID));
// if msg.sender doesn't have enough voting rights,
// request for enough voting rights
if (voteTokenBalance[msg.sender] < _numTokens) {
uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);
requestVotingRights(remainder);
}
// make sure msg.sender has enough voting rights
require(voteTokenBalance[msg.sender] >= _numTokens);
// prevent user from committing to zero node placeholder
require(_pollID != 0);
// prevent user from committing a secretHash of 0
require(_secretHash != 0);
// Check if _prevPollID exists in the user's DLL or if _prevPollID is 0
require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID));
uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);
// edge case: in-place update
if (nextPollID == _pollID) {
nextPollID = dllMap[msg.sender].getNext(_pollID);
}
require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));
dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);
bytes32 UUID = attrUUID(msg.sender, _pollID);
store.setAttribute(UUID, "numTokens", _numTokens);
store.setAttribute(UUID, "commitHash", uint(_secretHash));
pollMap[_pollID].didCommit[msg.sender] = true;
emit _VoteCommitted(_pollID, _numTokens, msg.sender);
}
/**
@notice Commits votes using hashes of choices and secret salts to conceal votes until reveal
@param _pollIDs Array of integer identifiers associated with target polls
@param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)
@param _numsTokens Array of numbers of tokens to be committed towards the target polls
@param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
*/
function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {
// make sure the array lengths are all the same
require(_pollIDs.length == _secretHashes.length);
require(_pollIDs.length == _numsTokens.length);
require(_pollIDs.length == _prevPollIDs.length);
// loop through arrays, committing each individual vote values
for (uint i = 0; i < _pollIDs.length; i++) {
commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]);
}
}
/**
@dev Compares previous and next poll's committed tokens for sorting purposes
@param _prevID Integer identifier associated with previous poll in sorted order
@param _nextID Integer identifier associated with next poll in sorted order
@param _voter Address of user to check DLL position for
@param _numTokens The number of tokens to be committed towards the poll (used for sorting)
@return valid Boolean indication of if the specified position maintains the sort
*/
function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) {
bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID));
// if next is zero node, _numTokens does not need to be greater
bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0);
return prevValid && nextValid;
}
/**
@notice Reveals vote with choice and secret salt used in generating commitHash to attribute committed tokens
@param _pollID Integer identifier associated with target poll
@param _voteOption Vote choice used to generate commitHash for associated poll
@param _salt Secret number used to generate commitHash for associated poll
*/
function revealVote(uint _pollID, uint _voteOption, uint _salt) public {
// Make sure the reveal period is active
require(revealPeriodActive(_pollID));
require(pollMap[_pollID].didCommit[msg.sender]); // make sure user has committed a vote for this poll
require(!pollMap[_pollID].didReveal[msg.sender]); // prevent user from revealing multiple times
require(keccak256(_voteOption, _salt) == getCommitHash(msg.sender, _pollID)); // compare resultant hash from inputs to original commitHash
uint numTokens = getNumTokens(msg.sender, _pollID);
if (_voteOption == 1) {// apply numTokens to appropriate poll choice
pollMap[_pollID].votesFor += numTokens;
} else {
pollMap[_pollID].votesAgainst += numTokens;
}
dllMap[msg.sender].remove(_pollID); // remove the node referring to this vote upon reveal
pollMap[_pollID].didReveal[msg.sender] = true;
emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender);
}
/**
@notice Reveals multiple votes with choices and secret salts used in generating commitHashes to attribute committed tokens
@param _pollIDs Array of integer identifiers associated with target polls
@param _voteOptions Array of vote choices used to generate commitHashes for associated polls
@param _salts Array of secret numbers used to generate commitHashes for associated polls
*/
function revealVotes(uint[] _pollIDs, uint[] _voteOptions, uint[] _salts) external {
// make sure the array lengths are all the same
require(_pollIDs.length == _voteOptions.length);
require(_pollIDs.length == _salts.length);
// loop through arrays, revealing each individual vote values
for (uint i = 0; i < _pollIDs.length; i++) {
revealVote(_pollIDs[i], _voteOptions[i], _salts[i]);
}
}
/**
@param _pollID Integer identifier associated with target poll
@param _salt Arbitrarily chosen integer used to generate secretHash
@return correctVotes Number of tokens voted for winning option
*/
function getNumPassingTokens(address _voter, uint _pollID, uint _salt) public constant returns (uint correctVotes) {
require(pollEnded(_pollID));
require(pollMap[_pollID].didReveal[_voter]);
uint winningChoice = isPassed(_pollID) ? 1 : 0;
bytes32 winnerHash = keccak256(winningChoice, _salt);
bytes32 commitHash = getCommitHash(_voter, _pollID);
require(winnerHash == commitHash);
return getNumTokens(_voter, _pollID);
}
// ==================
// POLLING INTERFACE:
// ==================
/**
@dev Initiates a poll with canonical configured parameters at pollID emitted by PollCreated event
@param _voteQuorum Type of majority (out of 100) that is necessary for poll to be successful
@param _commitDuration Length of desired commit period in seconds
@param _revealDuration Length of desired reveal period in seconds
*/
function startPoll(uint _voteQuorum, uint _commitDuration, uint _revealDuration) public returns (uint pollID) {
pollNonce = pollNonce + 1;
uint commitEndDate = block.timestamp.add(_commitDuration);
uint revealEndDate = commitEndDate.add(_revealDuration);
pollMap[pollNonce] = Poll({
voteQuorum: _voteQuorum,
commitEndDate: commitEndDate,
revealEndDate: revealEndDate,
votesFor: 0,
votesAgainst: 0
});
emit _PollCreated(_voteQuorum, commitEndDate, revealEndDate, pollNonce, msg.sender);
return pollNonce;
}
/**
@notice Determines if proposal has passed
@dev Check if votesFor out of totalVotes exceeds votesQuorum (requires pollEnded)
@param _pollID Integer identifier associated with target poll
*/
function isPassed(uint _pollID) constant public returns (bool passed) {
require(pollEnded(_pollID));
Poll memory poll = pollMap[_pollID];
return (100 * poll.votesFor) > (poll.voteQuorum * (poll.votesFor + poll.votesAgainst));
}
// ----------------
// POLLING HELPERS:
// ----------------
/**
@dev Gets the total winning votes for reward distribution purposes
@param _pollID Integer identifier associated with target poll
@return Total number of votes committed to the winning option for specified poll
*/
function getTotalNumberOfTokensForWinningOption(uint _pollID) constant public returns (uint numTokens) {
require(pollEnded(_pollID));
if (isPassed(_pollID))
return pollMap[_pollID].votesFor;
else
return pollMap[_pollID].votesAgainst;
}
/**
@notice Determines if poll is over
@dev Checks isExpired for specified poll's revealEndDate
@return Boolean indication of whether polling period is over
*/
function pollEnded(uint _pollID) constant public returns (bool ended) {
require(pollExists(_pollID));
return isExpired(pollMap[_pollID].revealEndDate);
}
/**
@notice Checks if the commit period is still active for the specified poll
@dev Checks isExpired for the specified poll's commitEndDate
@param _pollID Integer identifier associated with target poll
@return Boolean indication of isCommitPeriodActive for target poll
*/
function commitPeriodActive(uint _pollID) constant public returns (bool active) {
require(pollExists(_pollID));
return !isExpired(pollMap[_pollID].commitEndDate);
}
/**
@notice Checks if the reveal period is still active for the specified poll
@dev Checks isExpired for the specified poll's revealEndDate
@param _pollID Integer identifier associated with target poll
*/
function revealPeriodActive(uint _pollID) constant public returns (bool active) {
require(pollExists(_pollID));
return !isExpired(pollMap[_pollID].revealEndDate) && !commitPeriodActive(_pollID);
}
/**
@dev Checks if user has committed for specified poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Boolean indication of whether user has committed
*/
function didCommit(address _voter, uint _pollID) constant public returns (bool committed) {
require(pollExists(_pollID));
return pollMap[_pollID].didCommit[_voter];
}
/**
@dev Checks if user has revealed for specified poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Boolean indication of whether user has revealed
*/
function didReveal(address _voter, uint _pollID) constant public returns (bool revealed) {
require(pollExists(_pollID));
return pollMap[_pollID].didReveal[_voter];
}
/**
@dev Checks if a poll exists
@param _pollID The pollID whose existance is to be evaluated.
@return Boolean Indicates whether a poll exists for the provided pollID
*/
function pollExists(uint _pollID) constant public returns (bool exists) {
return (_pollID != 0 && _pollID <= pollNonce);
}
// ---------------------------
// DOUBLE-LINKED-LIST HELPERS:
// ---------------------------
/**
@dev Gets the bytes32 commitHash property of target poll
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Bytes32 hash property attached to target poll
*/
function getCommitHash(address _voter, uint _pollID) constant public returns (bytes32 commitHash) {
return bytes32(store.getAttribute(attrUUID(_voter, _pollID), "commitHash"));
}
/**
@dev Wrapper for getAttribute with attrName="numTokens"
@param _voter Address of user to check against
@param _pollID Integer identifier associated with target poll
@return Number of tokens committed to poll in sorted poll-linked-list
*/
function getNumTokens(address _voter, uint _pollID) constant public returns (uint numTokens) {
return store.getAttribute(attrUUID(_voter, _pollID), "numTokens");
}
/**
@dev Gets top element of sorted poll-linked-list
@param _voter Address of user to check against
@return Integer identifier to poll with maximum number of tokens committed to it
*/
function getLastNode(address _voter) constant public returns (uint pollID) {
return dllMap[_voter].getPrev(0);
}
/**
@dev Gets the numTokens property of getLastNode
@param _voter Address of user to check against
@return Maximum number of tokens committed in poll specified
*/
function getLockedTokens(address _voter) constant public returns (uint numTokens) {
return getNumTokens(_voter, getLastNode(_voter));
}
/*
@dev Takes the last node in the user's DLL and iterates backwards through the list searching
for a node with a value less than or equal to the provided _numTokens value. When such a node
is found, if the provided _pollID matches the found nodeID, this operation is an in-place
update. In that case, return the previous node of the node being updated. Otherwise return the
first node that was found with a value less than or equal to the provided _numTokens.
@param _voter The voter whose DLL will be searched
@param _numTokens The value for the numTokens attribute in the node to be inserted
@return the node which the propoded node should be inserted after
*/
function getInsertPointForNumTokens(address _voter, uint _numTokens, uint _pollID)
constant public returns (uint prevNode) {
// Get the last node in the list and the number of tokens in that node
uint nodeID = getLastNode(_voter);
uint tokensInNode = getNumTokens(_voter, nodeID);
// Iterate backwards through the list until reaching the root node
while(nodeID != 0) {
// Get the number of tokens in the current node
tokensInNode = getNumTokens(_voter, nodeID);
if(tokensInNode <= _numTokens) { // We found the insert point!
if(nodeID == _pollID) {
// This is an in-place update. Return the prev node of the node being updated
nodeID = dllMap[_voter].getPrev(nodeID);
}
// Return the insert point
return nodeID;
}
// We did not find the insert point. Continue iterating backwards through the list
nodeID = dllMap[_voter].getPrev(nodeID);
}
// The list is empty, or a smaller value than anything else in the list is being inserted
return nodeID;
}
// ----------------
// GENERAL HELPERS:
// ----------------
/**
@dev Checks if an expiration date has been reached
@param _terminationDate Integer timestamp of date to compare current timestamp with
@return expired Boolean indication of whether the terminationDate has passed
*/
function isExpired(uint _terminationDate) constant public returns (bool expired) {
return (block.timestamp > _terminationDate);
}
/**
@dev Generates an identifier which associates a user and a poll together
@param _pollID Integer identifier associated with target poll
@return UUID Hash which is deterministic from _user and _pollID
*/
function attrUUID(address _user, uint _pollID) public pure returns (bytes32 UUID) {
return keccak256(_user, _pollID);
}
}
// File: contracts/Parameterizer.sol
pragma solidity^0.4.11;
contract Parameterizer {
// ------
// EVENTS
// ------
event _ReparameterizationProposal(string name, uint value, bytes32 propID, uint deposit, uint appEndDate, address indexed proposer);
event _NewChallenge(bytes32 indexed propID, uint challengeID, uint commitEndDate, uint revealEndDate, address indexed challenger);
event _ProposalAccepted(bytes32 indexed propID, string name, uint value);
event _ProposalExpired(bytes32 indexed propID);
event _ChallengeSucceeded(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _ChallengeFailed(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _RewardClaimed(uint indexed challengeID, uint reward, address indexed voter);
// ------
// DATA STRUCTURES
// ------
using SafeMath for uint;
struct ParamProposal {
uint appExpiry;
uint challengeID;
uint deposit;
string name;
address owner;
uint processBy;
uint value;
}
struct Challenge {
uint rewardPool; // (remaining) pool of tokens distributed amongst winning voters
address challenger; // owner of Challenge
bool resolved; // indication of if challenge is resolved
uint stake; // number of tokens at risk for either party during challenge
uint winningTokens; // (remaining) amount of tokens used for voting by the winning side
mapping(address => bool) tokenClaims;
}
// ------
// STATE
// ------
mapping(bytes32 => uint) public params;
// maps challengeIDs to associated challenge data
mapping(uint => Challenge) public challenges;
// maps pollIDs to intended data change if poll passes
mapping(bytes32 => ParamProposal) public proposals;
// Global Variables
EIP20Interface public token;
PLCRVoting public voting;
uint public PROCESSBY = 604800; // 7 days
/**
@dev Initializer Can only be called once
@param _token The address where the ERC20 token contract is deployed
@param _plcr address of a PLCR voting contract for the provided token
@notice _parameters array of canonical parameters
*/
function init(
address _token,
address _plcr,
uint[] _parameters
) public {
require(_token != 0 && address(token) == 0);
require(_plcr != 0 && address(voting) == 0);
token = EIP20Interface(_token);
voting = PLCRVoting(_plcr);
// minimum deposit for listing to be whitelisted
set("minDeposit", _parameters[0]);
// minimum deposit to propose a reparameterization
set("pMinDeposit", _parameters[1]);
// period over which applicants wait to be whitelisted
set("applyStageLen", _parameters[2]);
// period over which reparmeterization proposals wait to be processed
set("pApplyStageLen", _parameters[3]);
// length of commit period for voting
set("commitStageLen", _parameters[4]);
// length of commit period for voting in parameterizer
set("pCommitStageLen", _parameters[5]);
// length of reveal period for voting
set("revealStageLen", _parameters[6]);
// length of reveal period for voting in parameterizer
set("pRevealStageLen", _parameters[7]);
// percentage of losing party's deposit distributed to winning party
set("dispensationPct", _parameters[8]);
// percentage of losing party's deposit distributed to winning party in parameterizer
set("pDispensationPct", _parameters[9]);
// type of majority out of 100 necessary for candidate success
set("voteQuorum", _parameters[10]);
// type of majority out of 100 necessary for proposal success in parameterizer
set("pVoteQuorum", _parameters[11]);
}
// -----------------------
// TOKEN HOLDER INTERFACE
// -----------------------
/**
@notice propose a reparamaterization of the key _name's value to _value.
@param _name the name of the proposed param to be set
@param _value the proposed value to set the param to be set
*/
function proposeReparameterization(string _name, uint _value) public returns (bytes32) {
uint deposit = get("pMinDeposit");
bytes32 propID = keccak256(_name, _value);
if (keccak256(_name) == keccak256("dispensationPct") ||
keccak256(_name) == keccak256("pDispensationPct")) {
require(_value <= 100);
}
require(!propExists(propID)); // Forbid duplicate proposals
require(get(_name) != _value); // Forbid NOOP reparameterizations
// attach name and value to pollID
proposals[propID] = ParamProposal({
appExpiry: now.add(get("pApplyStageLen")),
challengeID: 0,
deposit: deposit,
name: _name,
owner: msg.sender,
processBy: now.add(get("pApplyStageLen"))
.add(get("pCommitStageLen"))
.add(get("pRevealStageLen"))
.add(PROCESSBY),
value: _value
});
require(token.transferFrom(msg.sender, this, deposit)); // escrow tokens (deposit amt)
emit _ReparameterizationProposal(_name, _value, propID, deposit, proposals[propID].appExpiry, msg.sender);
return propID;
}
/**
@notice challenge the provided proposal ID, and put tokens at stake to do so.
@param _propID the proposal ID to challenge
*/
function challengeReparameterization(bytes32 _propID) public returns (uint challengeID) {
ParamProposal memory prop = proposals[_propID];
uint deposit = prop.deposit;
require(propExists(_propID) && prop.challengeID == 0);
//start poll
uint pollID = voting.startPoll(
get("pVoteQuorum"),
get("pCommitStageLen"),
get("pRevealStageLen")
);
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: SafeMath.sub(100, get("pDispensationPct")).mul(deposit).div(100),
stake: deposit,
resolved: false,
winningTokens: 0
});
proposals[_propID].challengeID = pollID; // update listing to store most recent challenge
//take tokens from challenger
require(token.transferFrom(msg.sender, this, deposit));
var (commitEndDate, revealEndDate,) = voting.pollMap(pollID);
emit _NewChallenge(_propID, pollID, commitEndDate, revealEndDate, msg.sender);
return pollID;
}
/**
@notice for the provided proposal ID, set it, resolve its challenge, or delete it depending on whether it can be set, has a challenge which can be resolved, or if its "process by" date has passed
@param _propID the proposal ID to make a determination and state transition for
*/
function processProposal(bytes32 _propID) public {
ParamProposal storage prop = proposals[_propID];
address propOwner = prop.owner;
uint propDeposit = prop.deposit;
// Before any token transfers, deleting the proposal will ensure that if reentrancy occurs the
// prop.owner and prop.deposit will be 0, thereby preventing theft
if (canBeSet(_propID)) {
// There is no challenge against the proposal. The processBy date for the proposal has not
// passed, but the proposal's appExpirty date has passed.
set(prop.name, prop.value);
emit _ProposalAccepted(_propID, prop.name, prop.value);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
} else if (challengeCanBeResolved(_propID)) {
// There is a challenge against the proposal.
resolveChallenge(_propID);
} else if (now > prop.processBy) {
// There is no challenge against the proposal, but the processBy date has passed.
emit _ProposalExpired(_propID);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
} else {
// There is no challenge against the proposal, and neither the appExpiry date nor the
// processBy date has passed.
revert();
}
assert(get("dispensationPct") <= 100);
assert(get("pDispensationPct") <= 100);
// verify that future proposal appExpiry and processBy times will not overflow
now.add(get("pApplyStageLen"))
.add(get("pCommitStageLen"))
.add(get("pRevealStageLen"))
.add(PROCESSBY);
delete proposals[_propID];
}
/**
@notice Claim the tokens owed for the msg.sender in the provided challenge
@param _challengeID the challenge ID to claim tokens for
@param _salt the salt used to vote in the challenge being withdrawn for
*/
function claimReward(uint _challengeID, uint _salt) public {
// ensure voter has not already claimed tokens and challenge results have been processed
require(challenges[_challengeID].tokenClaims[msg.sender] == false);
require(challenges[_challengeID].resolved == true);
uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
// subtract voter's information to preserve the participation ratios of other voters
// compared to the remaining pool of rewards
challenges[_challengeID].winningTokens -= voterTokens;
challenges[_challengeID].rewardPool -= reward;
// ensures a voter cannot claim tokens again
challenges[_challengeID].tokenClaims[msg.sender] = true;
emit _RewardClaimed(_challengeID, reward, msg.sender);
require(token.transfer(msg.sender, reward));
}
/**
@dev Called by a voter to claim their rewards for each completed vote.
Someone must call updateStatus() before this can be called.
@param _challengeIDs The PLCR pollIDs of the challenges rewards are being claimed for
@param _salts The salts of a voter's commit hashes in the given polls
*/
function claimRewards(uint[] _challengeIDs, uint[] _salts) public {
// make sure the array lengths are the same
require(_challengeIDs.length == _salts.length);
// loop through arrays, claiming each individual vote reward
for (uint i = 0; i < _challengeIDs.length; i++) {
claimReward(_challengeIDs[i], _salts[i]);
}
}
// --------
// GETTERS
// --------
/**
@dev Calculates the provided voter's token reward for the given poll.
@param _voter The address of the voter whose reward balance is to be returned
@param _challengeID The ID of the challenge the voter's reward is being calculated for
@param _salt The salt of the voter's commit hash in the given poll
@return The uint indicating the voter's reward
*/
function voterReward(address _voter, uint _challengeID, uint _salt)
public view returns (uint) {
uint winningTokens = challenges[_challengeID].winningTokens;
uint rewardPool = challenges[_challengeID].rewardPool;
uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt);
return (voterTokens * rewardPool) / winningTokens;
}
/**
@notice Determines whether a proposal passed its application stage without a challenge
@param _propID The proposal ID for which to determine whether its application stage passed without a challenge
*/
function canBeSet(bytes32 _propID) view public returns (bool) {
ParamProposal memory prop = proposals[_propID];
return (now > prop.appExpiry && now < prop.processBy && prop.challengeID == 0);
}
/**
@notice Determines whether a proposal exists for the provided proposal ID
@param _propID The proposal ID whose existance is to be determined
*/
function propExists(bytes32 _propID) view public returns (bool) {
return proposals[_propID].processBy > 0;
}
/**
@notice Determines whether the provided proposal ID has a challenge which can be resolved
@param _propID The proposal ID whose challenge to inspect
*/
function challengeCanBeResolved(bytes32 _propID) view public returns (bool) {
ParamProposal memory prop = proposals[_propID];
Challenge memory challenge = challenges[prop.challengeID];
return (prop.challengeID > 0 && challenge.resolved == false && voting.pollEnded(prop.challengeID));
}
/**
@notice Determines the number of tokens to awarded to the winning party in a challenge
@param _challengeID The challengeID to determine a reward for
*/
function challengeWinnerReward(uint _challengeID) public view returns (uint) {
if(voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {
// Edge case, nobody voted, give all tokens to the challenger.
return 2 * challenges[_challengeID].stake;
}
return (2 * challenges[_challengeID].stake) - challenges[_challengeID].rewardPool;
}
/**
@notice gets the parameter keyed by the provided name value from the params mapping
@param _name the key whose value is to be determined
*/
function get(string _name) public view returns (uint value) {
return params[keccak256(_name)];
}
/**
@dev Getter for Challenge tokenClaims mappings
@param _challengeID The challengeID to query
@param _voter The voter whose claim status to query for the provided challengeID
*/
function tokenClaims(uint _challengeID, address _voter) public view returns (bool) {
return challenges[_challengeID].tokenClaims[_voter];
}
// ----------------
// PRIVATE FUNCTIONS
// ----------------
/**
@dev resolves a challenge for the provided _propID. It must be checked in advance whether the _propID has a challenge on it
@param _propID the proposal ID whose challenge is to be resolved.
*/
function resolveChallenge(bytes32 _propID) private {
ParamProposal memory prop = proposals[_propID];
Challenge storage challenge = challenges[prop.challengeID];
// winner gets back their full staked deposit, and dispensationPct*loser's stake
uint reward = challengeWinnerReward(prop.challengeID);
challenge.winningTokens = voting.getTotalNumberOfTokensForWinningOption(prop.challengeID);
challenge.resolved = true;
if (voting.isPassed(prop.challengeID)) { // The challenge failed
if(prop.processBy > now) {
set(prop.name, prop.value);
}
emit _ChallengeFailed(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);
require(token.transfer(prop.owner, reward));
}
else { // The challenge succeeded or nobody voted
emit _ChallengeSucceeded(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);
require(token.transfer(challenges[prop.challengeID].challenger, reward));
}
}
/**
@dev sets the param keted by the provided name to the provided value
@param _name the name of the param to be set
@param _value the value to set the param to be set
*/
function set(string _name, uint _value) private {
params[keccak256(_name)] = _value;
}
}
// File: plcr-revival/ProxyFactory.sol
/***
* Shoutouts:
*
* Bytecode origin https://www.reddit.com/r/ethereum/comments/6ic49q/any_assembly_programmers_willing_to_write_a/dj5ceuw/
* Modified version of Vitalik's https://www.reddit.com/r/ethereum/comments/6c1jui/delegatecall_forwarders_how_to_save_5098_on/
* Credits to Jorge Izquierdo (@izqui) for coming up with this design here: https://gist.github.com/izqui/7f904443e6d19c1ab52ec7f5ad46b3a8
* Credits to Stefan George (@Georgi87) for inspiration for many of the improvements from Gnosis Safe: https://github.com/gnosis/gnosis-safe-contracts
*
* This version has many improvements over the original @izqui's library like using REVERT instead of THROWing on failed calls.
* It also implements the awesome design pattern for initializing code as seen in Gnosis Safe Factory: https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/ProxyFactory.sol
* but unlike this last one it doesn't require that you waste storage on both the proxy and the proxied contracts (v. https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/Proxy.sol#L8 & https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/GnosisSafe.sol#L14)
*
*
* v0.0.2
* The proxy is now only 60 bytes long in total. Constructor included.
* No functionalities were added. The change was just to make the proxy leaner.
*
* v0.0.3
* Thanks @dacarley for noticing the incorrect check for the subsequent call to the proxy. 🙌
* Note: I'm creating a new version of this that doesn't need that one call.
* Will add tests and put this in its own repository soon™.
*
* v0.0.4
* All the merit in this fix + update of the factory is @dacarley 's. 🙌
* Thank you! 😄
*
* Potential updates can be found at https://gist.github.com/GNSPS/ba7b88565c947cfd781d44cf469c2ddb
*
***/
pragma solidity ^0.4.19;
/* solhint-disable no-inline-assembly, indent, state-visibility, avoid-low-level-calls */
contract ProxyFactory {
event ProxyDeployed(address proxyAddress, address targetAddress);
event ProxiesDeployed(address[] proxyAddresses, address targetAddress);
function createManyProxies(uint256 _count, address _target, bytes _data)
public
{
address[] memory proxyAddresses = new address[](_count);
for (uint256 i = 0; i < _count; ++i) {
proxyAddresses[i] = createProxyImpl(_target, _data);
}
ProxiesDeployed(proxyAddresses, _target);
}
function createProxy(address _target, bytes _data)
public
returns (address proxyContract)
{
proxyContract = createProxyImpl(_target, _data);
ProxyDeployed(proxyContract, _target);
}
function createProxyImpl(address _target, bytes _data)
internal
returns (address proxyContract)
{
assembly {
let contractCode := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(add(contractCode, 0x0b), _target) // Add target address, with a 11 bytes [i.e. 23 - (32 - 20)] offset to later accomodate first part of the bytecode
mstore(sub(contractCode, 0x09), 0x000000000000000000603160008181600b9039f3600080808080368092803773) // First part of the bytecode, shifted left by 9 bytes, overwrites left padding of target address
mstore(add(contractCode, 0x2b), 0x5af43d828181803e808314602f57f35bfd000000000000000000000000000000) // Final part of bytecode, offset by 43 bytes
proxyContract := create(0, contractCode, 60) // total length 60 bytes
if iszero(extcodesize(proxyContract)) {
revert(0, 0)
}
// check if the _data.length > 0 and if it is forward it to the newly created contract
let dataLength := mload(_data)
if iszero(iszero(dataLength)) {
if iszero(call(gas, proxyContract, 0, add(_data, 0x20), dataLength, 0, 0)) {
revert(0, 0)
}
}
}
}
}
// File: tokens/eip20/EIP20.sol
/*
Implements EIP20 token standard: https://github.com/ethereum/EIPs/issues/20
.*/
pragma solidity ^0.4.8;
contract EIP20 is EIP20Interface {
uint256 constant MAX_UINT256 = 2**256 - 1;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
function EIP20(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
// File: plcr-revival/PLCRFactory.sol
contract PLCRFactory {
event newPLCR(address creator, EIP20 token, PLCRVoting plcr);
ProxyFactory public proxyFactory;
PLCRVoting public canonizedPLCR;
/// @dev constructor deploys a new canonical PLCRVoting contract and a proxyFactory.
constructor() {
canonizedPLCR = new PLCRVoting();
proxyFactory = new ProxyFactory();
}
/*
@dev deploys and initializes a new PLCRVoting contract that consumes a token at an address
supplied by the user.
@param _token an EIP20 token to be consumed by the new PLCR contract
*/
function newPLCRBYOToken(EIP20 _token) public returns (PLCRVoting) {
PLCRVoting plcr = PLCRVoting(proxyFactory.createProxy(canonizedPLCR, ""));
plcr.init(_token);
emit newPLCR(msg.sender, _token, plcr);
return plcr;
}
/*
@dev deploys and initializes a new PLCRVoting contract and an EIP20 to be consumed by the PLCR's
initializer.
@param _supply the total number of tokens to mint in the EIP20 contract
@param _name the name of the new EIP20 token
@param _decimals the decimal precision to be used in rendering balances in the EIP20 token
@param _symbol the symbol of the new EIP20 token
*/
function newPLCRWithToken(
uint _supply,
string _name,
uint8 _decimals,
string _symbol
) public returns (PLCRVoting) {
// Create a new token and give all the tokens to the PLCR creator
EIP20 token = new EIP20(_supply, _name, _decimals, _symbol);
token.transfer(msg.sender, _supply);
// Create and initialize a new PLCR contract
PLCRVoting plcr = PLCRVoting(proxyFactory.createProxy(canonizedPLCR, ""));
plcr.init(token);
emit newPLCR(msg.sender, token, plcr);
return plcr;
}
}
// File: contracts/ParameterizerFactory.sol
contract ParameterizerFactory {
event NewParameterizer(address creator, address token, address plcr, Parameterizer parameterizer);
PLCRFactory public plcrFactory;
ProxyFactory public proxyFactory;
Parameterizer public canonizedParameterizer;
/// @dev constructor deploys a new canonical Parameterizer contract and a proxyFactory.
constructor(PLCRFactory _plcrFactory) public {
plcrFactory = _plcrFactory;
proxyFactory = plcrFactory.proxyFactory();
canonizedParameterizer = new Parameterizer();
}
/*
@dev deploys and initializes a new Parameterizer contract that consumes a token at an address
supplied by the user.
@param _token an EIP20 token to be consumed by the new Parameterizer contract
@param _plcr a PLCR voting contract to be consumed by the new Parameterizer contract
@param _parameters array of canonical parameters
*/
function newParameterizerBYOToken(
EIP20 _token,
uint[] _parameters
) public returns (Parameterizer) {
PLCRVoting plcr = plcrFactory.newPLCRBYOToken(_token);
Parameterizer parameterizer = Parameterizer(proxyFactory.createProxy(canonizedParameterizer, ""));
parameterizer.init(
_token,
plcr,
_parameters
);
emit NewParameterizer(msg.sender, _token, plcr, parameterizer);
return parameterizer;
}
/*
@dev deploys and initializes new EIP20, PLCRVoting, and Parameterizer contracts
@param _supply the total number of tokens to mint in the EIP20 contract
@param _name the name of the new EIP20 token
@param _decimals the decimal precision to be used in rendering balances in the EIP20 token
@param _symbol the symbol of the new EIP20 token
@param _parameters array of canonical parameters
*/
function newParameterizerWithToken(
uint _supply,
string _name,
uint8 _decimals,
string _symbol,
uint[] _parameters
) public returns (Parameterizer) {
// Creates a new EIP20 token & transfers the supply to creator (msg.sender)
// Deploys & initializes a new PLCRVoting contract
PLCRVoting plcr = plcrFactory.newPLCRWithToken(_supply, _name, _decimals, _symbol);
EIP20 token = EIP20(plcr.token());
token.transfer(msg.sender, _supply);
// Create & initialize a new Parameterizer contract
Parameterizer parameterizer = Parameterizer(proxyFactory.createProxy(canonizedParameterizer, ""));
parameterizer.init(
token,
plcr,
_parameters
);
emit NewParameterizer(msg.sender, token, plcr, parameterizer);
return parameterizer;
}
} | / ============ EVENTS: ============ ============ DATA STRUCTURES: ============ | contract PLCRVoting {
event _VoteCommitted(uint indexed pollID, uint numTokens, address indexed voter);
event _VoteRevealed(uint indexed pollID, uint numTokens, uint votesFor, uint votesAgainst, uint indexed choice, address indexed voter);
event _PollCreated(uint voteQuorum, uint commitEndDate, uint revealEndDate, uint indexed pollID, address indexed creator);
event _VotingRightsGranted(uint numTokens, address indexed voter);
event _VotingRightsWithdrawn(uint numTokens, address indexed voter);
event _TokensRescued(uint indexed pollID, address indexed voter);
using AttributeStore for AttributeStore.Data;
using DLL for DLL.Data;
using SafeMath for uint;
@title Partial-Lock-Commit-Reveal Voting scheme with ERC20 tokens
struct Poll {
}
uint constant public INITIAL_POLL_NONCE = 0;
uint public pollNonce;
mapping(address => DLL.Data) dllMap;
AttributeStore.Data store;
EIP20Interface public token;
@param _token The address where the ERC20 token contract is deployed
@dev Initializer. Can only be called once.
function init(address _token) public {
require(_token != 0 && address(token) == 0);
token = EIP20Interface(_token);
pollNonce = INITIAL_POLL_NONCE;
}
@dev Assumes that msg.sender has approved voting contract to spend on their behalf
@param _numTokens The number of votingTokens desired in exchange for ERC20 tokens
@notice Loads _numTokens ERC20 tokens into the voting contract for one-to-one voting rights
function requestVotingRights(uint _numTokens) public {
require(token.balanceOf(msg.sender) >= _numTokens);
voteTokenBalance[msg.sender] += _numTokens;
require(token.transferFrom(msg.sender, this, _numTokens));
emit _VotingRightsGranted(_numTokens, msg.sender);
}
@param _numTokens The number of ERC20 tokens desired in exchange for voting rights
@notice Withdraw _numTokens ERC20 tokens from the voting contract, revoking these voting rights
function withdrawVotingRights(uint _numTokens) external {
uint availableTokens = voteTokenBalance[msg.sender].sub(getLockedTokens(msg.sender));
require(availableTokens >= _numTokens);
voteTokenBalance[msg.sender] -= _numTokens;
require(token.transfer(msg.sender, _numTokens));
emit _VotingRightsWithdrawn(_numTokens, msg.sender);
}
@param _pollID Integer identifier associated with the target poll
@dev Unlocks tokens locked in unrevealed vote where poll has ended
function rescueTokens(uint _pollID) public {
require(isExpired(pollMap[_pollID].revealEndDate));
require(dllMap[msg.sender].contains(_pollID));
dllMap[msg.sender].remove(_pollID);
emit _TokensRescued(_pollID, msg.sender);
}
@param _pollIDs Array of integer identifiers associated with the target polls
@dev Unlocks tokens locked in unrevealed votes where polls have ended
function rescueTokensInMultiplePolls(uint[] _pollIDs) public {
for (uint i = 0; i < _pollIDs.length; i++) {
rescueTokens(_pollIDs[i]);
}
}
@param _pollID Integer identifier associated with target poll
@param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order)
@param _numTokens The number of tokens to be committed towards the target poll
@param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
function rescueTokensInMultiplePolls(uint[] _pollIDs) public {
for (uint i = 0; i < _pollIDs.length; i++) {
rescueTokens(_pollIDs[i]);
}
}
@param _pollID Integer identifier associated with target poll
@param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order)
@param _numTokens The number of tokens to be committed towards the target poll
@param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
@notice Commits vote using hash of choice and secret salt to conceal vote until reveal
function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
require(commitPeriodActive(_pollID));
if (voteTokenBalance[msg.sender] < _numTokens) {
uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);
requestVotingRights(remainder);
}
uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);
if (nextPollID == _pollID) {
nextPollID = dllMap[msg.sender].getNext(_pollID);
}
require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));
dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);
bytes32 UUID = attrUUID(msg.sender, _pollID);
store.setAttribute(UUID, "numTokens", _numTokens);
store.setAttribute(UUID, "commitHash", uint(_secretHash));
pollMap[_pollID].didCommit[msg.sender] = true;
emit _VoteCommitted(_pollID, _numTokens, msg.sender);
}
@param _pollIDs Array of integer identifiers associated with target polls
@param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)
@param _numsTokens Array of numbers of tokens to be committed towards the target polls
@param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
require(commitPeriodActive(_pollID));
if (voteTokenBalance[msg.sender] < _numTokens) {
uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);
requestVotingRights(remainder);
}
uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);
if (nextPollID == _pollID) {
nextPollID = dllMap[msg.sender].getNext(_pollID);
}
require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));
dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);
bytes32 UUID = attrUUID(msg.sender, _pollID);
store.setAttribute(UUID, "numTokens", _numTokens);
store.setAttribute(UUID, "commitHash", uint(_secretHash));
pollMap[_pollID].didCommit[msg.sender] = true;
emit _VoteCommitted(_pollID, _numTokens, msg.sender);
}
@param _pollIDs Array of integer identifiers associated with target polls
@param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)
@param _numsTokens Array of numbers of tokens to be committed towards the target polls
@param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
require(voteTokenBalance[msg.sender] >= _numTokens);
require(_pollID != 0);
require(_secretHash != 0);
require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID));
function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
require(commitPeriodActive(_pollID));
if (voteTokenBalance[msg.sender] < _numTokens) {
uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);
requestVotingRights(remainder);
}
uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);
if (nextPollID == _pollID) {
nextPollID = dllMap[msg.sender].getNext(_pollID);
}
require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));
dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);
bytes32 UUID = attrUUID(msg.sender, _pollID);
store.setAttribute(UUID, "numTokens", _numTokens);
store.setAttribute(UUID, "commitHash", uint(_secretHash));
pollMap[_pollID].didCommit[msg.sender] = true;
emit _VoteCommitted(_pollID, _numTokens, msg.sender);
}
@param _pollIDs Array of integer identifiers associated with target polls
@param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)
@param _numsTokens Array of numbers of tokens to be committed towards the target polls
@param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
@notice Commits votes using hashes of choices and secret salts to conceal votes until reveal
function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {
require(_pollIDs.length == _secretHashes.length);
require(_pollIDs.length == _numsTokens.length);
require(_pollIDs.length == _prevPollIDs.length);
for (uint i = 0; i < _pollIDs.length; i++) {
commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]);
}
}
@param _prevID Integer identifier associated with previous poll in sorted order
@param _nextID Integer identifier associated with next poll in sorted order
@param _voter Address of user to check DLL position for
@param _numTokens The number of tokens to be committed towards the poll (used for sorting)
@return valid Boolean indication of if the specified position maintains the sort
function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {
require(_pollIDs.length == _secretHashes.length);
require(_pollIDs.length == _numsTokens.length);
require(_pollIDs.length == _prevPollIDs.length);
for (uint i = 0; i < _pollIDs.length; i++) {
commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]);
}
}
@param _prevID Integer identifier associated with previous poll in sorted order
@param _nextID Integer identifier associated with next poll in sorted order
@param _voter Address of user to check DLL position for
@param _numTokens The number of tokens to be committed towards the poll (used for sorting)
@return valid Boolean indication of if the specified position maintains the sort
@dev Compares previous and next poll's committed tokens for sorting purposes
function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) {
bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID));
bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0);
return prevValid && nextValid;
}
@param _pollID Integer identifier associated with target poll
@param _voteOption Vote choice used to generate commitHash for associated poll
@param _salt Secret number used to generate commitHash for associated poll
@notice Reveals vote with choice and secret salt used in generating commitHash to attribute committed tokens
function revealVote(uint _pollID, uint _voteOption, uint _salt) public {
require(revealPeriodActive(_pollID));
uint numTokens = getNumTokens(msg.sender, _pollID);
pollMap[_pollID].votesFor += numTokens;
pollMap[_pollID].votesAgainst += numTokens;
}
pollMap[_pollID].didReveal[msg.sender] = true;
emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender);
} else {
}
| 502,055 | [
1,
19,
422,
1432,
631,
9964,
55,
30,
422,
1432,
631,
422,
1432,
631,
8730,
7128,
9749,
4830,
55,
30,
422,
1432,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
22443,
5093,
58,
17128,
288,
203,
203,
203,
565,
871,
389,
19338,
27813,
12,
11890,
8808,
7672,
734,
16,
2254,
818,
5157,
16,
1758,
8808,
331,
20005,
1769,
203,
565,
871,
389,
19338,
426,
537,
18931,
12,
11890,
8808,
7672,
734,
16,
2254,
818,
5157,
16,
2254,
19588,
1290,
16,
2254,
19588,
23530,
334,
16,
2254,
8808,
6023,
16,
1758,
8808,
331,
20005,
1769,
203,
565,
871,
389,
19085,
6119,
12,
11890,
12501,
31488,
16,
2254,
3294,
24640,
16,
2254,
283,
24293,
24640,
16,
2254,
8808,
7672,
734,
16,
1758,
8808,
11784,
1769,
203,
565,
871,
389,
58,
17128,
18464,
14570,
12,
11890,
818,
5157,
16,
1758,
8808,
331,
20005,
1769,
203,
565,
871,
389,
58,
17128,
18464,
1190,
9446,
82,
12,
11890,
818,
5157,
16,
1758,
8808,
331,
20005,
1769,
203,
565,
871,
389,
5157,
607,
71,
5957,
12,
11890,
8808,
7672,
734,
16,
1758,
8808,
331,
20005,
1769,
203,
203,
203,
565,
1450,
3601,
2257,
364,
3601,
2257,
18,
751,
31,
203,
565,
1450,
463,
4503,
364,
463,
4503,
18,
751,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
203,
36,
2649,
19060,
17,
2531,
17,
5580,
17,
426,
24293,
776,
17128,
4355,
598,
4232,
39,
3462,
2430,
203,
565,
1958,
19160,
288,
203,
565,
289,
203,
203,
565,
2254,
5381,
1071,
28226,
67,
14232,
48,
67,
3993,
1441,
273,
374,
31,
203,
565,
2254,
1071,
7672,
13611,
31,
203,
203,
203,
565,
2874,
12,
2867,
516,
463,
4503,
18,
751,
13,
302,
2906,
863,
31,
203,
565,
2
] |
pragma solidity ^0.4.13;
/**
* @title SafeMath
* Math operations with safety checks
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title Ownable
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
*/
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Haltable
* Abstract contract that allows children to implement an
* emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode.
*/
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
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;
}
}
/**
* @title ERC20
* ERC20 interface
*/
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value);
function transferFrom(address _from, address _to, uint _value);
function approve(address _spender, uint _value);
function allowance(address _owner, address _spender) constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title StandardToken
* Standard ERC20-compliant token
* https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/**
* fix for ERC20 short address attack
*/
modifier onlyPayloadSize(uint256 size) {
require(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
function approve(address _spender, uint _value) {
/**
* Allowed amount should be first set to 0
* by calling approve(_spender, 0) in order to avoid this:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*/
require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract LiveStarsToken is StandardToken {
string public name = "Live Stars Token";
string public symbol = "LIVE";
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = 200000000 * 1 ether;
/**
* All tokens are allocated to creator.
*/
function LiveStarsToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
contract LiveStarsTokenPresale is Haltable {
using SafeMath for uint;
string public name = "Live Stars Token Presale";
LiveStarsToken public token;
address public beneficiary;
uint public hardCap;
uint public collected;
uint public price;
uint public purchaseLimit;
uint public currentBalance;
uint public tokensSold = 0;
uint public investorCount = 0;
uint public startTime;
uint public endTime;
event GoalReached(uint amountRaised);
event NewContribution(address indexed holder, uint256 tokenAmount, uint256 etherAmount);
modifier onlyAfter(uint time) {
require(now >= time);
_;
}
modifier onlyBefore(uint time) {
require(now <= time);
_;
}
function LiveStarsTokenPresale(
uint _hardCapUSD,
address _token,
address _beneficiary,
uint _totalTokens,
uint _priceETH,
uint _purchaseLimitUSD,
uint _startTime,
uint _duration
) {
hardCap = _hardCapUSD * 1 ether / _priceETH;
price = _totalTokens * 1 ether / hardCap;
purchaseLimit = _purchaseLimitUSD * 1 ether / _priceETH * price;
token = LiveStarsToken(_token);
beneficiary = _beneficiary;
startTime = _startTime;
endTime = _startTime + _duration * 1 hours;
}
function () payable stopInEmergency{
require(msg.value >= 0.01 * 1 ether);
doPurchase(msg.sender);
}
function withdraw() onlyOwner {
require(beneficiary.send(currentBalance));
currentBalance = 0;
}
function finalWithdraw() onlyOwner onlyAfter(endTime) {
if (currentBalance > 0) {
require(beneficiary.send(currentBalance));
}
token.transfer(beneficiary, token.balanceOf(this));
}
function doPurchase(address _owner) private onlyAfter(startTime) onlyBefore(endTime) {
assert(collected.add(msg.value) <= hardCap);
uint tokens = msg.value * price;
assert(token.balanceOf(msg.sender) + tokens <= purchaseLimit);
if (token.balanceOf(msg.sender) == 0) investorCount++;
collected = collected.add(msg.value);
currentBalance = currentBalance.add(msg.value);
token.transfer(msg.sender, tokens);
tokensSold = tokensSold.add(tokens);
NewContribution(_owner, tokens, msg.value);
if (collected == hardCap) {
GoalReached(hardCap);
}
}
} | * All tokens are allocated to creator./ | function LiveStarsToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
| 15,883,018 | [
1,
1595,
2430,
854,
11977,
358,
11784,
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,
21559,
510,
5913,
1345,
1435,
288,
203,
3639,
2078,
3088,
1283,
273,
28226,
67,
13272,
23893,
31,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
28226,
67,
13272,
23893,
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
] |
/**
* @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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of 'user permissions'.
*/
/// @title Ownable
/// @author Applicature
/// @notice helper mixed to other contracts to link contract on an owner
/// @dev Base class
contract Ownable {
//Variables
address public owner;
address public newOwner;
// Modifiers
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @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));
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
/// @title OpenZeppelinERC20
/// @author Applicature
/// @notice Open Zeppelin implementation of standart ERC20
/// @dev Base class
contract OpenZeppelinERC20 is StandardToken, Ownable {
using SafeMath for uint256;
uint8 public decimals;
string public name;
string public symbol;
string public standard;
constructor(
uint256 _totalSupply,
string _tokenName,
uint8 _decimals,
string _tokenSymbol,
bool _transferAllSupplyToOwner
) public {
standard = 'ERC20 0.1';
totalSupply_ = _totalSupply;
if (_transferAllSupplyToOwner) {
balances[msg.sender] = _totalSupply;
} else {
balances[this] = _totalSupply;
}
name = _tokenName;
// Set the name for display purposes
symbol = _tokenSymbol;
// Set the symbol for display purposes
decimals = _decimals;
}
}
/// @title MintableToken
/// @author Applicature
/// @notice allow to mint tokens
/// @dev Base class
contract MintableToken is BasicToken, Ownable {
using SafeMath for uint256;
uint256 public maxSupply;
bool public allowedMinting;
mapping(address => bool) public mintingAgents;
mapping(address => bool) public stateChangeAgents;
event Mint(address indexed holder, uint256 tokens);
modifier onlyMintingAgents () {
require(mintingAgents[msg.sender]);
_;
}
modifier onlyStateChangeAgents () {
require(stateChangeAgents[msg.sender]);
_;
}
constructor(uint256 _maxSupply, uint256 _mintedSupply, bool _allowedMinting) public {
maxSupply = _maxSupply;
totalSupply_ = totalSupply_.add(_mintedSupply);
allowedMinting = _allowedMinting;
mintingAgents[msg.sender] = true;
}
/// @notice allow to mint tokens
function mint(address _holder, uint256 _tokens) public onlyMintingAgents() {
require(allowedMinting == true && totalSupply_.add(_tokens) <= maxSupply);
totalSupply_ = totalSupply_.add(_tokens);
balances[_holder] = balances[_holder].add(_tokens);
if (totalSupply_ == maxSupply) {
allowedMinting = false;
}
emit Transfer(address(0), _holder, _tokens);
emit Mint(_holder, _tokens);
}
/// @notice update allowedMinting flat
function disableMinting() public onlyStateChangeAgents() {
allowedMinting = false;
}
/// @notice update minting agent
function updateMintingAgent(address _agent, bool _status) public onlyOwner {
mintingAgents[_agent] = _status;
}
/// @notice update state change agent
function updateStateChangeAgent(address _agent, bool _status) public onlyOwner {
stateChangeAgents[_agent] = _status;
}
/// @return available tokens
function availableTokens() public view returns (uint256 tokens) {
return maxSupply.sub(totalSupply_);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/// @title MintableBurnableToken
/// @author Applicature
/// @notice helper mixed to other contracts to burn tokens
/// @dev implementation
contract MintableBurnableToken is MintableToken, BurnableToken {
mapping (address => bool) public burnAgents;
modifier onlyBurnAgents () {
require(burnAgents[msg.sender]);
_;
}
constructor(
uint256 _maxSupply,
uint256 _mintedSupply,
bool _allowedMinting
) public MintableToken(
_maxSupply,
_mintedSupply,
_allowedMinting
) {
}
/// @notice update burn agent
function updateBurnAgent(address _agent, bool _status) public onlyOwner {
burnAgents[_agent] = _status;
}
function burnByAgent(address _holder, uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) {
if (_tokensToBurn == 0) {
_tokensToBurn = balances[_holder];
}
_burn(_holder, _tokensToBurn);
return _tokensToBurn;
}
function _burn(address _who, uint256 _value) internal {
super._burn(_who, _value);
maxSupply = maxSupply.sub(_value);
}
}
/// @title TimeLocked
/// @author Applicature
/// @notice helper mixed to other contracts to lock contract on a timestamp
/// @dev Base class
contract TimeLocked {
uint256 public time;
mapping(address => bool) public excludedAddresses;
modifier isTimeLocked(address _holder, bool _timeLocked) {
bool locked = (block.timestamp < time);
require(excludedAddresses[_holder] == true || locked == _timeLocked);
_;
}
constructor(uint256 _time) public {
time = _time;
}
function updateExcludedAddress(address _address, bool _status) public;
}
/// @title TimeLockedToken
/// @author Applicature
/// @notice helper mixed to other contracts to lock contract on a timestamp
/// @dev Base class
contract TimeLockedToken is TimeLocked, StandardToken {
constructor(uint256 _time) public TimeLocked(_time) {}
function transfer(address _to, uint256 _tokens) public isTimeLocked(msg.sender, false) returns (bool) {
return super.transfer(_to, _tokens);
}
function transferFrom(address _holder, address _to, uint256 _tokens)
public
isTimeLocked(_holder, false)
returns (bool)
{
return super.transferFrom(_holder, _to, _tokens);
}
}
contract ICUToken is OpenZeppelinERC20, MintableBurnableToken, TimeLockedToken {
ICUCrowdsale public crowdsale;
bool public isSoftCapAchieved;
constructor(uint256 _unlockTokensTime)
public
OpenZeppelinERC20(0, 'iCumulate', 18, 'ICU', false)
MintableBurnableToken(4700000000e18, 0, true)
TimeLockedToken(_unlockTokensTime)
{}
function setUnlockTime(uint256 _unlockTokensTime) public onlyStateChangeAgents {
time = _unlockTokensTime;
}
function setIsSoftCapAchieved() public onlyStateChangeAgents {
isSoftCapAchieved = true;
}
function setCrowdSale(address _crowdsale) public onlyOwner {
require(_crowdsale != address(0));
crowdsale = ICUCrowdsale(_crowdsale);
}
function updateExcludedAddress(address _address, bool _status) public onlyOwner {
excludedAddresses[_address] = _status;
}
function transfer(address _to, uint256 _tokens) public returns (bool) {
require(true == isTransferAllowed(msg.sender));
return super.transfer(_to, _tokens);
}
function transferFrom(address _holder, address _to, uint256 _tokens) public returns (bool) {
require(true == isTransferAllowed(_holder));
return super.transferFrom(_holder, _to, _tokens);
}
function isTransferAllowed(address _address) public view returns (bool) {
if (excludedAddresses[_address] == true) {
return true;
}
if (!isSoftCapAchieved && (address(crowdsale) == address(0) || false == crowdsale.isSoftCapAchieved(0))) {
return false;
}
return true;
}
function burnUnsoldTokens(uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) {
require(maxSupply.sub(_tokensToBurn) >= totalSupply_);
maxSupply = maxSupply.sub(_tokensToBurn);
emit Burn(address(0), _tokensToBurn);
return _tokensToBurn;
}
}
/// @title Agent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// @dev Base class
contract Agent {
using SafeMath for uint256;
function isInitialized() public view returns (bool) {
return false;
}
}
/// @title CrowdsaleAgent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// @dev Base class
contract CrowdsaleAgent is Agent {
Crowdsale public crowdsale;
bool public _isInitialized;
modifier onlyCrowdsale() {
require(msg.sender == address(crowdsale));
_;
}
constructor(Crowdsale _crowdsale) public {
crowdsale = _crowdsale;
if (address(0) != address(_crowdsale)) {
_isInitialized = true;
} else {
_isInitialized = false;
}
}
function isInitialized() public view returns (bool) {
return _isInitialized;
}
function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus)
public onlyCrowdsale();
function onStateChange(Crowdsale.State _state) public onlyCrowdsale();
function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned);
}
/// @title MintableCrowdsaleOnSuccessAgent
/// @author Applicature
/// @notice Contract which takes actions on state change and contribution
/// un-pause tokens and disable minting on Crowdsale success
/// @dev implementation
contract MintableCrowdsaleOnSuccessAgent is CrowdsaleAgent {
MintableToken public token;
bool public _isInitialized;
constructor(Crowdsale _crowdsale, MintableToken _token) public CrowdsaleAgent(_crowdsale) {
token = _token;
if (address(0) != address(_token) && address(0) != address(_crowdsale)) {
_isInitialized = true;
} else {
_isInitialized = false;
}
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return _isInitialized;
}
/// @notice Takes actions on contribution
function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus) public onlyCrowdsale;
/// @notice Takes actions on state change,
/// un-pause tokens and disable minting on Crowdsale success
/// @param _state Crowdsale.State
function onStateChange(Crowdsale.State _state) public onlyCrowdsale;
}
contract ICUAgent is MintableCrowdsaleOnSuccessAgent {
ICUStrategy public strategy;
ICUCrowdsale public crowdsale;
bool public burnStatus;
constructor(
ICUCrowdsale _crowdsale,
ICUToken _token,
ICUStrategy _strategy
) public MintableCrowdsaleOnSuccessAgent(_crowdsale, _token) {
require(address(_strategy) != address(0) && address(_crowdsale) != address(0));
strategy = _strategy;
crowdsale = _crowdsale;
}
/// @notice Takes actions on contribution
function onContribution(
address,
uint256 _tierIndex,
uint256 _tokens,
uint256 _bonus
) public onlyCrowdsale() {
strategy.updateTierState(_tierIndex, _tokens, _bonus);
}
function onStateChange(Crowdsale.State _state) public onlyCrowdsale() {
ICUToken icuToken = ICUToken(token);
if (
icuToken.isSoftCapAchieved() == false
&& (_state == Crowdsale.State.Success || _state == Crowdsale.State.Finalized)
&& crowdsale.isSoftCapAchieved(0)
) {
icuToken.setIsSoftCapAchieved();
}
if (_state > Crowdsale.State.InCrowdsale && burnStatus == false) {
uint256 unsoldTokensAmount = strategy.getUnsoldTokens();
burnStatus = true;
icuToken.burnUnsoldTokens(unsoldTokensAmount);
}
}
function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned) {
burned = ICUToken(token).burnByAgent(_contributor, _tokens);
}
function updateLockPeriod(uint256 _time) public {
require(msg.sender == address(strategy));
ICUToken(token).setUnlockTime(_time);
}
}
/// @title TokenAllocator
/// @author Applicature
/// @notice Contract responsible for defining distribution logic of tokens.
/// @dev Base class
contract TokenAllocator is Ownable {
mapping(address => bool) public crowdsales;
modifier onlyCrowdsale() {
require(crowdsales[msg.sender]);
_;
}
function addCrowdsales(address _address) public onlyOwner {
crowdsales[_address] = true;
}
function removeCrowdsales(address _address) public onlyOwner {
crowdsales[_address] = false;
}
function isInitialized() public view returns (bool) {
return false;
}
function allocate(address _holder, uint256 _tokens) public onlyCrowdsale() {
internalAllocate(_holder, _tokens);
}
function tokensAvailable() public view returns (uint256);
function internalAllocate(address _holder, uint256 _tokens) internal onlyCrowdsale();
}
/// @title MintableTokenAllocator
/// @author Applicature
/// @notice Contract responsible for defining distribution logic of tokens.
/// @dev implementation
contract MintableTokenAllocator is TokenAllocator {
using SafeMath for uint256;
MintableToken public token;
constructor(MintableToken _token) public {
require(address(0) != address(_token));
token = _token;
}
/// @notice update instance of MintableToken
function setToken(MintableToken _token) public onlyOwner {
token = _token;
}
function internalAllocate(address _holder, uint256 _tokens) internal {
token.mint(_holder, _tokens);
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return token.mintingAgents(this);
}
/// @return available tokens
function tokensAvailable() public view returns (uint256) {
return token.availableTokens();
}
}
/// @title ContributionForwarder
/// @author Applicature
/// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale.
/// @dev Base class
contract ContributionForwarder {
using SafeMath for uint256;
uint256 public weiCollected;
uint256 public weiForwarded;
event ContributionForwarded(address receiver, uint256 weiAmount);
function isInitialized() public view returns (bool) {
return false;
}
/// @notice transfer wei to receiver
function forward() public payable {
require(msg.value > 0);
weiCollected += msg.value;
internalForward();
}
function internalForward() internal;
}
/// @title DistributedDirectContributionForwarder
/// @author Applicature
/// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale.
/// @dev implementation
contract DistributedDirectContributionForwarder is ContributionForwarder {
Receiver[] public receivers;
uint256 public proportionAbsMax;
bool public isInitialized_;
struct Receiver {
address receiver;
uint256 proportion; // abslolute value in range of 0 - proportionAbsMax
uint256 forwardedWei;
}
constructor(uint256 _proportionAbsMax, address[] _receivers, uint256[] _proportions) public {
proportionAbsMax = _proportionAbsMax;
require(_receivers.length == _proportions.length);
require(_receivers.length > 0);
uint256 totalProportion;
for (uint256 i = 0; i < _receivers.length; i++) {
uint256 proportion = _proportions[i];
totalProportion = totalProportion.add(proportion);
receivers.push(Receiver(_receivers[i], proportion, 0));
}
require(totalProportion == proportionAbsMax);
isInitialized_ = true;
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return isInitialized_;
}
function internalForward() internal {
uint256 transferred;
for (uint256 i = 0; i < receivers.length; i++) {
Receiver storage receiver = receivers[i];
uint256 value = msg.value.mul(receiver.proportion).div(proportionAbsMax);
if (i == receivers.length - 1) {
value = msg.value.sub(transferred);
}
transferred = transferred.add(value);
receiver.receiver.transfer(value);
emit ContributionForwarded(receiver.receiver, value);
}
weiForwarded = weiForwarded.add(transferred);
}
}
contract Crowdsale {
uint256 public tokensSold;
enum State {Unknown, Initializing, BeforeCrowdsale, InCrowdsale, Success, Finalized, Refunding}
function externalContribution(address _contributor, uint256 _wei) public payable;
function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable;
function getState() public view returns (State);
function updateState() public;
function internalContribution(address _contributor, uint256 _wei) internal;
}
/// @title Crowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
contract CrowdsaleImpl is Crowdsale, Ownable {
using SafeMath for uint256;
State public currentState;
TokenAllocator public allocator;
ContributionForwarder public contributionForwarder;
PricingStrategy public pricingStrategy;
CrowdsaleAgent public crowdsaleAgent;
bool public finalized;
uint256 public startDate;
uint256 public endDate;
bool public allowWhitelisted;
bool public allowSigned;
bool public allowAnonymous;
mapping(address => bool) public whitelisted;
mapping(address => bool) public signers;
mapping(address => bool) public externalContributionAgents;
event Contribution(address _contributor, uint256 _wei, uint256 _tokensExcludingBonus, uint256 _bonus);
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous
) public {
allocator = _allocator;
contributionForwarder = _contributionForwarder;
pricingStrategy = _pricingStrategy;
startDate = _startDate;
endDate = _endDate;
allowWhitelisted = _allowWhitelisted;
allowSigned = _allowSigned;
allowAnonymous = _allowAnonymous;
currentState = State.Unknown;
}
/// @notice default payable function
function() public payable {
require(allowWhitelisted || allowAnonymous);
if (!allowAnonymous) {
if (allowWhitelisted) {
require(whitelisted[msg.sender]);
}
}
internalContribution(msg.sender, msg.value);
}
/// @notice update crowdsale agent
function setCrowdsaleAgent(CrowdsaleAgent _crowdsaleAgent) public onlyOwner {
require(address(_crowdsaleAgent) != address(0));
crowdsaleAgent = _crowdsaleAgent;
}
/// @notice allows external user to do contribution
function externalContribution(address _contributor, uint256 _wei) public payable {
require(externalContributionAgents[msg.sender]);
internalContribution(_contributor, _wei);
}
/// @notice update external contributor
function addExternalContributor(address _contributor) public onlyOwner {
externalContributionAgents[_contributor] = true;
}
/// @notice update external contributor
function removeExternalContributor(address _contributor) public onlyOwner {
externalContributionAgents[_contributor] = false;
}
/// @notice update whitelisting address
function updateWhitelist(address _address, bool _status) public onlyOwner {
whitelisted[_address] = _status;
}
/// @notice update signer
function addSigner(address _signer) public onlyOwner {
signers[_signer] = true;
}
/// @notice update signer
function removeSigner(address _signer) public onlyOwner {
signers[_signer] = false;
}
/// @notice allows to do signed contributions
function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable {
address recoveredAddress = verify(msg.sender, _v, _r, _s);
require(signers[recoveredAddress]);
internalContribution(msg.sender, msg.value);
}
/// @notice check sign
function verify(address _sender, uint8 _v, bytes32 _r, bytes32 _s) public view returns (address) {
bytes32 hash = keccak256(abi.encodePacked(this, _sender));
bytes memory prefix = '\x19Ethereum Signed Message:\n32';
return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s);
}
/// @return Crowdsale state
function getState() public view returns (State) {
if (finalized) {
return State.Finalized;
} else if (allocator.isInitialized() == false) {
return State.Initializing;
} else if (contributionForwarder.isInitialized() == false) {
return State.Initializing;
} else if (pricingStrategy.isInitialized() == false) {
return State.Initializing;
} else if (block.timestamp < startDate) {
return State.BeforeCrowdsale;
} else if (block.timestamp >= startDate && block.timestamp <= endDate) {
return State.InCrowdsale;
} else if (block.timestamp > endDate) {
return State.Success;
}
return State.Unknown;
}
/// @notice Crowdsale state
function updateState() public {
State state = getState();
if (currentState != state) {
if (crowdsaleAgent != address(0)) {
crowdsaleAgent.onStateChange(state);
}
currentState = state;
}
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(getState() == State.InCrowdsale);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens > 0 && tokens <= tokensAvailable);
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
if (msg.value > 0) {
contributionForwarder.forward.value(msg.value)();
}
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
}
/// @title HardCappedCrowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
/// with hard limit
contract HardCappedCrowdsale is CrowdsaleImpl {
using SafeMath for uint256;
uint256 public hardCap;
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous,
uint256 _hardCap
) public CrowdsaleImpl(
_allocator,
_contributionForwarder,
_pricingStrategy,
_startDate,
_endDate,
_allowWhitelisted,
_allowSigned,
_allowAnonymous
) {
hardCap = _hardCap;
}
/// @return Crowdsale state
function getState() public view returns (State) {
State state = super.getState();
if (state == State.InCrowdsale) {
if (isHardCapAchieved(0)) {
return State.Success;
}
}
return state;
}
function isHardCapAchieved(uint256 _value) public view returns (bool) {
if (hardCap <= tokensSold.add(_value)) {
return true;
}
return false;
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(getState() == State.InCrowdsale);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens <= tokensAvailable && tokens > 0 && false == isHardCapAchieved(tokens.sub(1)));
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
if (msg.value > 0) {
contributionForwarder.forward.value(msg.value)();
}
crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
}
/// @title RefundableCrowdsale
/// @author Applicature
/// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale.
/// with hard and soft limits
contract RefundableCrowdsale is HardCappedCrowdsale {
using SafeMath for uint256;
uint256 public softCap;
mapping(address => uint256) public contributorsWei;
address[] public contributors;
event Refund(address _holder, uint256 _wei, uint256 _tokens);
constructor(
TokenAllocator _allocator,
ContributionForwarder _contributionForwarder,
PricingStrategy _pricingStrategy,
uint256 _startDate,
uint256 _endDate,
bool _allowWhitelisted,
bool _allowSigned,
bool _allowAnonymous,
uint256 _softCap,
uint256 _hardCap
) public HardCappedCrowdsale(
_allocator, _contributionForwarder, _pricingStrategy,
_startDate, _endDate,
_allowWhitelisted, _allowSigned, _allowAnonymous, _hardCap
) {
softCap = _softCap;
}
/// @return Crowdsale state
function getState() public view returns (State) {
State state = super.getState();
if (state == State.Success) {
if (!isSoftCapAchieved(0)) {
return State.Refunding;
}
}
return state;
}
function isSoftCapAchieved(uint256 _value) public view returns (bool) {
if (softCap <= tokensSold.add(_value)) {
return true;
}
return false;
}
/// @notice refund ethers to contributor
function refund() public {
internalRefund(msg.sender);
}
/// @notice refund ethers to delegate
function delegatedRefund(address _address) public {
internalRefund(_address);
}
function internalContribution(address _contributor, uint256 _wei) internal {
require(block.timestamp >= startDate && block.timestamp <= endDate);
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei);
require(tokens <= tokensAvailable && tokens > 0 && hardCap > tokensSold.add(tokens));
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokens);
// transfer only if softcap is reached
if (isSoftCapAchieved(0)) {
if (msg.value > 0) {
contributionForwarder.forward.value(address(this).balance)();
}
} else {
// store contributor if it is not stored before
if (contributorsWei[_contributor] == 0) {
contributors.push(_contributor);
}
contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value);
}
crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
function internalRefund(address _holder) internal {
updateState();
require(block.timestamp > endDate);
require(!isSoftCapAchieved(0));
require(crowdsaleAgent != address(0));
uint256 value = contributorsWei[_holder];
require(value > 0);
contributorsWei[_holder] = 0;
uint256 burnedTokens = crowdsaleAgent.onRefund(_holder, 0);
_holder.transfer(value);
emit Refund(_holder, value, burnedTokens);
}
}
contract ICUCrowdsale is RefundableCrowdsale {
uint256 public maxSaleSupply = 2350000000e18;
uint256 public availableBonusAmount = 447500000e18;
uint256 public usdCollected;
mapping(address => uint256) public contributorBonuses;
constructor(
MintableTokenAllocator _allocator,
DistributedDirectContributionForwarder _contributionForwarder,
ICUStrategy _pricingStrategy,
uint256 _startTime,
uint256 _endTime
) public RefundableCrowdsale(
_allocator,
_contributionForwarder,
_pricingStrategy,
_startTime,
_endTime,
true,
true,
false,
2500000e5, //softCap
23500000e5//hardCap
) {}
function updateState() public {
(startDate, endDate) = ICUStrategy(pricingStrategy).getActualDates();
super.updateState();
}
function claimBonuses() public {
require(isSoftCapAchieved(0) && contributorBonuses[msg.sender] > 0);
uint256 bonus = contributorBonuses[msg.sender];
contributorBonuses[msg.sender] = 0;
allocator.allocate(msg.sender, bonus);
}
function addExternalContributor(address) public onlyOwner {
require(false);
}
function isHardCapAchieved(uint256 _value) public view returns (bool) {
if (hardCap <= usdCollected.add(_value)) {
return true;
}
return false;
}
function isSoftCapAchieved(uint256 _value) public view returns (bool) {
if (softCap <= usdCollected.add(_value)) {
return true;
}
return false;
}
function internalContribution(address _contributor, uint256 _wei) internal {
updateState();
require(currentState == State.InCrowdsale);
ICUStrategy pricing = ICUStrategy(pricingStrategy);
uint256 usdAmount = pricing.getUSDAmount(_wei);
require(!isHardCapAchieved(usdAmount.sub(1)));
uint256 tokensAvailable = allocator.tokensAvailable();
uint256 collectedWei = contributionForwarder.weiCollected();
uint256 tierIndex = pricing.getTierIndex();
uint256 tokens;
uint256 tokensExcludingBonus;
uint256 bonus;
(tokens, tokensExcludingBonus, bonus) = pricing.getTokens(
_contributor, tokensAvailable, tokensSold, _wei, collectedWei
);
require(tokens > 0);
tokensSold = tokensSold.add(tokens);
allocator.allocate(_contributor, tokensExcludingBonus);
if (isSoftCapAchieved(usdAmount)) {
if (msg.value > 0) {
contributionForwarder.forward.value(address(this).balance)();
}
} else {
// store contributor if it is not stored before
if (contributorsWei[_contributor] == 0) {
contributors.push(_contributor);
}
contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value);
}
usdCollected = usdCollected.add(usdAmount);
if (availableBonusAmount > 0) {
if (availableBonusAmount >= bonus) {
availableBonusAmount -= bonus;
} else {
bonus = availableBonusAmount;
availableBonusAmount = 0;
}
contributorBonuses[_contributor] = contributorBonuses[_contributor].add(bonus);
} else {
bonus = 0;
}
crowdsaleAgent.onContribution(pricing, tierIndex, tokensExcludingBonus, bonus);
emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus);
}
}
/// @title PricingStrategy
/// @author Applicature
/// @notice Contract is responsible for calculating tokens amount depending on different criterias
/// @dev Base class
contract PricingStrategy {
function isInitialized() public view returns (bool);
function getTokens(
address _contributor,
uint256 _tokensAvailable,
uint256 _tokensSold,
uint256 _weiAmount,
uint256 _collectedWei
)
public
view
returns (uint256 tokens, uint256 tokensExludingBonus, uint256 bonus);
function getWeis(
uint256 _collectedWei,
uint256 _tokensSold,
uint256 _tokens
)
public
view
returns (uint256 weiAmount, uint256 tokensBonus);
}
/// @title TokenDateCappedTiersPricingStrategy
/// @author Applicature
/// @notice Contract is responsible for calculating tokens amount depending on price in USD
/// @dev implementation
contract TokenDateCappedTiersPricingStrategy is PricingStrategy, Ownable {
using SafeMath for uint256;
uint256 public etherPriceInUSD;
uint256 public capsAmount;
struct Tier {
uint256 tokenInUSD;
uint256 maxTokensCollected;
uint256 soldTierTokens;
uint256 bonusTierTokens;
uint256 discountPercents;
uint256 minInvestInUSD;
uint256 startDate;
uint256 endDate;
bool unsoldProcessed;
uint256[] capsData;
}
Tier[] public tiers;
uint256 public decimals;
constructor(
uint256[] _tiers,
uint256[] _capsData,
uint256 _decimals,
uint256 _etherPriceInUSD
)
public
{
decimals = _decimals;
require(_etherPriceInUSD > 0);
etherPriceInUSD = _etherPriceInUSD;
require(_tiers.length % 6 == 0);
uint256 length = _tiers.length / 6;
require(_capsData.length % 2 == 0);
uint256 lengthCaps = _capsData.length / 2;
uint256[] memory emptyArray;
for (uint256 i = 0; i < length; i++) {
tiers.push(
Tier(
_tiers[i * 6],//tokenInUSD
_tiers[i * 6 + 1],//maxTokensCollected
0,//soldTierTokens
0,//bonusTierTokens
_tiers[i * 6 + 2],//discountPercents
_tiers[i * 6 + 3],//minInvestInUSD
_tiers[i * 6 + 4],//startDate
_tiers[i * 6 + 5],//endDate
false,
emptyArray//capsData
)
);
for (uint256 j = 0; j < lengthCaps; j++) {
tiers[i].capsData.push(_capsData[i * lengthCaps + j]);
}
}
}
/// @return tier index
function getTierIndex() public view returns (uint256) {
for (uint256 i = 0; i < tiers.length; i++) {
if (
block.timestamp >= tiers[i].startDate &&
block.timestamp < tiers[i].endDate &&
tiers[i].maxTokensCollected > tiers[i].soldTierTokens
) {
return i;
}
}
return tiers.length;
}
function getActualTierIndex() public view returns (uint256) {
for (uint256 i = 0; i < tiers.length; i++) {
if (
block.timestamp >= tiers[i].startDate
&& block.timestamp < tiers[i].endDate
&& tiers[i].maxTokensCollected > tiers[i].soldTierTokens
|| block.timestamp < tiers[i].startDate
) {
return i;
}
}
return tiers.length.sub(1);
}
/// @return actual dates
function getActualDates() public view returns (uint256 startDate, uint256 endDate) {
uint256 tierIndex = getActualTierIndex();
startDate = tiers[tierIndex].startDate;
endDate = tiers[tierIndex].endDate;
}
function getTokensWithoutRestrictions(uint256 _weiAmount) public view returns (
uint256 tokens,
uint256 tokensExcludingBonus,
uint256 bonus
) {
if (_weiAmount == 0) {
return (0, 0, 0);
}
uint256 tierIndex = getActualTierIndex();
tokensExcludingBonus = _weiAmount.mul(etherPriceInUSD).div(getTokensInUSD(tierIndex));
bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus);
tokens = tokensExcludingBonus.add(bonus);
}
/// @return tokens based on sold tokens and wei amount
function getTokens(
address,
uint256 _tokensAvailable,
uint256,
uint256 _weiAmount,
uint256
) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) {
if (_weiAmount == 0) {
return (0, 0, 0);
}
uint256 tierIndex = getTierIndex();
if (tierIndex == tiers.length || _weiAmount.mul(etherPriceInUSD).div(1e18) < tiers[tierIndex].minInvestInUSD) {
return (0, 0, 0);
}
tokensExcludingBonus = _weiAmount.mul(etherPriceInUSD).div(getTokensInUSD(tierIndex));
if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(tokensExcludingBonus)) {
return (0, 0, 0);
}
bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus);
tokens = tokensExcludingBonus.add(bonus);
if (tokens > _tokensAvailable) {
return (0, 0, 0);
}
}
/// @return weis based on sold and required tokens
function getWeis(
uint256,
uint256,
uint256 _tokens
) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) {
if (_tokens == 0) {
return (0, 0);
}
uint256 tierIndex = getTierIndex();
if (tierIndex == tiers.length) {
return (0, 0);
}
if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(_tokens)) {
return (0, 0);
}
uint256 usdAmount = _tokens.mul(getTokensInUSD(tierIndex)).div(1e18);
totalWeiAmount = usdAmount.mul(1e18).div(etherPriceInUSD);
if (totalWeiAmount < uint256(1 ether).mul(tiers[tierIndex].minInvestInUSD).div(etherPriceInUSD)) {
return (0, 0);
}
tokensBonus = calculateBonusAmount(tierIndex, _tokens);
}
function calculateBonusAmount(uint256 _tierIndex, uint256 _tokens) public view returns (uint256 bonus) {
uint256 length = tiers[_tierIndex].capsData.length.div(2);
uint256 remainingTokens = _tokens;
uint256 newSoldTokens = tiers[_tierIndex].soldTierTokens;
for (uint256 i = 0; i < length; i++) {
if (tiers[_tierIndex].capsData[i.mul(2)] == 0) {
break;
}
if (newSoldTokens.add(remainingTokens) <= tiers[_tierIndex].capsData[i.mul(2)]) {
bonus += remainingTokens.mul(tiers[_tierIndex].capsData[i.mul(2).add(1)]).div(100);
break;
} else {
uint256 diff = tiers[_tierIndex].capsData[i.mul(2)].sub(newSoldTokens);
remainingTokens -= diff;
newSoldTokens += diff;
bonus += diff.mul(tiers[_tierIndex].capsData[i.mul(2).add(1)]).div(100);
}
}
}
function getTokensInUSD(uint256 _tierIndex) public view returns (uint256) {
if (_tierIndex < uint256(tiers.length)) {
return tiers[_tierIndex].tokenInUSD;
}
}
function getDiscount(uint256 _tierIndex) public view returns (uint256) {
if (_tierIndex < uint256(tiers.length)) {
return tiers[_tierIndex].discountPercents;
}
}
function getMinEtherInvest(uint256 _tierIndex) public view returns (uint256) {
if (_tierIndex < uint256(tiers.length)) {
return tiers[_tierIndex].minInvestInUSD.mul(1 ether).div(etherPriceInUSD);
}
}
function getUSDAmount(uint256 _weiAmount) public view returns (uint256) {
return _weiAmount.mul(etherPriceInUSD).div(1 ether);
}
/// @notice Check whether contract is initialised
/// @return true if initialized
function isInitialized() public view returns (bool) {
return true;
}
/// @notice updates tier start/end dates by id
function updateDates(uint8 _tierId, uint256 _start, uint256 _end) public onlyOwner() {
if (_start != 0 && _start < _end && _tierId < tiers.length) {
Tier storage tier = tiers[_tierId];
tier.startDate = _start;
tier.endDate = _end;
}
}
}
contract ICUStrategy is TokenDateCappedTiersPricingStrategy {
ICUAgent public agent;
event UnsoldTokensProcessed(uint256 fromTier, uint256 toTier, uint256 tokensAmount);
constructor(
uint256[] _emptyArray,
uint256 _etherPriceInUSD
) public TokenDateCappedTiersPricingStrategy(
_emptyArray,
_emptyArray,
18,
_etherPriceInUSD
) {
//Pre-ICO
tiers.push(
Tier(
0.01e5,//tokenInUSD
1000000000e18,//maxTokensCollected
0,//soldTierTokens
0,//bonusTierTokens
0,//discountPercents
uint256(20).mul(_etherPriceInUSD),//minInvestInUSD | 20 ethers
1543579200,//startDate | 2018/11/30 12:00:00 PM UTC
1544184000,//endDate | 2018/12/07 12:00:00 PM UTC
false,
_emptyArray
)
);
//ICO
tiers.push(
Tier(
0.01e5,//tokenInUSD
1350000000e18,//maxTokensCollected
0,//soldTierTokens
0,//bonusTierTokens
0,//discountPercents
uint256(_etherPriceInUSD).div(10),//minInvestInUSD | 0.1 ether
1544443200,//startDate | 2018/12/10 12:00:00 PM UTC
1546257600,//endDate | 2018/12/31 12:00:00 PM UTC
false,
_emptyArray
)
);
//Pre-ICO caps data
tiers[0].capsData.push(1000000000e18);//cap $10,000,000 in tokens
tiers[0].capsData.push(30);//bonus percents
//ICO caps data
tiers[1].capsData.push(400000000e18);//cap $4,000,000 in tokens
tiers[1].capsData.push(20);//bonus percents
tiers[1].capsData.push(800000000e18);//cap $4,000,000 in tokens
tiers[1].capsData.push(10);//bonus percents
tiers[1].capsData.push(1350000000e18);//cap $5,500,000 in tokens
tiers[1].capsData.push(5);//bonus percents
}
function getArrayOfTiers() public view returns (uint256[14] tiersData) {
uint256 j = 0;
for (uint256 i = 0; i < tiers.length; i++) {
tiersData[j++] = uint256(tiers[i].tokenInUSD);
tiersData[j++] = uint256(tiers[i].maxTokensCollected);
tiersData[j++] = uint256(tiers[i].soldTierTokens);
tiersData[j++] = uint256(tiers[i].discountPercents);
tiersData[j++] = uint256(tiers[i].minInvestInUSD);
tiersData[j++] = uint256(tiers[i].startDate);
tiersData[j++] = uint256(tiers[i].endDate);
}
}
function updateTier(
uint256 _tierId,
uint256 _start,
uint256 _end,
uint256 _minInvest,
uint256 _price,
uint256 _discount,
uint256[] _capsData,
bool updateLockNeeded
) public onlyOwner() {
require(
_start != 0 &&
_price != 0 &&
_start < _end &&
_tierId < tiers.length &&
_capsData.length > 0 &&
_capsData.length % 2 == 0
);
if (updateLockNeeded) {
agent.updateLockPeriod(_end);
}
Tier storage tier = tiers[_tierId];
tier.tokenInUSD = _price;
tier.discountPercents = _discount;
tier.minInvestInUSD = _minInvest;
tier.startDate = _start;
tier.endDate = _end;
tier.capsData = _capsData;
}
function setCrowdsaleAgent(ICUAgent _crowdsaleAgent) public onlyOwner {
agent = _crowdsaleAgent;
}
function updateTierState(uint256 _tierId, uint256 _soldTokens, uint256 _bonusTokens) public {
require(
msg.sender == address(agent) &&
_tierId < tiers.length &&
_soldTokens > 0
);
Tier storage tier = tiers[_tierId];
if (_tierId > 0 && !tiers[_tierId.sub(1)].unsoldProcessed) {
Tier storage prevTier = tiers[_tierId.sub(1)];
prevTier.unsoldProcessed = true;
uint256 unsold = prevTier.maxTokensCollected.sub(prevTier.soldTierTokens);
tier.maxTokensCollected = tier.maxTokensCollected.add(unsold);
tier.capsData[0] = tier.capsData[0].add(unsold);
emit UnsoldTokensProcessed(_tierId.sub(1), _tierId, unsold);
}
tier.soldTierTokens = tier.soldTierTokens.add(_soldTokens);
tier.bonusTierTokens = tier.bonusTierTokens.add(_bonusTokens);
}
function getTierUnsoldTokens(uint256 _tierId) public view returns (uint256) {
if (_tierId >= tiers.length || tiers[_tierId].unsoldProcessed) {
return 0;
}
return tiers[_tierId].maxTokensCollected.sub(tiers[_tierId].soldTierTokens);
}
function getUnsoldTokens() public view returns (uint256 unsoldTokens) {
for (uint256 i = 0; i < tiers.length; i++) {
unsoldTokens += getTierUnsoldTokens(i);
}
}
function getCapsData(uint256 _tierId) public view returns (uint256[]) {
if (_tierId < tiers.length) {
return tiers[_tierId].capsData;
}
}
}
contract Referral is Ownable {
using SafeMath for uint256;
MintableTokenAllocator public allocator;
CrowdsaleImpl public crowdsale;
uint256 public constant DECIMALS = 18;
uint256 public totalSupply;
bool public unLimited;
bool public sentOnce;
mapping(address => bool) public claimed;
mapping(address => uint256) public claimedBalances;
constructor(
uint256 _totalSupply,
address _allocator,
address _crowdsale,
bool _sentOnce
) public {
require(_allocator != address(0) && _crowdsale != address(0));
totalSupply = _totalSupply;
if (totalSupply == 0) {
unLimited = true;
}
allocator = MintableTokenAllocator(_allocator);
crowdsale = CrowdsaleImpl(_crowdsale);
sentOnce = _sentOnce;
}
function setAllocator(address _allocator) public onlyOwner {
require(_allocator != address(0));
allocator = MintableTokenAllocator(_allocator);
}
function setCrowdsale(address _crowdsale) public onlyOwner {
require(_crowdsale != address(0));
crowdsale = CrowdsaleImpl(_crowdsale);
}
function multivestMint(
address _address,
uint256 _amount,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
require(true == crowdsale.signers(verify(msg.sender, _amount, _v, _r, _s)));
if (true == sentOnce) {
require(claimed[_address] == false);
claimed[_address] = true;
}
require(
_address == msg.sender &&
_amount > 0 &&
(true == unLimited || _amount <= totalSupply)
);
claimedBalances[_address] = claimedBalances[_address].add(_amount);
if (false == unLimited) {
totalSupply = totalSupply.sub(_amount);
}
allocator.allocate(_address, _amount);
}
/// @notice check sign
function verify(address _sender, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(_sender, _amount));
bytes memory prefix = '\x19Ethereum Signed Message:\n32';
return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s);
}
}
contract ICUReferral is Referral {
constructor(
address _allocator,
address _crowdsale
) public Referral(35000000e18, _allocator, _crowdsale, true) {}
function multivestMint(
address _address,
uint256 _amount,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
ICUCrowdsale icuCrowdsale = ICUCrowdsale(crowdsale);
icuCrowdsale.updateState();
require(icuCrowdsale.isSoftCapAchieved(0) && block.timestamp > icuCrowdsale.endDate());
super.multivestMint(_address, _amount, _v, _r, _s);
}
}
contract Stats {
using SafeMath for uint256;
MintableToken public token;
MintableTokenAllocator public allocator;
ICUCrowdsale public crowdsale;
ICUStrategy public pricing;
constructor(
MintableToken _token,
MintableTokenAllocator _allocator,
ICUCrowdsale _crowdsale,
ICUStrategy _pricing
) public {
token = _token;
allocator = _allocator;
crowdsale = _crowdsale;
pricing = _pricing;
}
function getTokens(
uint256,
uint256 _weiAmount
) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) {
return pricing.getTokensWithoutRestrictions(_weiAmount);
}
function getWeis(
uint256,
uint256 _tokenAmount
) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) {
return pricing.getWeis(0, 0, _tokenAmount);
}
function getStats(uint256 _userType, uint256[7] _ethPerCurrency) public view returns (
uint256[8] stats,
uint256[26] tiersData,
uint256[21] currencyContr //tokensPerEachCurrency,
) {
stats = getStatsData(_userType);
tiersData = getTiersData(_userType);
currencyContr = getCurrencyContrData(_userType, _ethPerCurrency);
}
function getTiersData(uint256) public view returns (
uint256[26] tiersData
) {
uint256[14] memory tiers = pricing.getArrayOfTiers();
uint256 tierElements = tiers.length.div(2);
uint256 j = 0;
for (uint256 i = 0; i <= tierElements; i += tierElements) {
tiersData[j++] = uint256(1e23).div(tiers[i]);// tokenInUSD;
tiersData[j++] = 0;// tokenInWei;
tiersData[j++] = uint256(tiers[i.add(1)]);// maxTokensCollected;
tiersData[j++] = uint256(tiers[i.add(2)]);// soldTierTokens;
tiersData[j++] = 0;// discountPercents;
tiersData[j++] = 0;// bonusPercents;
tiersData[j++] = uint256(tiers[i.add(4)]);// minInvestInUSD;
tiersData[j++] = 0;// minInvestInWei;
tiersData[j++] = 0;// maxInvestInUSD;
tiersData[j++] = 0;// maxInvestInWei;
tiersData[j++] = uint256(tiers[i.add(5)]);// startDate;
tiersData[j++] = uint256(tiers[i.add(6)]);// endDate;
tiersData[j++] = 1;
}
tiersData[25] = 2;
}
function getStatsData(uint256 _type) public view returns (
uint256[8] stats
) {
_type = _type;
stats[0] = token.maxSupply();
stats[1] = token.totalSupply();
stats[2] = crowdsale.maxSaleSupply();
stats[3] = crowdsale.tokensSold();
stats[4] = uint256(crowdsale.currentState());
stats[5] = pricing.getActualTierIndex();
stats[6] = pricing.getTierUnsoldTokens(stats[5]);
stats[7] = pricing.getMinEtherInvest(stats[5]);
}
function getCurrencyContrData(uint256 _type, uint256[7] _ethPerCurrency) public view returns (
uint256[21] currencyContr
) {
_type = _type;
uint256 j = 0;
for (uint256 i = 0; i < _ethPerCurrency.length; i++) {
(currencyContr[j++], currencyContr[j++], currencyContr[j++]) = pricing.getTokensWithoutRestrictions(
_ethPerCurrency[i]
);
}
}
}
contract PeriodicTokenVesting is TokenVesting {
address public unreleasedHolder;
uint256 public periods;
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable,
address _unreleasedHolder
)
public TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable)
{
require(_revocable == false || _unreleasedHolder != address(0));
periods = _periods;
unreleasedHolder = _unreleasedHolder;
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration * periods) || revoked[token]) {
return totalBalance;
} else {
uint256 periodTokens = totalBalance.div(periods);
uint256 periodsOver = now.sub(start).div(duration);
if (periodsOver >= periods) {
return totalBalance;
}
return periodTokens.mul(periodsOver);
}
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(unreleasedHolder, refund);
emit Revoked();
}
}
contract ICUAllocation is Ownable {
using SafeERC20 for ERC20Basic;
using SafeMath for uint256;
uint256 public constant BOUNTY_TOKENS = 47000000e18;
uint256 public constant MAX_TREASURY_TOKENS = 2350000000e18;
uint256 public icoEndTime;
address[] public vestings;
address public bountyAddress;
address public treasuryAddress;
bool public isBountySent;
bool public isTeamSent;
event VestingCreated(
address _vesting,
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable
);
event VestingRevoked(address _vesting);
constructor(address _bountyAddress, address _treasuryAddress) public {
require(_bountyAddress != address(0) && _treasuryAddress != address(0));
bountyAddress = _bountyAddress;
treasuryAddress = _treasuryAddress;
}
function setICOEndTime(uint256 _icoEndTime) public onlyOwner {
icoEndTime = _icoEndTime;
}
function allocateBounty(MintableTokenAllocator _allocator, ICUCrowdsale _crowdsale) public onlyOwner {
require(!isBountySent && icoEndTime < block.timestamp && _crowdsale.isSoftCapAchieved(0));
isBountySent = true;
_allocator.allocate(bountyAddress, BOUNTY_TOKENS);
}
function allocateTreasury(MintableTokenAllocator _allocator) public onlyOwner {
require(icoEndTime < block.timestamp, 'ICO is not ended');
require(isBountySent, 'Bounty is not sent');
require(isTeamSent, 'Team vesting is not created');
require(MAX_TREASURY_TOKENS >= _allocator.tokensAvailable(), 'Unsold tokens are not burned');
_allocator.allocate(treasuryAddress, _allocator.tokensAvailable());
}
function createVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
uint256 _periods,
bool _revocable,
address _unreleasedHolder,
MintableTokenAllocator _allocator,
uint256 _amount
) public onlyOwner returns (PeriodicTokenVesting) {
require(icoEndTime > 0 && _amount > 0);
isTeamSent = true;
PeriodicTokenVesting vesting = new PeriodicTokenVesting(
_beneficiary, _start, _cliff, _duration, _periods, _revocable, _unreleasedHolder
);
vestings.push(vesting);
emit VestingCreated(vesting, _beneficiary, _start, _cliff, _duration, _periods, _revocable);
_allocator.allocate(address(vesting), _amount);
return vesting;
}
function revokeVesting(PeriodicTokenVesting _vesting, ERC20Basic token) public onlyOwner() {
_vesting.revoke(token);
emit VestingRevoked(_vesting);
}
} | @title PricingStrategy @author Applicature @notice Contract is responsible for calculating tokens amount depending on different criterias @dev Base class | contract PricingStrategy {
function isInitialized() public view returns (bool);
function getTokens(
address _contributor,
uint256 _tokensAvailable,
uint256 _tokensSold,
uint256 _weiAmount,
uint256 _collectedWei
)
public
view
returns (uint256 tokens, uint256 tokensExludingBonus, uint256 bonus);
function getWeis(
uint256 _collectedWei,
uint256 _tokensSold,
uint256 _tokens
)
public
view
returns (uint256 weiAmount, uint256 tokensBonus);
}
| 13,111,423 | [
1,
52,
1512,
25866,
225,
1716,
1780,
1231,
225,
13456,
353,
14549,
364,
21046,
2430,
3844,
8353,
603,
3775,
24992,
1795,
225,
3360,
667,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
453,
1512,
25866,
288,
203,
203,
565,
445,
25359,
1435,
1071,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
18349,
12,
203,
3639,
1758,
389,
591,
19293,
16,
203,
3639,
2254,
5034,
389,
7860,
5268,
16,
203,
3639,
2254,
5034,
389,
7860,
55,
1673,
16,
203,
3639,
2254,
5034,
389,
1814,
77,
6275,
16,
203,
3639,
2254,
5034,
389,
14676,
329,
3218,
77,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
2430,
16,
2254,
5034,
2430,
424,
80,
12673,
38,
22889,
16,
2254,
5034,
324,
22889,
1769,
203,
203,
565,
445,
336,
3218,
291,
12,
203,
3639,
2254,
5034,
389,
14676,
329,
3218,
77,
16,
203,
3639,
2254,
5034,
389,
7860,
55,
1673,
16,
203,
3639,
2254,
5034,
389,
7860,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
732,
77,
6275,
16,
2254,
5034,
2430,
38,
22889,
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
] |
pragma solidity >=0.4.22 <0.7.0;
contract ClientStore {
// Client configuration requires a LWM2M BS Server config. and a LWM2M Server config.
struct ClientConfig {
bytes32 url_bs;
bytes32 id_bs;
bytes32 key_bs;
bytes32 url_s;
bytes32 id_s;
bytes32 key_s;
}
// This declares a state variable that stores a 'ClientConfig' struct for each client endpoint
mapping(bytes32 => ClientConfig) clients;
// This declares a state variable that stores all client endpoints
bytes32[] endpoints;
address public owner; // Contract owner
mapping(address => bool) public whitelist; // White list of addresses that can execute transactions
// Can add some addresses to white list during contract deployment
constructor(address[] memory addresses) public {
owner = msg.sender;
whitelist[msg.sender] = true;
if(addresses.length > 0) {
for(uint i = 0; i < addresses.length; i++){
whitelist[addresses[i]] = true;
}
}
}
modifier onlyOwner {
require(msg.sender == owner, "Only contract owner can execute this");
_;
}
modifier onlyWhitelist {
require(whitelist[msg.sender], "Only whitelisted accounts can execute this");
_;
}
function setPermission(address addr, bool permission) public onlyOwner {
whitelist[addr] = permission;
}
function addClient(
bytes32 endpoint, // Client Endpoint
bytes32 url_bs, bytes32 id_bs, bytes32 key_bs, // LWM2M Server config.
bytes32 url_s, bytes32 id_s, bytes32 key_s // LWM2M BS Server config.
) public onlyWhitelist {
int exists = existsClient(endpoint);
// require triggers a revert() with the message specified if condition is false
// https://solidity.readthedocs.io/en/v0.4.24/control-structures.html#error-handling-assert-require-revert-and-exceptions
require(exists == -1, "Client Endpoint already exists");
clients[endpoint].url_bs = url_bs;
clients[endpoint].id_bs = id_bs;
clients[endpoint].key_bs = key_bs;
clients[endpoint].url_s = url_s;
clients[endpoint].id_s = id_s;
clients[endpoint].key_s = key_s;
endpoints.push(endpoint); // Client added
}
function getClient(bytes32 endpoint) public onlyWhitelist view returns (
// Why I used 'view'?
// https://ethereum.stackexchange.com/questions/39561/solidity-function-state-mutability-warning#answers
bytes32, bytes32, bytes32, // LWM2M BS Server config
bytes32, bytes32, bytes32 // LWM2M Server config
) {
int exists = existsClient(endpoint);
if(exists == -1) {
return("", "", "", "", "", ""); // Endpoint does not exist
}
return (
clients[endpoint].url_bs, clients[endpoint].id_bs, clients[endpoint].key_bs, // BS Server config
clients[endpoint].url_s, clients[endpoint].id_s, clients[endpoint].key_s); // Server config
}
function removeClient(bytes32 endpoint) public onlyWhitelist {
int pos = existsClient(endpoint);
// require triggers a revert() with the message specified if condition is false
require(pos != -1, "Endpoint does not exist");
for (uint i = uint(pos); i < endpoints.length - 1; i++) {
endpoints[i] = endpoints[i + 1];
}
endpoints.pop();
delete clients[endpoint];
// Endpoint deleted successfully
}
function existsClient(bytes32 endpoint) public onlyWhitelist view returns(int) {
for (uint i = 0; i < endpoints.length; i++) {
if(endpoint == endpoints[i]){
return int(i);
}
}
return -1;
}
function getAllClients() public view onlyWhitelist returns (
bytes32[] memory, bytes32[] memory, bytes32[] memory, bytes32[] memory, bytes32[] memory, bytes32[] memory, bytes32[] memory)
{
bytes32[] memory endpoints_res = new bytes32[](endpoints.length);
bytes32[] memory urls_bs = new bytes32[](endpoints.length);
bytes32[] memory ids_bs = new bytes32[](endpoints.length);
bytes32[] memory keys_bs = new bytes32[](endpoints.length);
bytes32[] memory urls_s = new bytes32[](endpoints.length);
bytes32[] memory ids_s = new bytes32[](endpoints.length);
bytes32[] memory keys_s = new bytes32[](endpoints.length);
for (uint256 i = 0; i < endpoints.length; i++) {
endpoints_res[i] = endpoints[i];
urls_bs[i] = clients[endpoints[i]].url_bs;
ids_bs[i] = clients[endpoints[i]].id_bs;
keys_bs[i] = clients[endpoints[i]].key_bs;
urls_s[i] = clients[endpoints[i]].url_s;
ids_s[i] = clients[endpoints[i]].id_s;
keys_s[i] = clients[endpoints[i]].key_s;
}
return (endpoints_res, urls_bs, ids_bs, keys_bs, urls_s, ids_s, keys_s);
}
}
| This declares a state variable that stores a 'ClientConfig' struct for each client endpoint | mapping(bytes32 => ClientConfig) clients;
| 1,753,482 | [
1,
2503,
3496,
4807,
279,
919,
2190,
716,
9064,
279,
296,
16790,
11,
1958,
364,
1517,
1004,
2494,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
3890,
1578,
516,
26518,
13,
7712,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20FlashMint.sol";
/// @custom:security-contact [email protected]
contract VIZU is ERC20, ERC20Burnable, Pausable, AccessControl, ERC20Permit, ERC20FlashMint {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
constructor() ERC20("VIZU", "VIZU") ERC20Permit("VIZU") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_mint(msg.sender, 21000000000000 * 10 ** decimals());
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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:
*
* - `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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20FlashMint.sol)
pragma solidity ^0.8.0;
import "../../../interfaces/IERC3156.sol";
import "../ERC20.sol";
/**
* @dev Implementation of the ERC3156 Flash loans extension, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* Adds the {flashLoan} method, which provides flash loan support at the token
* level. By default there is no fee, but this can be changed by overriding {flashFee}.
*
* _Available since v4.1._
*/
abstract contract ERC20FlashMint is ERC20, IERC3156FlashLender {
bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
/**
* @dev Returns the maximum amount of tokens available for loan.
* @param token The address of the token that is requested.
* @return The amont of token that can be loaned.
*/
function maxFlashLoan(address token) public view override returns (uint256) {
return token == address(this) ? type(uint256).max - ERC20.totalSupply() : 0;
}
/**
* @dev Returns the fee applied when doing flash loans. By default this
* implementation has 0 fees. This function can be overloaded to make
* the flash loan mechanism deflationary.
* @param token The token to be flash loaned.
* @param amount The amount of tokens to be loaned.
* @return The fees applied to the corresponding flash loan.
*/
function flashFee(address token, uint256 amount) public view virtual override returns (uint256) {
require(token == address(this), "ERC20FlashMint: wrong token");
// silence warning about unused variable without the addition of bytecode.
amount;
return 0;
}
/**
* @dev Performs a flash loan. New tokens are minted and sent to the
* `receiver`, who is required to implement the {IERC3156FlashBorrower}
* interface. By the end of the flash loan, the receiver is expected to own
* amount + fee tokens and have them approved back to the token contract itself so
* they can be burned.
* @param receiver The receiver of the flash loan. Should implement the
* {IERC3156FlashBorrower.onFlashLoan} interface.
* @param token The token to be flash loaned. Only `address(this)` is
* supported.
* @param amount The amount of tokens to be loaned.
* @param data An arbitrary datafield that is passed to the receiver.
* @return `true` is the flash loan was successful.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) public virtual override returns (bool) {
uint256 fee = flashFee(token, amount);
_mint(address(receiver), amount);
require(
receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE,
"ERC20FlashMint: invalid return value"
);
uint256 currentAllowance = allowance(address(receiver), address(this));
require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund");
_approve(address(receiver), address(this), currentAllowance - amount - fee);
_burn(address(receiver), amount + fee);
return true;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156.sol)
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrower.sol";
import "./IERC3156FlashLender.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashBorrower.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC3156 FlashBorrower, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* _Available since v4.1._
*/
interface IERC3156FlashBorrower {
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashLender.sol)
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrower.sol";
/**
* @dev Interface of the ERC3156 FlashLender, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* _Available since v4.1._
*/
interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address token) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address token, uint256 amount) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
} | * @dev Interface of the ERC3156 FlashLender, as defined in _Available since v4.1._/ | interface IERC3156FlashLender {
function maxFlashLoan(address token) external view returns (uint256);
function flashFee(address token, uint256 amount) external view returns (uint256);
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
} | 5,903,153 | [
1,
1358,
434,
326,
4232,
39,
23,
28946,
15014,
48,
2345,
16,
487,
2553,
316,
389,
5268,
3241,
331,
24,
18,
21,
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,
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,
5831,
467,
654,
39,
23,
28946,
11353,
48,
2345,
288,
203,
565,
445,
943,
11353,
1504,
304,
12,
2867,
1147,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
9563,
14667,
12,
2867,
1147,
16,
2254,
5034,
3844,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
9563,
1504,
304,
12,
203,
3639,
467,
654,
39,
23,
28946,
11353,
38,
15318,
264,
5971,
16,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
97,
203,
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
] |
./partial_match/1/0xda99cbAaa7307D4e0c3D1CF83D459f9ad729e9C8/sources/contracts/twap/base/UniswapV3TwapLiquidityManager.sol | shift the index element at last of array | ticks[_tickIndex] = ticks[ticks.length - 1];
| 3,692,537 | [
1,
4012,
326,
770,
930,
622,
1142,
434,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13003,
63,
67,
6470,
1016,
65,
273,
13003,
63,
11767,
18,
2469,
300,
404,
15533,
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
] |
/*
___ _ ___ _
| .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___
| _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._>
|_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___.
* PeriFinance: Issuer.sol
*
* Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/Issuer.sol
* Docs: Will be added in the future.
* https://docs.peri.finance/contracts/source/contracts/Issuer
*
* Contract Dependencies:
* - IAddressResolver
* - IIssuer
* - MixinResolver
* - MixinSystemSettings
* - Owned
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 PeriFinance
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity 0.5.16;
// https://docs.peri.finance/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// https://docs.peri.finance/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getPynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.peri.finance/contracts/source/interfaces/ipynth
interface IPynth {
// Views
function currencyKey() external view returns (bytes32);
function transferablePynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to PeriFinance
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function canBurnPynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function externalTokenLimit() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function externalTokenQuota(
address _account,
uint _addtionalpUSD,
uint _addtionalExToken,
bool _isIssue
) external view returns (uint);
function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey)
external
view
returns (uint issueAmountToQuota, uint stakeAmountToQuota);
function minimumStakeTime() external view returns (uint);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to PeriFinance
function issuePynths(
address _issuer,
bytes32 _currencyKey,
uint _issueAmount
) external;
function issueMaxPynths(address _issuer) external;
function issuePynthsToMaxQuota(address _issuer, bytes32 _currencyKey) external;
function burnPynths(
address _from,
bytes32 _currencyKey,
uint _burnAmount
) external;
function fitToClaimable(address _from) external;
function exit(address _from) external;
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getPynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.pynths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.peri.finance/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.peri.finance/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
// Internal references
// https://docs.peri.finance/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver {
bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings";
bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs";
bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor";
bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio";
bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration";
bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold";
bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay";
bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio";
bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty";
bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod";
bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate";
bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime";
bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags";
bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled";
bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime";
bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit";
bytes32 internal constant SETTING_EXTERNAL_TOKEN_QUOTA = "externalTokenQuota";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal}
constructor(address _resolver) internal MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](1);
addresses[0] = CONTRACT_FLEXIBLESTORAGE;
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) {
if (gasLimitType == CrossDomainMessageGasLimits.Deposit) {
return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) {
return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Reward) {
return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) {
return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT;
} else {
revert("Unknown gas limit type");
}
}
function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType));
}
function getTradingRewardsEnabled() internal view returns (bool) {
return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED);
}
function getWaitingPeriodSecs() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS);
}
function getPriceDeviationThresholdFactor() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR);
}
function getIssuanceRatio() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO);
}
function getFeePeriodDuration() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION);
}
function getTargetThreshold() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD);
}
function getLiquidationDelay() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY);
}
function getLiquidationRatio() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO);
}
function getLiquidationPenalty() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY);
}
function getRateStalePeriod() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD);
}
function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getMinimumStakeTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME);
}
function getAggregatorWarningFlags() internal view returns (address) {
return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS);
}
function getDebtSnapshotStaleTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME);
}
function getExternalTokenQuota() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_EXTERNAL_TOKEN_QUOTA);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.peri.finance/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @dev Round down the value with given number
*/
function roundDownDecimal(uint x, uint d) internal pure returns (uint) {
return x.div(10**d).mul(10**d);
}
/**
* @dev Round up the value with given number
*/
function roundUpDecimal(uint x, uint d) internal pure returns (uint) {
uint _decimal = 10**d;
if (x % _decimal > 0) {
x = x.add(10**d);
}
return x.div(_decimal).mul(_decimal);
}
}
interface IVirtualPynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function pynth() external view returns (IPynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iperiFinance
interface IPeriFinance {
// Views
function getRequiredAddress(bytes32 contractName) external view returns (address);
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint);
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
function maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function externalTokenQuota(
address _account,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) external view returns (uint);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey)
external
view
returns (uint issueAmountToQuota, uint stakeAmountToQuota);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey) external view returns (uint);
function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint);
function transferablePeriFinance(address account) external view returns (uint transferable);
// Mutative Functions
function issuePynths(bytes32 _currencyKey, uint _issueAmount) external;
function issueMaxPynths() external;
function issuePynthsToMaxQuota(bytes32 _currencyKey) external;
function burnPynths(bytes32 _currencyKey, uint _burnAmount) external;
function fitToClaimable() external;
function exit() external;
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth);
function mint(address _user, uint _amount) external returns (bool);
function inflationalMint(uint _networkDebtShare) external returns (bool);
function settle(bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
// Liquidations
function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool);
// Restricted Functions
function mintSecondary(address account, uint amount) external;
function mintSecondaryRewards(uint amount) external;
function burnSecondary(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to PeriFinance
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint pUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iperiFinancestate
interface IPeriFinanceState {
// Views
function debtLedger(uint index) external view returns (uint);
function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex);
function debtLedgerLength() external view returns (uint);
function hasIssued(address account) external view returns (bool);
function lastDebtLedgerEntry() external view returns (uint);
// Mutative functions
function incrementTotalIssuerCount() external;
function decrementTotalIssuerCount() external;
function setCurrentIssuanceData(address account, uint initialDebtOwnership) external;
function appendDebtLedgerValue(uint value) external;
function clearIssuanceData(address account) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isPynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function setLastExchangeRateForPynth(bytes32 currencyKey, uint rate) external;
function suspendPynthWithInvalidRate(bytes32 currencyKey) external;
}
// https://docs.peri.finance/contracts/source/interfaces/idelegateapprovals
interface IDelegateApprovals {
// Views
function canBurnFor(address authoriser, address delegate) external view returns (bool);
function canIssueFor(address authoriser, address delegate) external view returns (bool);
function canClaimFor(address authoriser, address delegate) external view returns (bool);
function canExchangeFor(address authoriser, address delegate) external view returns (bool);
// Mutative
function approveAllDelegatePowers(address delegate) external;
function removeAllDelegatePowers(address delegate) external;
function approveBurnOnBehalf(address delegate) external;
function removeBurnOnBehalf(address delegate) external;
function approveIssueOnBehalf(address delegate) external;
function removeIssueOnBehalf(address delegate) external;
function approveClaimOnBehalf(address delegate) external;
function removeClaimOnBehalf(address delegate) external;
function approveExchangeOnBehalf(address delegate) external;
function removeExchangeOnBehalf(address delegate) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iexchangerates
interface IExchangeRates {
// Structs
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozenAtUpperLimit;
bool frozenAtLowerLimit;
}
// Views
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
// Mutative functions
function freezeRate(bytes32 currencyKey) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iethercollateral
interface IEtherCollateral {
// Views
function totalIssuedPynths() external view returns (uint256);
function totalLoansCreated() external view returns (uint256);
function totalOpenLoanCount() external view returns (uint256);
// Mutative functions
function openLoan() external payable returns (uint256 loanID);
function closeLoan(uint256 loanID) external;
function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iethercollateralsusd
interface IEtherCollateralpUSD {
// Views
function totalIssuedPynths() external view returns (uint256);
function totalLoansCreated() external view returns (uint256);
function totalOpenLoanCount() external view returns (uint256);
// Mutative functions
function openLoan(uint256 _loanAmount) external payable returns (uint256 loanID);
function closeLoan(uint256 loanID) external;
function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external;
function depositCollateral(address account, uint256 loanID) external payable;
function withdrawCollateral(uint256 loanID, uint256 withdrawAmount) external;
function repayLoan(
address _loanCreatorsAddress,
uint256 _loanID,
uint256 _repayAmount
) external;
}
// https://docs.peri.finance/contracts/source/interfaces/ihasbalance
interface IHasBalance {
// Views
function balanceOf(address account) external view returns (uint);
}
// https://docs.peri.finance/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.peri.finance/contracts/source/interfaces/iliquidations
interface ILiquidations {
// Views
function isOpenForLiquidation(address account) external view returns (bool);
function getLiquidationDeadlineForAccount(address account) external view returns (uint);
function isLiquidationDeadlinePassed(address account) external view returns (bool);
function liquidationDelay() external view returns (uint);
function liquidationRatio() external view returns (uint);
function liquidationPenalty() external view returns (uint);
function calculateAmountToFixCollateral(uint debtBalance, uint collateral) external view returns (uint);
// Mutative Functions
function flagAccountForLiquidation(address account) external;
// Restricted: used internally to PeriFinance
function removeAccountInLiquidation(address account) external;
function checkAndRemoveAccountInLiquidation(address account) external;
}
interface ICollateralManager {
// Manager information
function hasCollateral(address collateral) external view returns (bool);
function isPynthManaged(bytes32 currencyKey) external view returns (bool);
// State information
function long(bytes32 pynth) external view returns (uint amount);
function short(bytes32 pynth) external view returns (uint amount);
function totalLong() external view returns (uint pusdValue, bool anyRateIsInvalid);
function totalShort() external view returns (uint pusdValue, bool anyRateIsInvalid);
function getBorrowRate() external view returns (uint borrowRate, bool anyRateIsInvalid);
function getShortRate(bytes32 pynth) external view returns (uint shortRate, bool rateIsInvalid);
function getRatesAndTime(uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function getShortRatesAndTime(bytes32 currency, uint index)
external
view
returns (
uint entryRate,
uint lastRate,
uint lastUpdated,
uint newIndex
);
function exceedsDebtLimit(uint amount, bytes32 currency) external view returns (bool canIssue, bool anyRateIsInvalid);
function arePynthsAndCurrenciesSet(bytes32[] calldata requiredPynthNamesInResolver, bytes32[] calldata pynthKeys)
external
view
returns (bool);
function areShortablePynthsSet(bytes32[] calldata requiredPynthNamesInResolver, bytes32[] calldata pynthKeys)
external
view
returns (bool);
// Loans
function getNewLoanId() external returns (uint id);
// Manager mutative
function addCollaterals(address[] calldata collaterals) external;
function removeCollaterals(address[] calldata collaterals) external;
function addPynths(bytes32[] calldata pynthNamesInResolver, bytes32[] calldata pynthKeys) external;
function removePynths(bytes32[] calldata pynths, bytes32[] calldata pynthKeys) external;
function addShortablePynths(bytes32[2][] calldata requiredPynthAndInverseNamesInResolver, bytes32[] calldata pynthKeys)
external;
function removeShortablePynths(bytes32[] calldata pynths) external;
// State mutative
function updateBorrowRates(uint rate) external;
function updateShortRates(bytes32 currency, uint rate) external;
function incrementLongs(bytes32 pynth, uint amount) external;
function decrementLongs(bytes32 pynth, uint amount) external;
function incrementShorts(bytes32 pynth, uint amount) external;
function decrementShorts(bytes32 pynth, uint amount) external;
}
contract IExternalTokenStakeManager {
function stake(
address _staker,
uint _amount,
bytes32 _targetCurrency,
bytes32 _inputCurrency
) external;
function unstake(
address _unstaker,
uint _amount,
bytes32 _targetCurrency,
bytes32 _inputCurrency
) external;
function unstakeMultipleTokens(
address _unstaker,
uint _amount,
bytes32 _inputCurrency
) external;
function getTokenList() external view returns (bytes32[] memory);
function getTokenAddress(bytes32 _currencyKey) external view returns (address);
function getTokenDecimals(bytes32 _currencyKey) external view returns (uint8);
function getTokenActivation(bytes32 _currencyKey) external view returns (bool);
function getCurrencyKeyOrder() external view returns (bytes32[] memory);
function combinedStakedAmountOf(address _user, bytes32 _unitCurrency) external view returns (uint);
function stakedAmountOf(
address _user,
bytes32 _currencyKey,
bytes32 _unitCurrency
) external view returns (uint);
}
// Inheritance
// Libraries
// Internal references
interface IRewardEscrowV2 {
// Views
function balanceOf(address account) external view returns (uint);
}
interface IIssuerInternalDebtCache {
function updateCachedPynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external;
function updateCachedPynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateDebtCacheValidity(bool currentlyInvalid) external;
function cacheInfo()
external
view
returns (
uint cachedDebt,
uint timestamp,
bool isInvalid,
bool isStale
);
}
// https://docs.peri.finance/contracts/source/contracts/issuer
contract Issuer is Owned, MixinSystemSettings, IIssuer {
using SafeMath for uint;
using SafeDecimalMath for uint;
// Available Pynths which can be used with the system
IPynth[] public availablePynths;
mapping(bytes32 => IPynth) public pynths;
mapping(address => bytes32) public pynthsByAddress;
/* ========== ENCODED NAMES ========== */
bytes32 internal constant pUSD = "pUSD";
bytes32 internal constant pETH = "pETH";
bytes32 internal constant PERI = "PERI";
bytes32 internal constant USDC = "USDC";
// Flexible storage names
bytes32 public constant CONTRACT_NAME = "Issuer";
bytes32 internal constant LAST_ISSUE_EVENT = "lastIssueEvent";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_PERIFINANCE = "PeriFinance";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral";
bytes32 private constant CONTRACT_ETHERCOLLATERAL_PUSD = "EtherCollateralpUSD";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_PERIFINANCEESCROW = "PeriFinanceEscrow";
bytes32 private constant CONTRACT_LIQUIDATIONS = "Liquidations";
bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache";
bytes32 private constant CONTRACT_EXTOKENSTAKEMANAGER = "ExternalTokenStakeManager";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](14);
newAddresses[0] = CONTRACT_PERIFINANCE;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_PERIFINANCESTATE;
newAddresses[4] = CONTRACT_FEEPOOL;
newAddresses[5] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[6] = CONTRACT_ETHERCOLLATERAL;
newAddresses[7] = CONTRACT_ETHERCOLLATERAL_PUSD;
newAddresses[8] = CONTRACT_REWARDESCROW_V2;
newAddresses[9] = CONTRACT_PERIFINANCEESCROW;
newAddresses[10] = CONTRACT_LIQUIDATIONS;
newAddresses[11] = CONTRACT_DEBTCACHE;
newAddresses[12] = CONTRACT_COLLATERALMANAGER;
newAddresses[13] = CONTRACT_EXTOKENSTAKEMANAGER;
return combineArrays(existingAddresses, newAddresses);
}
function periFinance() internal view returns (IPeriFinance) {
return IPeriFinance(requireAndGetAddress(CONTRACT_PERIFINANCE));
}
function exTokenStakeManager() internal view returns (IExternalTokenStakeManager) {
return IExternalTokenStakeManager(requireAndGetAddress(CONTRACT_EXTOKENSTAKEMANAGER));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function periFinanceState() internal view returns (IPeriFinanceState) {
return IPeriFinanceState(requireAndGetAddress(CONTRACT_PERIFINANCESTATE));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function liquidations() internal view returns (ILiquidations) {
return ILiquidations(requireAndGetAddress(CONTRACT_LIQUIDATIONS));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function etherCollateral() internal view returns (IEtherCollateral) {
return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL));
}
function etherCollateralpUSD() internal view returns (IEtherCollateralpUSD) {
return IEtherCollateralpUSD(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL_PUSD));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function periFinanceEscrow() internal view returns (IHasBalance) {
return IHasBalance(requireAndGetAddress(CONTRACT_PERIFINANCEESCROW));
}
function debtCache() internal view returns (IIssuerInternalDebtCache) {
return IIssuerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE));
}
function issuanceRatio() external view returns (uint) {
return getIssuanceRatio();
}
function externalTokenLimit() external view returns (uint) {
return getExternalTokenQuota();
}
function _availableCurrencyKeysWithOptionalPERI(bool withPERI) internal view returns (bytes32[] memory) {
bytes32[] memory currencyKeys = new bytes32[](availablePynths.length + (withPERI ? 1 : 0));
for (uint i = 0; i < availablePynths.length; i++) {
currencyKeys[i] = pynthsByAddress[address(availablePynths[i])];
}
if (withPERI) {
currencyKeys[availablePynths.length] = PERI;
}
return currencyKeys;
}
function _totalIssuedPynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
{
(uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo();
anyRateIsInvalid = cacheIsInvalid || cacheIsStale;
IExchangeRates exRates = exchangeRates();
// Add total issued pynths from non peri collateral back into the total if not excluded
if (!excludeCollateral) {
// Get the pUSD equivalent amount of all the MC issued pynths.
(uint nonPeriDebt, bool invalid) = collateralManager().totalLong();
debt = debt.add(nonPeriDebt);
anyRateIsInvalid = anyRateIsInvalid || invalid;
// Now add the ether collateral stuff as we are still supporting it.
debt = debt.add(etherCollateralpUSD().totalIssuedPynths());
// Add ether collateral pETH
(uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(pETH);
uint ethIssuedDebt = etherCollateral().totalIssuedPynths().multiplyDecimalRound(ethRate);
debt = debt.add(ethIssuedDebt);
anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid;
}
if (currencyKey == pUSD) {
return (debt, anyRateIsInvalid);
}
(uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey);
return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid);
}
function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey)
internal
view
returns (
uint debtBalance,
uint totalSystemValue,
bool anyRateIsInvalid
)
{
IPeriFinanceState state = periFinanceState();
// What was their initial debt ownership?
(uint initialDebtOwnership, uint debtEntryIndex) = state.issuanceData(_issuer);
// What's the total value of the system excluding ETH backed pynths in their requested currency?
(totalSystemValue, anyRateIsInvalid) = _totalIssuedPynths(currencyKey, true);
// If it's zero, they haven't issued, and they have no debt.
// Note: it's more gas intensive to put this check here rather than before _totalIssuedPynths
// if they have 0 PERI, but it's a necessary trade-off
if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsInvalid);
// Figure out the global debt percentage delta from when they entered the system.
// This is a high precision integer of 27 (1e27) decimals.
uint _debtLedgerLength = state.debtLedgerLength();
uint systemDebt = state.debtLedger(debtEntryIndex);
uint currentDebtOwnership;
if (_debtLedgerLength == 0 || systemDebt == 0) {
currentDebtOwnership = 0;
} else {
currentDebtOwnership = state
.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(systemDebt)
.multiplyDecimalRoundPrecise(initialDebtOwnership);
}
// Their debt balance is their portion of the total system value.
uint highPrecisionBalance =
totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise(currentDebtOwnership);
// Convert back into 18 decimals (1e18)
debtBalance = highPrecisionBalance.preciseDecimalToDecimal();
}
function _canBurnPynths(address account) internal view returns (bool) {
return now >= _lastIssueEvent(account).add(getMinimumStakeTime());
}
function _lastIssueEvent(address account) internal view returns (uint) {
// Get the timestamp of the last issue this account made
return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)));
}
function _remainingIssuablePynths(address _issuer)
internal
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt,
bool anyRateIsInvalid
)
{
(alreadyIssued, totalSystemDebt, anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, pUSD);
(uint issuable, bool isInvalid) = _maxIssuablePynths(_issuer);
maxIssuable = issuable;
anyRateIsInvalid = anyRateIsInvalid || isInvalid;
if (alreadyIssued >= maxIssuable) {
maxIssuable = 0;
} else {
maxIssuable = maxIssuable.sub(alreadyIssued);
}
}
function _periToUSD(uint amount, uint periRate) internal pure returns (uint) {
return amount.multiplyDecimalRound(periRate);
}
function _usdToPeri(uint amount, uint periRate) internal pure returns (uint) {
return amount.divideDecimalRound(periRate);
}
function _maxIssuablePynths(address _issuer) internal view returns (uint, bool) {
// What is the value of their PERI balance in pUSD
(uint periRate, bool periRateIsInvalid) = exchangeRates().rateAndInvalid(PERI);
uint periCollateral = _periToUSD(_collateral(_issuer), periRate);
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(_issuer, pUSD);
uint destinationValue = periCollateral.add(externalTokenStaked);
// They're allowed to issue up to issuanceRatio of that value
return (destinationValue.multiplyDecimal(getIssuanceRatio()), periRateIsInvalid);
}
function _collateralisationRatio(address _issuer) internal view returns (uint, bool) {
uint totalOwnedPeriFinance = _collateral(_issuer);
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(_issuer, PERI);
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, PERI);
// it's more gas intensive to put this check here if they have 0 PERI, but it complies with the interface
if (totalOwnedPeriFinance == 0 && externalTokenStaked == 0) return (0, anyRateIsInvalid);
uint totalOwned = totalOwnedPeriFinance.add(externalTokenStaked);
return (debtBalance.divideDecimal(totalOwned), anyRateIsInvalid);
}
function _collateral(address account) internal view returns (uint) {
uint balance = IERC20(address(periFinance())).balanceOf(account);
if (address(periFinanceEscrow()) != address(0)) {
balance = balance.add(periFinanceEscrow().balanceOf(account));
}
if (address(rewardEscrowV2()) != address(0)) {
balance = balance.add(rewardEscrowV2().balanceOf(account));
}
return balance;
}
/**
* @notice It calculates the quota of user's staked amount to the debt.
* If parameters are not 0, it estimates the quota assuming those value is applied to current status.
*
* @param _account account
* @param _debtBalance Debt balance to estimate [USD]
* @param _additionalpUSD The pUSD value to be applied for estimation [USD]
* @param _additionalExToken The external token stake amount to be applied for estimation [USD]
* @param _isIssue If true, it is considered issueing/staking estimation.
*/
function _externalTokenQuota(
address _account,
uint _debtBalance,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) internal view returns (uint) {
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_account, pUSD);
if (_debtBalance == 0 || combinedStakedAmount == 0) {
return 0;
}
if (_isIssue) {
_debtBalance = _debtBalance.add(_additionalpUSD);
combinedStakedAmount = combinedStakedAmount.add(_additionalExToken);
} else {
_debtBalance = _debtBalance.sub(_additionalpUSD);
combinedStakedAmount = combinedStakedAmount.sub(_additionalExToken);
}
return combinedStakedAmount.divideDecimalRound(_debtBalance.divideDecimalRound(getIssuanceRatio()));
}
function _amountsToFitClaimable(
uint _currentDebt,
uint _stakedExTokenAmount,
uint _periCollateral
) internal view returns (uint burnAmount, uint exTokenAmountToUnstake) {
uint targetRatio = getIssuanceRatio();
uint exTokenQuota = getExternalTokenQuota();
uint initialCRatio = _currentDebt.divideDecimal(_stakedExTokenAmount.add(_periCollateral));
// it doesn't satisfy target c-ratio
if (initialCRatio > targetRatio) {
uint maxAllowedExTokenStakeAmountByPeriCollateral =
_periCollateral.multiplyDecimal(exTokenQuota.divideDecimal(SafeDecimalMath.unit().sub(exTokenQuota)));
exTokenAmountToUnstake = _stakedExTokenAmount > maxAllowedExTokenStakeAmountByPeriCollateral
? _stakedExTokenAmount.sub(maxAllowedExTokenStakeAmountByPeriCollateral)
: 0;
burnAmount = _currentDebt.sub(
_periCollateral.add(_stakedExTokenAmount).sub(exTokenAmountToUnstake).multiplyDecimal(targetRatio)
);
// it satisfies target c-ratio but violates external token quota
} else {
uint currentExTokenQuota = _stakedExTokenAmount.multiplyDecimal(targetRatio).divideDecimal(_currentDebt);
require(currentExTokenQuota > exTokenQuota, "Account is already claimable");
burnAmount = (_stakedExTokenAmount.multiplyDecimal(targetRatio).sub(_currentDebt.multiplyDecimal(exTokenQuota)))
.divideDecimal(SafeDecimalMath.unit().sub(exTokenQuota));
exTokenAmountToUnstake = burnAmount.divideDecimal(targetRatio);
}
}
/**
* @notice It calculates maximum issue/stake(external token) amount to meet external token quota limit.
*
* @param _from target address
* @param _debtBalance current debt balance[pUSD]
* @param _stakedAmount currently target address's external token staked amount[pUSD]
* @param _currencyKey currency key of external token to stake
*/
function _maxExternalTokenStakeAmount(
address _from,
uint _debtBalance,
uint _stakedAmount,
bytes32 _currencyKey
) internal view returns (uint issueAmount, uint stakeAmount) {
uint targetRatio = getIssuanceRatio();
uint quotaLimit = getExternalTokenQuota();
uint maxAllowedStakingAmount = _debtBalance.multiplyDecimal(quotaLimit).divideDecimal(targetRatio);
if (_stakedAmount >= maxAllowedStakingAmount) {
return (0, 0);
}
stakeAmount = ((maxAllowedStakingAmount).sub(_stakedAmount)).divideDecimal(SafeDecimalMath.unit().sub(quotaLimit));
uint balance = IERC20(exTokenStakeManager().getTokenAddress(_currencyKey)).balanceOf(_from);
stakeAmount = balance < stakeAmount ? balance : stakeAmount;
issueAmount = stakeAmount.multiplyDecimal(targetRatio);
}
function minimumStakeTime() external view returns (uint) {
return getMinimumStakeTime();
}
function canBurnPynths(address account) external view returns (bool) {
return _canBurnPynths(account);
}
function availableCurrencyKeys() external view returns (bytes32[] memory) {
return _availableCurrencyKeysWithOptionalPERI(false);
}
function availablePynthCount() external view returns (uint) {
return availablePynths.length;
}
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) {
(, anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(_availableCurrencyKeysWithOptionalPERI(true));
}
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint totalIssued) {
(totalIssued, ) = _totalIssuedPynths(currencyKey, excludeEtherCollateral);
}
function lastIssueEvent(address account) external view returns (uint) {
return _lastIssueEvent(account);
}
function collateralisationRatio(address _issuer) external view returns (uint cratio) {
(cratio, ) = _collateralisationRatio(_issuer);
}
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid)
{
return _collateralisationRatio(_issuer);
}
function collateral(address account) external view returns (uint) {
return _collateral(account);
}
function debtBalanceOf(address _issuer, bytes32 currencyKey) external view returns (uint debtBalance) {
IPeriFinanceState state = periFinanceState();
// What was their initial debt ownership?
(uint initialDebtOwnership, ) = state.issuanceData(_issuer);
// If it's zero, they haven't issued, and they have no debt.
if (initialDebtOwnership == 0) return 0;
(debtBalance, , ) = _debtBalanceOfAndTotalDebt(_issuer, currencyKey);
}
function remainingIssuablePynths(address _issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
)
{
(maxIssuable, alreadyIssued, totalSystemDebt, ) = _remainingIssuablePynths(_issuer);
}
function maxIssuablePynths(address _issuer) external view returns (uint) {
(uint maxIssuable, ) = _maxIssuablePynths(_issuer);
return maxIssuable;
}
function externalTokenQuota(
address _account,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) external view returns (uint) {
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_account, pUSD);
_requireRatesNotInvalid(anyRateIsInvalid);
uint estimatedQuota = _externalTokenQuota(_account, debtBalance, _additionalpUSD, _additionalExToken, _isIssue);
return estimatedQuota;
}
function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey)
external
view
returns (uint issueAmountToQuota, uint stakeAmountToQuota)
{
(uint debtBalance, , ) = _debtBalanceOfAndTotalDebt(_account, pUSD);
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_account, pUSD);
(issueAmountToQuota, stakeAmountToQuota) = _maxExternalTokenStakeAmount(
_account,
debtBalance,
combinedStakedAmount,
_currencyKey
);
}
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid)
{
// How many PERI do they have, excluding escrow?
// Note: We're excluding escrow here because we're interested in their transferable amount
// and escrowed PERI are not transferable.
// How many of those will be locked by the amount they've issued?
// Assuming issuance ratio is 20%, then issuing 20 PERI of value would require
// 100 PERI to be locked in their wallet to maintain their collateralisation ratio
// The locked periFinance value can exceed their balance.
(uint debtBalance, , bool rateIsInvalid) = _debtBalanceOfAndTotalDebt(account, PERI);
uint debtAppliedIssuanceRatio = debtBalance.divideDecimalRound(getIssuanceRatio());
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(account, PERI);
// If external token staked balance is larger than required collateral amount for current debt,
// no PERI would be locked. (But it violates external token staking quota rule)
uint lockedPeriFinanceValue =
debtAppliedIssuanceRatio > externalTokenStaked ? debtAppliedIssuanceRatio.sub(externalTokenStaked) : 0;
// If we exceed the balance, no PERI are transferable, otherwise the difference is.
if (lockedPeriFinanceValue >= balance) {
transferable = 0;
} else {
transferable = balance.sub(lockedPeriFinanceValue);
}
anyRateIsInvalid = rateIsInvalid;
}
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory) {
uint numKeys = currencyKeys.length;
IPynth[] memory addresses = new IPynth[](numKeys);
for (uint i = 0; i < numKeys; i++) {
addresses[i] = pynths[currencyKeys[i]];
}
return addresses;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _addPynth(IPynth pynth) internal {
bytes32 currencyKey = pynth.currencyKey();
require(pynths[currencyKey] == IPynth(0), "Pynth exists");
require(pynthsByAddress[address(pynth)] == bytes32(0), "Pynth address already exists");
availablePynths.push(pynth);
pynths[currencyKey] = pynth;
pynthsByAddress[address(pynth)] = currencyKey;
emit PynthAdded(currencyKey, address(pynth));
}
function addPynth(IPynth pynth) external onlyOwner {
_addPynth(pynth);
// Invalidate the cache to force a snapshot to be recomputed. If a pynth were to be added
// back to the system and it still somehow had cached debt, this would force the value to be
// updated.
debtCache().updateDebtCacheValidity(true);
}
function addPynths(IPynth[] calldata pynthsToAdd) external onlyOwner {
uint numPynths = pynthsToAdd.length;
for (uint i = 0; i < numPynths; i++) {
_addPynth(pynthsToAdd[i]);
}
// Invalidate the cache to force a snapshot to be recomputed.
debtCache().updateDebtCacheValidity(true);
}
function _removePynth(bytes32 currencyKey) internal {
address pynthToRemove = address(pynths[currencyKey]);
require(pynthToRemove != address(0), "Pynth does not exist");
require(IERC20(pynthToRemove).totalSupply() == 0, "Pynth supply exists");
require(currencyKey != pUSD, "Cannot remove pynth");
// Remove the pynth from the availablePynths array.
for (uint i = 0; i < availablePynths.length; i++) {
if (address(availablePynths[i]) == pynthToRemove) {
delete availablePynths[i];
// Copy the last pynth into the place of the one we just deleted
// If there's only one pynth, this is pynths[0] = pynths[0].
// If we're deleting the last one, it's also a NOOP in the same way.
availablePynths[i] = availablePynths[availablePynths.length - 1];
// Decrease the size of the array by one.
availablePynths.length--;
break;
}
}
// And remove it from the pynths mapping
delete pynthsByAddress[pynthToRemove];
delete pynths[currencyKey];
emit PynthRemoved(currencyKey, pynthToRemove);
}
function removePynth(bytes32 currencyKey) external onlyOwner {
// Remove its contribution from the debt pool snapshot, and
// invalidate the cache to force a new snapshot.
IIssuerInternalDebtCache cache = debtCache();
cache.updateCachedPynthDebtWithRate(currencyKey, 0);
cache.updateDebtCacheValidity(true);
_removePynth(currencyKey);
}
function removePynths(bytes32[] calldata currencyKeys) external onlyOwner {
uint numKeys = currencyKeys.length;
// Remove their contributions from the debt pool snapshot, and
// invalidate the cache to force a new snapshot.
IIssuerInternalDebtCache cache = debtCache();
uint[] memory zeroRates = new uint[](numKeys);
cache.updateCachedPynthDebtsWithRates(currencyKeys, zeroRates);
cache.updateDebtCacheValidity(true);
for (uint i = 0; i < numKeys; i++) {
_removePynth(currencyKeys[i]);
}
}
function issuePynths(
address _issuer,
bytes32 _currencyKey,
uint _issueAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
if (_currencyKey != PERI) {
uint amountToStake = _issueAmount.divideDecimalRound(getIssuanceRatio());
(uint initialDebtOwnership, ) = periFinanceState().issuanceData(_issuer);
// Condition of policy, user must have any amount of PERI locked before staking external token.
require(initialDebtOwnership > 0, "User does not have any debt yet");
exTokenStakeManager().stake(_issuer, amountToStake, _currencyKey, pUSD);
}
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
uint afterDebtBalance = _issuePynths(_issuer, _issueAmount, maxIssuable, existingDebt, totalSystemDebt, false);
// For preventing additional gas consumption by calculating debt twice, the quota checker is placed here.
_requireNotExceedsQuotaLimit(_issuer, afterDebtBalance, 0, 0, true);
}
function issueMaxPynths(address _issuer) external onlyPeriFinance {
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
_issuePynths(_issuer, 0, maxIssuable, existingDebt, totalSystemDebt, true);
}
function issuePynthsToMaxQuota(address _issuer, bytes32 _currencyKey) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
require(_currencyKey != PERI, "Only external token allowed to stake");
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
require(existingDebt > 0, "User does not have any debt yet");
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_issuer, pUSD);
(uint issueAmountToQuota, uint stakeAmountToQuota) =
_maxExternalTokenStakeAmount(_issuer, existingDebt, combinedStakedAmount, _currencyKey);
require(issueAmountToQuota > 0 && stakeAmountToQuota > 0, "No available external token staking amount");
exTokenStakeManager().stake(_issuer, stakeAmountToQuota, _currencyKey, pUSD);
// maxIssuable should be increased for increased collateral
maxIssuable = maxIssuable.add(issueAmountToQuota);
uint afterDebtBalance = _issuePynths(_issuer, issueAmountToQuota, maxIssuable, existingDebt, totalSystemDebt, false);
// For preventing additional gas consumption by calculating debt twice, the quota checker is placed here.
_requireNotExceedsQuotaLimit(_issuer, afterDebtBalance, 0, 0, true);
}
function burnPynths(
address _from,
bytes32 _currencyKey,
uint _burnAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
uint remainingDebt = _voluntaryBurnPynths(_from, _burnAmount, false, false);
if (_currencyKey == PERI) {
_requireNotExceedsQuotaLimit(_from, remainingDebt, 0, 0, false);
}
if (_currencyKey != PERI) {
exTokenStakeManager().unstake(_from, _burnAmount.divideDecimalRound(getIssuanceRatio()), _currencyKey, pUSD);
}
}
function fitToClaimable(address _from) external onlyPeriFinance {
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_from, pUSD);
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_from, pUSD);
(uint periRate, bool isPeriInvalid) = exchangeRates().rateAndInvalid(PERI);
uint periCollateralToUSD = _periToUSD(_collateral(_from), periRate);
_requireRatesNotInvalid(anyRateIsInvalid || isPeriInvalid);
(uint burnAmount, uint amountToUnstake) =
_amountsToFitClaimable(debtBalance, combinedStakedAmount, periCollateralToUSD);
_voluntaryBurnPynths(_from, burnAmount, true, false);
exTokenStakeManager().unstakeMultipleTokens(_from, amountToUnstake, pUSD);
}
function exit(address _from) external onlyPeriFinance {
_voluntaryBurnPynths(_from, 0, true, true);
bytes32[] memory tokenList = exTokenStakeManager().getTokenList();
for (uint i = 0; i < tokenList.length; i++) {
uint stakedAmount = exTokenStakeManager().stakedAmountOf(_from, tokenList[i], tokenList[i]);
if (stakedAmount == 0) {
continue;
}
exTokenStakeManager().unstake(_from, stakedAmount, tokenList[i], tokenList[i]);
}
}
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external onlyPeriFinance returns (uint totalRedeemed, uint amountToLiquidate) {
// Ensure waitingPeriod and pUSD balance is settled as burning impacts the size of debt pool
require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, pUSD), "pUSD needs to be settled");
// Check account is liquidation open
require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation");
// require liquidator has enough pUSD
require(IERC20(address(pynths[pUSD])).balanceOf(liquidator) >= pusdAmount, "Not enough pUSD");
uint liquidationPenalty = liquidations().liquidationPenalty();
// What is their debt in pUSD?
(uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, pUSD);
(uint periRate, bool periRateInvalid) = exchangeRates().rateAndInvalid(PERI);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
uint collateralForAccount = _collateral(account);
uint amountToFixRatio =
liquidations().calculateAmountToFixCollateral(debtBalance, _periToUSD(collateralForAccount, periRate));
// Cap amount to liquidate to repair collateral ratio based on issuance ratio
amountToLiquidate = amountToFixRatio < pusdAmount ? amountToFixRatio : pusdAmount;
// what's the equivalent amount of peri for the amountToLiquidate?
uint periRedeemed = _usdToPeri(amountToLiquidate, periRate);
// Add penalty
totalRedeemed = periRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty));
// if total PERI to redeem is greater than account's collateral
// account is under collateralised, liquidate all collateral and reduce pUSD to burn
if (totalRedeemed > collateralForAccount) {
// set totalRedeemed to all transferable collateral
totalRedeemed = collateralForAccount;
// whats the equivalent pUSD to burn for all collateral less penalty
amountToLiquidate = _periToUSD(
collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)),
periRate
);
}
// burn pUSD from messageSender (liquidator) and reduce account's debt
_burnPynths(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued);
// Remove liquidation flag if amount liquidated fixes ratio
if (amountToLiquidate == amountToFixRatio) {
// Remove liquidation
liquidations().removeAccountInLiquidation(account);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _requireRatesNotInvalid(bool anyRateIsInvalid) internal pure {
require(!anyRateIsInvalid, "A pynth or PERI rate is invalid");
}
function _requireCanIssueOnBehalf(address issueForAddress, address from) internal view {
require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf");
}
function _requireCanBurnOnBehalf(address burnForAddress, address from) internal view {
require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf");
}
function _requireCurrencyKeyIsNotpUSD(bytes32 _currencyKey) internal pure {
require(_currencyKey != pUSD, "pUSD is not staking coin");
}
function _requireNotExceedsQuotaLimit(
address _account,
uint _debtBalance,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) internal view {
uint estimatedExternalTokenQuota =
_externalTokenQuota(_account, _debtBalance, _additionalpUSD, _additionalExToken, _isIssue);
bytes32[] memory tokenList = exTokenStakeManager().getTokenList();
uint minDecimals = 18;
for (uint i = 0; i < tokenList.length; i++) {
uint decimals = exTokenStakeManager().getTokenDecimals(tokenList[i]);
minDecimals = decimals < minDecimals ? decimals : minDecimals;
}
require(
// due to the error caused by decimal difference, round down it upto minimum decimals among staking token list.
estimatedExternalTokenQuota.roundDownDecimal(uint(18).sub(minDecimals)) <= getExternalTokenQuota(),
"External token staking amount exceeds quota limit"
);
}
function _issuePynths(
address from,
uint amount,
uint maxIssuable,
uint existingDebt,
uint totalSystemDebt,
bool issueMax
) internal returns (uint afterDebt) {
if (!issueMax) {
require(amount <= maxIssuable, "Amount too large");
} else {
amount = maxIssuable;
}
// Keep track of the debt they're about to create
_addToDebtRegister(from, amount, existingDebt, totalSystemDebt);
// record issue timestamp
_setLastIssueEvent(from);
// Create their pynths
pynths[pUSD].issue(from, amount);
// Account for the issued debt in the cache
debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit());
// Store their locked PERI amount to determine their fee % for the period
_appendAccountIssuanceRecord(from);
afterDebt = existingDebt.add(amount);
}
function _burnPynths(
address debtAccount,
address burnAccount,
uint amountBurnt,
uint existingDebt,
uint totalDebtIssued
) internal returns (uint) {
// liquidation requires pUSD to be already settled / not in waiting period
require(amountBurnt <= existingDebt, "Trying to burn more than debt");
// Remove liquidated debt from the ledger
_removeFromDebtRegister(debtAccount, amountBurnt, existingDebt, totalDebtIssued);
// pynth.burn does a safe subtraction on balance (so it will revert if there are not enough pynths).
pynths[pUSD].burn(burnAccount, amountBurnt);
// Account for the burnt debt in the cache.
debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit());
// Store their debtRatio against a fee period to determine their fee/rewards % for the period
_appendAccountIssuanceRecord(debtAccount);
return amountBurnt;
}
// If burning to target, `amount` is ignored, and the correct quantity of pUSD is burnt to reach the target
// c-ratio, allowing fees to be claimed. In this case, pending settlements will be skipped as the user
// will still have debt remaining after reaching their target.
function _voluntaryBurnPynths(
address from,
uint amount,
bool burnToTarget,
bool burnMax
) internal returns (uint remainingDebt) {
if (!burnToTarget) {
// If not burning to target, then burning requires that the minimum stake time has elapsed.
require(_canBurnPynths(from), "Minimum stake time not reached");
// First settle anything pending into pUSD as burning or issuing impacts the size of the debt pool
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD);
(uint maxIssuablePynthsForAccount, bool periRateInvalid) = _maxIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnMax) {
amount = existingDebt;
}
uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue);
remainingDebt = existingDebt.sub(amountBurnt);
// Check and remove liquidation if existingDebt after burning is <= maxIssuablePynths
// Issuance ratio is fixed so should remove any liquidations
if (existingDebt >= amountBurnt && remainingDebt <= maxIssuablePynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _setLastIssueEvent(address account) internal {
// Set the timestamp of the last issuePynths
flexibleStorage().setUIntValue(
CONTRACT_NAME,
keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)),
block.timestamp
);
}
function _appendAccountIssuanceRecord(address from) internal {
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = periFinanceState().issuanceData(from);
feePool().appendAccountIssuanceRecord(from, initialDebtOwnership, debtEntryIndex);
}
function _addToDebtRegister(
address from,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
// What will the new total be including the new value?
uint newTotalDebtIssued = amount.add(totalDebtIssued);
// What is their percentage (as a high precision int) of the total debt?
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
// The delta is a high precision integer.
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
// And what does their debt ownership look like including this previous stake?
if (existingDebt > 0) {
debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
} else {
// If they have no debt, they're a new issuer; record this.
state.incrementTotalIssuerCount();
}
// Save the debt entry parameters
state.setCurrentIssuanceData(from, debtPercentage);
// And if we're the first, push 1 as there was no effect to any other holders, otherwise push
// the change for the rest of the debt holders. The debt ledger holds high precision integers.
if (state.debtLedgerLength() > 0 && state.lastDebtLedgerEntry() != 0) {
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
} else {
state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
function _removeFromDebtRegister(
address from,
uint debtToRemove,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
// What will the new total after taking out the withdrawn amount
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta = 0;
// What will the debt delta be if there is any debt left?
// Set delta to 0 if no more debt left in system after user
if (newTotalDebtIssued > 0) {
// What is the percentage of the withdrawn debt (as a high precision int) of the total debt after?
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
}
// Are they exiting the system, or are they just decreasing their debt position?
if (debtToRemove == existingDebt) {
state.setCurrentIssuanceData(from, 0);
state.decrementTotalIssuerCount();
} else {
// What percentage of the debt will they be left with?
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
// Store the debt percentage and debt ledger as high precision integers
state.setCurrentIssuanceData(from, newDebtPercentage);
}
// Update our cumulative ledger. This is also a high precision integer.
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
}
/* ========== MODIFIERS ========== */
function _onlyPeriFinance() internal view {
require(msg.sender == address(periFinance()), "Issuer: Only the periFinance contract can perform this action");
}
modifier onlyPeriFinance() {
_onlyPeriFinance(); // Use an internal function to save code size.
_;
}
/* ========== EVENTS ========== */
event PynthAdded(bytes32 currencyKey, address pynth);
event PynthRemoved(bytes32 currencyKey, address pynth);
}
| ERROR: type should be string, got " https:docs.peri.finance/contracts/source/contracts/issuer Available Pynths which can be used with the system Flexible storage names" | contract Issuer is Owned, MixinSystemSettings, IIssuer {
using SafeMath for uint;
using SafeDecimalMath for uint;
IPynth[] public availablePynths;
mapping(bytes32 => IPynth) public pynths;
mapping(address => bytes32) public pynthsByAddress;
bytes32 internal constant pUSD = "pUSD";
bytes32 internal constant pETH = "pETH";
bytes32 internal constant PERI = "PERI";
bytes32 internal constant USDC = "USDC";
bytes32 public constant CONTRACT_NAME = "Issuer";
bytes32 internal constant LAST_ISSUE_EVENT = "lastIssueEvent";
bytes32 private constant CONTRACT_PERIFINANCE = "PeriFinance";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral";
bytes32 private constant CONTRACT_ETHERCOLLATERAL_PUSD = "EtherCollateralpUSD";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_PERIFINANCEESCROW = "PeriFinanceEscrow";
bytes32 private constant CONTRACT_LIQUIDATIONS = "Liquidations";
bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache";
bytes32 private constant CONTRACT_EXTOKENSTAKEMANAGER = "ExternalTokenStakeManager";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
function freezeRate(bytes32 currencyKey) external;
}
}
}
}
}
}
}
}
}
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](14);
newAddresses[0] = CONTRACT_PERIFINANCE;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_PERIFINANCESTATE;
newAddresses[4] = CONTRACT_FEEPOOL;
newAddresses[5] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[6] = CONTRACT_ETHERCOLLATERAL;
newAddresses[7] = CONTRACT_ETHERCOLLATERAL_PUSD;
newAddresses[8] = CONTRACT_REWARDESCROW_V2;
newAddresses[9] = CONTRACT_PERIFINANCEESCROW;
newAddresses[10] = CONTRACT_LIQUIDATIONS;
newAddresses[11] = CONTRACT_DEBTCACHE;
newAddresses[12] = CONTRACT_COLLATERALMANAGER;
newAddresses[13] = CONTRACT_EXTOKENSTAKEMANAGER;
return combineArrays(existingAddresses, newAddresses);
}
function periFinance() internal view returns (IPeriFinance) {
return IPeriFinance(requireAndGetAddress(CONTRACT_PERIFINANCE));
}
function exTokenStakeManager() internal view returns (IExternalTokenStakeManager) {
return IExternalTokenStakeManager(requireAndGetAddress(CONTRACT_EXTOKENSTAKEMANAGER));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function periFinanceState() internal view returns (IPeriFinanceState) {
return IPeriFinanceState(requireAndGetAddress(CONTRACT_PERIFINANCESTATE));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function liquidations() internal view returns (ILiquidations) {
return ILiquidations(requireAndGetAddress(CONTRACT_LIQUIDATIONS));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function etherCollateral() internal view returns (IEtherCollateral) {
return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL));
}
function etherCollateralpUSD() internal view returns (IEtherCollateralpUSD) {
return IEtherCollateralpUSD(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL_PUSD));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function periFinanceEscrow() internal view returns (IHasBalance) {
return IHasBalance(requireAndGetAddress(CONTRACT_PERIFINANCEESCROW));
}
function debtCache() internal view returns (IIssuerInternalDebtCache) {
return IIssuerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE));
}
function issuanceRatio() external view returns (uint) {
return getIssuanceRatio();
}
function externalTokenLimit() external view returns (uint) {
return getExternalTokenQuota();
}
function _availableCurrencyKeysWithOptionalPERI(bool withPERI) internal view returns (bytes32[] memory) {
bytes32[] memory currencyKeys = new bytes32[](availablePynths.length + (withPERI ? 1 : 0));
for (uint i = 0; i < availablePynths.length; i++) {
currencyKeys[i] = pynthsByAddress[address(availablePynths[i])];
}
if (withPERI) {
currencyKeys[availablePynths.length] = PERI;
}
return currencyKeys;
}
function _availableCurrencyKeysWithOptionalPERI(bool withPERI) internal view returns (bytes32[] memory) {
bytes32[] memory currencyKeys = new bytes32[](availablePynths.length + (withPERI ? 1 : 0));
for (uint i = 0; i < availablePynths.length; i++) {
currencyKeys[i] = pynthsByAddress[address(availablePynths[i])];
}
if (withPERI) {
currencyKeys[availablePynths.length] = PERI;
}
return currencyKeys;
}
function _availableCurrencyKeysWithOptionalPERI(bool withPERI) internal view returns (bytes32[] memory) {
bytes32[] memory currencyKeys = new bytes32[](availablePynths.length + (withPERI ? 1 : 0));
for (uint i = 0; i < availablePynths.length; i++) {
currencyKeys[i] = pynthsByAddress[address(availablePynths[i])];
}
if (withPERI) {
currencyKeys[availablePynths.length] = PERI;
}
return currencyKeys;
}
function _totalIssuedPynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
{
(uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo();
anyRateIsInvalid = cacheIsInvalid || cacheIsStale;
IExchangeRates exRates = exchangeRates();
if (!excludeCollateral) {
(uint nonPeriDebt, bool invalid) = collateralManager().totalLong();
debt = debt.add(nonPeriDebt);
anyRateIsInvalid = anyRateIsInvalid || invalid;
debt = debt.add(etherCollateralpUSD().totalIssuedPynths());
(uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(pETH);
uint ethIssuedDebt = etherCollateral().totalIssuedPynths().multiplyDecimalRound(ethRate);
debt = debt.add(ethIssuedDebt);
anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid;
}
if (currencyKey == pUSD) {
return (debt, anyRateIsInvalid);
}
(uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey);
return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid);
}
function _totalIssuedPynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
{
(uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo();
anyRateIsInvalid = cacheIsInvalid || cacheIsStale;
IExchangeRates exRates = exchangeRates();
if (!excludeCollateral) {
(uint nonPeriDebt, bool invalid) = collateralManager().totalLong();
debt = debt.add(nonPeriDebt);
anyRateIsInvalid = anyRateIsInvalid || invalid;
debt = debt.add(etherCollateralpUSD().totalIssuedPynths());
(uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(pETH);
uint ethIssuedDebt = etherCollateral().totalIssuedPynths().multiplyDecimalRound(ethRate);
debt = debt.add(ethIssuedDebt);
anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid;
}
if (currencyKey == pUSD) {
return (debt, anyRateIsInvalid);
}
(uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey);
return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid);
}
function _totalIssuedPynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
{
(uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo();
anyRateIsInvalid = cacheIsInvalid || cacheIsStale;
IExchangeRates exRates = exchangeRates();
if (!excludeCollateral) {
(uint nonPeriDebt, bool invalid) = collateralManager().totalLong();
debt = debt.add(nonPeriDebt);
anyRateIsInvalid = anyRateIsInvalid || invalid;
debt = debt.add(etherCollateralpUSD().totalIssuedPynths());
(uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(pETH);
uint ethIssuedDebt = etherCollateral().totalIssuedPynths().multiplyDecimalRound(ethRate);
debt = debt.add(ethIssuedDebt);
anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid;
}
if (currencyKey == pUSD) {
return (debt, anyRateIsInvalid);
}
(uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey);
return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid);
}
function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey)
internal
view
returns (
uint debtBalance,
uint totalSystemValue,
bool anyRateIsInvalid
)
{
IPeriFinanceState state = periFinanceState();
(uint initialDebtOwnership, uint debtEntryIndex) = state.issuanceData(_issuer);
(totalSystemValue, anyRateIsInvalid) = _totalIssuedPynths(currencyKey, true);
if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsInvalid);
uint _debtLedgerLength = state.debtLedgerLength();
uint systemDebt = state.debtLedger(debtEntryIndex);
uint currentDebtOwnership;
if (_debtLedgerLength == 0 || systemDebt == 0) {
currentDebtOwnership = 0;
currentDebtOwnership = state
.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(systemDebt)
.multiplyDecimalRoundPrecise(initialDebtOwnership);
}
totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise(currentDebtOwnership);
}
function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey)
internal
view
returns (
uint debtBalance,
uint totalSystemValue,
bool anyRateIsInvalid
)
{
IPeriFinanceState state = periFinanceState();
(uint initialDebtOwnership, uint debtEntryIndex) = state.issuanceData(_issuer);
(totalSystemValue, anyRateIsInvalid) = _totalIssuedPynths(currencyKey, true);
if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsInvalid);
uint _debtLedgerLength = state.debtLedgerLength();
uint systemDebt = state.debtLedger(debtEntryIndex);
uint currentDebtOwnership;
if (_debtLedgerLength == 0 || systemDebt == 0) {
currentDebtOwnership = 0;
currentDebtOwnership = state
.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(systemDebt)
.multiplyDecimalRoundPrecise(initialDebtOwnership);
}
totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise(currentDebtOwnership);
}
} else {
uint highPrecisionBalance =
debtBalance = highPrecisionBalance.preciseDecimalToDecimal();
function _canBurnPynths(address account) internal view returns (bool) {
return now >= _lastIssueEvent(account).add(getMinimumStakeTime());
}
function _lastIssueEvent(address account) internal view returns (uint) {
return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)));
}
function _remainingIssuablePynths(address _issuer)
internal
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt,
bool anyRateIsInvalid
)
{
(alreadyIssued, totalSystemDebt, anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, pUSD);
(uint issuable, bool isInvalid) = _maxIssuablePynths(_issuer);
maxIssuable = issuable;
anyRateIsInvalid = anyRateIsInvalid || isInvalid;
if (alreadyIssued >= maxIssuable) {
maxIssuable = 0;
maxIssuable = maxIssuable.sub(alreadyIssued);
}
}
function _remainingIssuablePynths(address _issuer)
internal
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt,
bool anyRateIsInvalid
)
{
(alreadyIssued, totalSystemDebt, anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, pUSD);
(uint issuable, bool isInvalid) = _maxIssuablePynths(_issuer);
maxIssuable = issuable;
anyRateIsInvalid = anyRateIsInvalid || isInvalid;
if (alreadyIssued >= maxIssuable) {
maxIssuable = 0;
maxIssuable = maxIssuable.sub(alreadyIssued);
}
}
} else {
function _periToUSD(uint amount, uint periRate) internal pure returns (uint) {
return amount.multiplyDecimalRound(periRate);
}
function _usdToPeri(uint amount, uint periRate) internal pure returns (uint) {
return amount.divideDecimalRound(periRate);
}
function _maxIssuablePynths(address _issuer) internal view returns (uint, bool) {
(uint periRate, bool periRateIsInvalid) = exchangeRates().rateAndInvalid(PERI);
uint periCollateral = _periToUSD(_collateral(_issuer), periRate);
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(_issuer, pUSD);
uint destinationValue = periCollateral.add(externalTokenStaked);
return (destinationValue.multiplyDecimal(getIssuanceRatio()), periRateIsInvalid);
}
function _collateralisationRatio(address _issuer) internal view returns (uint, bool) {
uint totalOwnedPeriFinance = _collateral(_issuer);
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(_issuer, PERI);
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, PERI);
if (totalOwnedPeriFinance == 0 && externalTokenStaked == 0) return (0, anyRateIsInvalid);
uint totalOwned = totalOwnedPeriFinance.add(externalTokenStaked);
return (debtBalance.divideDecimal(totalOwned), anyRateIsInvalid);
}
function _collateral(address account) internal view returns (uint) {
uint balance = IERC20(address(periFinance())).balanceOf(account);
if (address(periFinanceEscrow()) != address(0)) {
balance = balance.add(periFinanceEscrow().balanceOf(account));
}
if (address(rewardEscrowV2()) != address(0)) {
balance = balance.add(rewardEscrowV2().balanceOf(account));
}
return balance;
}
function _collateral(address account) internal view returns (uint) {
uint balance = IERC20(address(periFinance())).balanceOf(account);
if (address(periFinanceEscrow()) != address(0)) {
balance = balance.add(periFinanceEscrow().balanceOf(account));
}
if (address(rewardEscrowV2()) != address(0)) {
balance = balance.add(rewardEscrowV2().balanceOf(account));
}
return balance;
}
function _collateral(address account) internal view returns (uint) {
uint balance = IERC20(address(periFinance())).balanceOf(account);
if (address(periFinanceEscrow()) != address(0)) {
balance = balance.add(periFinanceEscrow().balanceOf(account));
}
if (address(rewardEscrowV2()) != address(0)) {
balance = balance.add(rewardEscrowV2().balanceOf(account));
}
return balance;
}
function _externalTokenQuota(
address _account,
uint _debtBalance,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) internal view returns (uint) {
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_account, pUSD);
if (_debtBalance == 0 || combinedStakedAmount == 0) {
return 0;
}
if (_isIssue) {
_debtBalance = _debtBalance.add(_additionalpUSD);
combinedStakedAmount = combinedStakedAmount.add(_additionalExToken);
_debtBalance = _debtBalance.sub(_additionalpUSD);
combinedStakedAmount = combinedStakedAmount.sub(_additionalExToken);
}
return combinedStakedAmount.divideDecimalRound(_debtBalance.divideDecimalRound(getIssuanceRatio()));
}
function _externalTokenQuota(
address _account,
uint _debtBalance,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) internal view returns (uint) {
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_account, pUSD);
if (_debtBalance == 0 || combinedStakedAmount == 0) {
return 0;
}
if (_isIssue) {
_debtBalance = _debtBalance.add(_additionalpUSD);
combinedStakedAmount = combinedStakedAmount.add(_additionalExToken);
_debtBalance = _debtBalance.sub(_additionalpUSD);
combinedStakedAmount = combinedStakedAmount.sub(_additionalExToken);
}
return combinedStakedAmount.divideDecimalRound(_debtBalance.divideDecimalRound(getIssuanceRatio()));
}
function _externalTokenQuota(
address _account,
uint _debtBalance,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) internal view returns (uint) {
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_account, pUSD);
if (_debtBalance == 0 || combinedStakedAmount == 0) {
return 0;
}
if (_isIssue) {
_debtBalance = _debtBalance.add(_additionalpUSD);
combinedStakedAmount = combinedStakedAmount.add(_additionalExToken);
_debtBalance = _debtBalance.sub(_additionalpUSD);
combinedStakedAmount = combinedStakedAmount.sub(_additionalExToken);
}
return combinedStakedAmount.divideDecimalRound(_debtBalance.divideDecimalRound(getIssuanceRatio()));
}
} else {
function _amountsToFitClaimable(
uint _currentDebt,
uint _stakedExTokenAmount,
uint _periCollateral
) internal view returns (uint burnAmount, uint exTokenAmountToUnstake) {
uint targetRatio = getIssuanceRatio();
uint exTokenQuota = getExternalTokenQuota();
uint initialCRatio = _currentDebt.divideDecimal(_stakedExTokenAmount.add(_periCollateral));
if (initialCRatio > targetRatio) {
uint maxAllowedExTokenStakeAmountByPeriCollateral =
_periCollateral.multiplyDecimal(exTokenQuota.divideDecimal(SafeDecimalMath.unit().sub(exTokenQuota)));
exTokenAmountToUnstake = _stakedExTokenAmount > maxAllowedExTokenStakeAmountByPeriCollateral
? _stakedExTokenAmount.sub(maxAllowedExTokenStakeAmountByPeriCollateral)
: 0;
burnAmount = _currentDebt.sub(
_periCollateral.add(_stakedExTokenAmount).sub(exTokenAmountToUnstake).multiplyDecimal(targetRatio)
);
uint currentExTokenQuota = _stakedExTokenAmount.multiplyDecimal(targetRatio).divideDecimal(_currentDebt);
require(currentExTokenQuota > exTokenQuota, "Account is already claimable");
burnAmount = (_stakedExTokenAmount.multiplyDecimal(targetRatio).sub(_currentDebt.multiplyDecimal(exTokenQuota)))
.divideDecimal(SafeDecimalMath.unit().sub(exTokenQuota));
exTokenAmountToUnstake = burnAmount.divideDecimal(targetRatio);
}
}
function _amountsToFitClaimable(
uint _currentDebt,
uint _stakedExTokenAmount,
uint _periCollateral
) internal view returns (uint burnAmount, uint exTokenAmountToUnstake) {
uint targetRatio = getIssuanceRatio();
uint exTokenQuota = getExternalTokenQuota();
uint initialCRatio = _currentDebt.divideDecimal(_stakedExTokenAmount.add(_periCollateral));
if (initialCRatio > targetRatio) {
uint maxAllowedExTokenStakeAmountByPeriCollateral =
_periCollateral.multiplyDecimal(exTokenQuota.divideDecimal(SafeDecimalMath.unit().sub(exTokenQuota)));
exTokenAmountToUnstake = _stakedExTokenAmount > maxAllowedExTokenStakeAmountByPeriCollateral
? _stakedExTokenAmount.sub(maxAllowedExTokenStakeAmountByPeriCollateral)
: 0;
burnAmount = _currentDebt.sub(
_periCollateral.add(_stakedExTokenAmount).sub(exTokenAmountToUnstake).multiplyDecimal(targetRatio)
);
uint currentExTokenQuota = _stakedExTokenAmount.multiplyDecimal(targetRatio).divideDecimal(_currentDebt);
require(currentExTokenQuota > exTokenQuota, "Account is already claimable");
burnAmount = (_stakedExTokenAmount.multiplyDecimal(targetRatio).sub(_currentDebt.multiplyDecimal(exTokenQuota)))
.divideDecimal(SafeDecimalMath.unit().sub(exTokenQuota));
exTokenAmountToUnstake = burnAmount.divideDecimal(targetRatio);
}
}
} else {
function _maxExternalTokenStakeAmount(
address _from,
uint _debtBalance,
uint _stakedAmount,
bytes32 _currencyKey
) internal view returns (uint issueAmount, uint stakeAmount) {
uint targetRatio = getIssuanceRatio();
uint quotaLimit = getExternalTokenQuota();
uint maxAllowedStakingAmount = _debtBalance.multiplyDecimal(quotaLimit).divideDecimal(targetRatio);
if (_stakedAmount >= maxAllowedStakingAmount) {
return (0, 0);
}
stakeAmount = ((maxAllowedStakingAmount).sub(_stakedAmount)).divideDecimal(SafeDecimalMath.unit().sub(quotaLimit));
uint balance = IERC20(exTokenStakeManager().getTokenAddress(_currencyKey)).balanceOf(_from);
stakeAmount = balance < stakeAmount ? balance : stakeAmount;
issueAmount = stakeAmount.multiplyDecimal(targetRatio);
}
function _maxExternalTokenStakeAmount(
address _from,
uint _debtBalance,
uint _stakedAmount,
bytes32 _currencyKey
) internal view returns (uint issueAmount, uint stakeAmount) {
uint targetRatio = getIssuanceRatio();
uint quotaLimit = getExternalTokenQuota();
uint maxAllowedStakingAmount = _debtBalance.multiplyDecimal(quotaLimit).divideDecimal(targetRatio);
if (_stakedAmount >= maxAllowedStakingAmount) {
return (0, 0);
}
stakeAmount = ((maxAllowedStakingAmount).sub(_stakedAmount)).divideDecimal(SafeDecimalMath.unit().sub(quotaLimit));
uint balance = IERC20(exTokenStakeManager().getTokenAddress(_currencyKey)).balanceOf(_from);
stakeAmount = balance < stakeAmount ? balance : stakeAmount;
issueAmount = stakeAmount.multiplyDecimal(targetRatio);
}
function minimumStakeTime() external view returns (uint) {
return getMinimumStakeTime();
}
function canBurnPynths(address account) external view returns (bool) {
return _canBurnPynths(account);
}
function availableCurrencyKeys() external view returns (bytes32[] memory) {
return _availableCurrencyKeysWithOptionalPERI(false);
}
function availablePynthCount() external view returns (uint) {
return availablePynths.length;
}
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) {
(, anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(_availableCurrencyKeysWithOptionalPERI(true));
}
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint totalIssued) {
(totalIssued, ) = _totalIssuedPynths(currencyKey, excludeEtherCollateral);
}
function lastIssueEvent(address account) external view returns (uint) {
return _lastIssueEvent(account);
}
function collateralisationRatio(address _issuer) external view returns (uint cratio) {
(cratio, ) = _collateralisationRatio(_issuer);
}
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid)
{
return _collateralisationRatio(_issuer);
}
function collateral(address account) external view returns (uint) {
return _collateral(account);
}
function debtBalanceOf(address _issuer, bytes32 currencyKey) external view returns (uint debtBalance) {
IPeriFinanceState state = periFinanceState();
(uint initialDebtOwnership, ) = state.issuanceData(_issuer);
if (initialDebtOwnership == 0) return 0;
(debtBalance, , ) = _debtBalanceOfAndTotalDebt(_issuer, currencyKey);
}
function remainingIssuablePynths(address _issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
)
{
(maxIssuable, alreadyIssued, totalSystemDebt, ) = _remainingIssuablePynths(_issuer);
}
function maxIssuablePynths(address _issuer) external view returns (uint) {
(uint maxIssuable, ) = _maxIssuablePynths(_issuer);
return maxIssuable;
}
function externalTokenQuota(
address _account,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) external view returns (uint) {
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_account, pUSD);
_requireRatesNotInvalid(anyRateIsInvalid);
uint estimatedQuota = _externalTokenQuota(_account, debtBalance, _additionalpUSD, _additionalExToken, _isIssue);
return estimatedQuota;
}
function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey)
external
view
returns (uint issueAmountToQuota, uint stakeAmountToQuota)
{
(uint debtBalance, , ) = _debtBalanceOfAndTotalDebt(_account, pUSD);
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_account, pUSD);
(issueAmountToQuota, stakeAmountToQuota) = _maxExternalTokenStakeAmount(
_account,
debtBalance,
combinedStakedAmount,
_currencyKey
);
}
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid)
{
(uint debtBalance, , bool rateIsInvalid) = _debtBalanceOfAndTotalDebt(account, PERI);
uint debtAppliedIssuanceRatio = debtBalance.divideDecimalRound(getIssuanceRatio());
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(account, PERI);
uint lockedPeriFinanceValue =
debtAppliedIssuanceRatio > externalTokenStaked ? debtAppliedIssuanceRatio.sub(externalTokenStaked) : 0;
if (lockedPeriFinanceValue >= balance) {
transferable = 0;
transferable = balance.sub(lockedPeriFinanceValue);
}
anyRateIsInvalid = rateIsInvalid;
}
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid)
{
(uint debtBalance, , bool rateIsInvalid) = _debtBalanceOfAndTotalDebt(account, PERI);
uint debtAppliedIssuanceRatio = debtBalance.divideDecimalRound(getIssuanceRatio());
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(account, PERI);
uint lockedPeriFinanceValue =
debtAppliedIssuanceRatio > externalTokenStaked ? debtAppliedIssuanceRatio.sub(externalTokenStaked) : 0;
if (lockedPeriFinanceValue >= balance) {
transferable = 0;
transferable = balance.sub(lockedPeriFinanceValue);
}
anyRateIsInvalid = rateIsInvalid;
}
} else {
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory) {
uint numKeys = currencyKeys.length;
IPynth[] memory addresses = new IPynth[](numKeys);
for (uint i = 0; i < numKeys; i++) {
addresses[i] = pynths[currencyKeys[i]];
}
return addresses;
}
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory) {
uint numKeys = currencyKeys.length;
IPynth[] memory addresses = new IPynth[](numKeys);
for (uint i = 0; i < numKeys; i++) {
addresses[i] = pynths[currencyKeys[i]];
}
return addresses;
}
function _addPynth(IPynth pynth) internal {
bytes32 currencyKey = pynth.currencyKey();
require(pynths[currencyKey] == IPynth(0), "Pynth exists");
require(pynthsByAddress[address(pynth)] == bytes32(0), "Pynth address already exists");
availablePynths.push(pynth);
pynths[currencyKey] = pynth;
pynthsByAddress[address(pynth)] = currencyKey;
emit PynthAdded(currencyKey, address(pynth));
}
function addPynth(IPynth pynth) external onlyOwner {
_addPynth(pynth);
debtCache().updateDebtCacheValidity(true);
}
function addPynths(IPynth[] calldata pynthsToAdd) external onlyOwner {
uint numPynths = pynthsToAdd.length;
for (uint i = 0; i < numPynths; i++) {
_addPynth(pynthsToAdd[i]);
}
}
function addPynths(IPynth[] calldata pynthsToAdd) external onlyOwner {
uint numPynths = pynthsToAdd.length;
for (uint i = 0; i < numPynths; i++) {
_addPynth(pynthsToAdd[i]);
}
}
debtCache().updateDebtCacheValidity(true);
function _removePynth(bytes32 currencyKey) internal {
address pynthToRemove = address(pynths[currencyKey]);
require(pynthToRemove != address(0), "Pynth does not exist");
require(IERC20(pynthToRemove).totalSupply() == 0, "Pynth supply exists");
require(currencyKey != pUSD, "Cannot remove pynth");
for (uint i = 0; i < availablePynths.length; i++) {
if (address(availablePynths[i]) == pynthToRemove) {
delete availablePynths[i];
availablePynths[i] = availablePynths[availablePynths.length - 1];
availablePynths.length--;
break;
}
}
delete pynths[currencyKey];
emit PynthRemoved(currencyKey, pynthToRemove);
}
function _removePynth(bytes32 currencyKey) internal {
address pynthToRemove = address(pynths[currencyKey]);
require(pynthToRemove != address(0), "Pynth does not exist");
require(IERC20(pynthToRemove).totalSupply() == 0, "Pynth supply exists");
require(currencyKey != pUSD, "Cannot remove pynth");
for (uint i = 0; i < availablePynths.length; i++) {
if (address(availablePynths[i]) == pynthToRemove) {
delete availablePynths[i];
availablePynths[i] = availablePynths[availablePynths.length - 1];
availablePynths.length--;
break;
}
}
delete pynths[currencyKey];
emit PynthRemoved(currencyKey, pynthToRemove);
}
function _removePynth(bytes32 currencyKey) internal {
address pynthToRemove = address(pynths[currencyKey]);
require(pynthToRemove != address(0), "Pynth does not exist");
require(IERC20(pynthToRemove).totalSupply() == 0, "Pynth supply exists");
require(currencyKey != pUSD, "Cannot remove pynth");
for (uint i = 0; i < availablePynths.length; i++) {
if (address(availablePynths[i]) == pynthToRemove) {
delete availablePynths[i];
availablePynths[i] = availablePynths[availablePynths.length - 1];
availablePynths.length--;
break;
}
}
delete pynths[currencyKey];
emit PynthRemoved(currencyKey, pynthToRemove);
}
delete pynthsByAddress[pynthToRemove];
function removePynth(bytes32 currencyKey) external onlyOwner {
IIssuerInternalDebtCache cache = debtCache();
cache.updateCachedPynthDebtWithRate(currencyKey, 0);
cache.updateDebtCacheValidity(true);
_removePynth(currencyKey);
}
function removePynths(bytes32[] calldata currencyKeys) external onlyOwner {
uint numKeys = currencyKeys.length;
IIssuerInternalDebtCache cache = debtCache();
uint[] memory zeroRates = new uint[](numKeys);
cache.updateCachedPynthDebtsWithRates(currencyKeys, zeroRates);
cache.updateDebtCacheValidity(true);
for (uint i = 0; i < numKeys; i++) {
_removePynth(currencyKeys[i]);
}
}
function removePynths(bytes32[] calldata currencyKeys) external onlyOwner {
uint numKeys = currencyKeys.length;
IIssuerInternalDebtCache cache = debtCache();
uint[] memory zeroRates = new uint[](numKeys);
cache.updateCachedPynthDebtsWithRates(currencyKeys, zeroRates);
cache.updateDebtCacheValidity(true);
for (uint i = 0; i < numKeys; i++) {
_removePynth(currencyKeys[i]);
}
}
function issuePynths(
address _issuer,
bytes32 _currencyKey,
uint _issueAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
if (_currencyKey != PERI) {
uint amountToStake = _issueAmount.divideDecimalRound(getIssuanceRatio());
(uint initialDebtOwnership, ) = periFinanceState().issuanceData(_issuer);
require(initialDebtOwnership > 0, "User does not have any debt yet");
exTokenStakeManager().stake(_issuer, amountToStake, _currencyKey, pUSD);
}
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
uint afterDebtBalance = _issuePynths(_issuer, _issueAmount, maxIssuable, existingDebt, totalSystemDebt, false);
}
function issuePynths(
address _issuer,
bytes32 _currencyKey,
uint _issueAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
if (_currencyKey != PERI) {
uint amountToStake = _issueAmount.divideDecimalRound(getIssuanceRatio());
(uint initialDebtOwnership, ) = periFinanceState().issuanceData(_issuer);
require(initialDebtOwnership > 0, "User does not have any debt yet");
exTokenStakeManager().stake(_issuer, amountToStake, _currencyKey, pUSD);
}
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
uint afterDebtBalance = _issuePynths(_issuer, _issueAmount, maxIssuable, existingDebt, totalSystemDebt, false);
}
_requireNotExceedsQuotaLimit(_issuer, afterDebtBalance, 0, 0, true);
function issueMaxPynths(address _issuer) external onlyPeriFinance {
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
_issuePynths(_issuer, 0, maxIssuable, existingDebt, totalSystemDebt, true);
}
function issuePynthsToMaxQuota(address _issuer, bytes32 _currencyKey) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
require(_currencyKey != PERI, "Only external token allowed to stake");
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
require(existingDebt > 0, "User does not have any debt yet");
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_issuer, pUSD);
(uint issueAmountToQuota, uint stakeAmountToQuota) =
_maxExternalTokenStakeAmount(_issuer, existingDebt, combinedStakedAmount, _currencyKey);
require(issueAmountToQuota > 0 && stakeAmountToQuota > 0, "No available external token staking amount");
exTokenStakeManager().stake(_issuer, stakeAmountToQuota, _currencyKey, pUSD);
maxIssuable = maxIssuable.add(issueAmountToQuota);
uint afterDebtBalance = _issuePynths(_issuer, issueAmountToQuota, maxIssuable, existingDebt, totalSystemDebt, false);
_requireNotExceedsQuotaLimit(_issuer, afterDebtBalance, 0, 0, true);
}
function burnPynths(
address _from,
bytes32 _currencyKey,
uint _burnAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
uint remainingDebt = _voluntaryBurnPynths(_from, _burnAmount, false, false);
if (_currencyKey == PERI) {
_requireNotExceedsQuotaLimit(_from, remainingDebt, 0, 0, false);
}
if (_currencyKey != PERI) {
exTokenStakeManager().unstake(_from, _burnAmount.divideDecimalRound(getIssuanceRatio()), _currencyKey, pUSD);
}
}
function burnPynths(
address _from,
bytes32 _currencyKey,
uint _burnAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
uint remainingDebt = _voluntaryBurnPynths(_from, _burnAmount, false, false);
if (_currencyKey == PERI) {
_requireNotExceedsQuotaLimit(_from, remainingDebt, 0, 0, false);
}
if (_currencyKey != PERI) {
exTokenStakeManager().unstake(_from, _burnAmount.divideDecimalRound(getIssuanceRatio()), _currencyKey, pUSD);
}
}
function burnPynths(
address _from,
bytes32 _currencyKey,
uint _burnAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
uint remainingDebt = _voluntaryBurnPynths(_from, _burnAmount, false, false);
if (_currencyKey == PERI) {
_requireNotExceedsQuotaLimit(_from, remainingDebt, 0, 0, false);
}
if (_currencyKey != PERI) {
exTokenStakeManager().unstake(_from, _burnAmount.divideDecimalRound(getIssuanceRatio()), _currencyKey, pUSD);
}
}
function fitToClaimable(address _from) external onlyPeriFinance {
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_from, pUSD);
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_from, pUSD);
(uint periRate, bool isPeriInvalid) = exchangeRates().rateAndInvalid(PERI);
uint periCollateralToUSD = _periToUSD(_collateral(_from), periRate);
_requireRatesNotInvalid(anyRateIsInvalid || isPeriInvalid);
(uint burnAmount, uint amountToUnstake) =
_amountsToFitClaimable(debtBalance, combinedStakedAmount, periCollateralToUSD);
_voluntaryBurnPynths(_from, burnAmount, true, false);
exTokenStakeManager().unstakeMultipleTokens(_from, amountToUnstake, pUSD);
}
function exit(address _from) external onlyPeriFinance {
_voluntaryBurnPynths(_from, 0, true, true);
bytes32[] memory tokenList = exTokenStakeManager().getTokenList();
for (uint i = 0; i < tokenList.length; i++) {
uint stakedAmount = exTokenStakeManager().stakedAmountOf(_from, tokenList[i], tokenList[i]);
if (stakedAmount == 0) {
continue;
}
exTokenStakeManager().unstake(_from, stakedAmount, tokenList[i], tokenList[i]);
}
}
function exit(address _from) external onlyPeriFinance {
_voluntaryBurnPynths(_from, 0, true, true);
bytes32[] memory tokenList = exTokenStakeManager().getTokenList();
for (uint i = 0; i < tokenList.length; i++) {
uint stakedAmount = exTokenStakeManager().stakedAmountOf(_from, tokenList[i], tokenList[i]);
if (stakedAmount == 0) {
continue;
}
exTokenStakeManager().unstake(_from, stakedAmount, tokenList[i], tokenList[i]);
}
}
function exit(address _from) external onlyPeriFinance {
_voluntaryBurnPynths(_from, 0, true, true);
bytes32[] memory tokenList = exTokenStakeManager().getTokenList();
for (uint i = 0; i < tokenList.length; i++) {
uint stakedAmount = exTokenStakeManager().stakedAmountOf(_from, tokenList[i], tokenList[i]);
if (stakedAmount == 0) {
continue;
}
exTokenStakeManager().unstake(_from, stakedAmount, tokenList[i], tokenList[i]);
}
}
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external onlyPeriFinance returns (uint totalRedeemed, uint amountToLiquidate) {
require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, pUSD), "pUSD needs to be settled");
require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation");
require(IERC20(address(pynths[pUSD])).balanceOf(liquidator) >= pusdAmount, "Not enough pUSD");
uint liquidationPenalty = liquidations().liquidationPenalty();
(uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, pUSD);
(uint periRate, bool periRateInvalid) = exchangeRates().rateAndInvalid(PERI);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
uint collateralForAccount = _collateral(account);
uint amountToFixRatio =
liquidations().calculateAmountToFixCollateral(debtBalance, _periToUSD(collateralForAccount, periRate));
amountToLiquidate = amountToFixRatio < pusdAmount ? amountToFixRatio : pusdAmount;
uint periRedeemed = _usdToPeri(amountToLiquidate, periRate);
totalRedeemed = periRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty));
if (totalRedeemed > collateralForAccount) {
totalRedeemed = collateralForAccount;
amountToLiquidate = _periToUSD(
collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)),
periRate
);
}
if (amountToLiquidate == amountToFixRatio) {
liquidations().removeAccountInLiquidation(account);
}
}
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external onlyPeriFinance returns (uint totalRedeemed, uint amountToLiquidate) {
require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, pUSD), "pUSD needs to be settled");
require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation");
require(IERC20(address(pynths[pUSD])).balanceOf(liquidator) >= pusdAmount, "Not enough pUSD");
uint liquidationPenalty = liquidations().liquidationPenalty();
(uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, pUSD);
(uint periRate, bool periRateInvalid) = exchangeRates().rateAndInvalid(PERI);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
uint collateralForAccount = _collateral(account);
uint amountToFixRatio =
liquidations().calculateAmountToFixCollateral(debtBalance, _periToUSD(collateralForAccount, periRate));
amountToLiquidate = amountToFixRatio < pusdAmount ? amountToFixRatio : pusdAmount;
uint periRedeemed = _usdToPeri(amountToLiquidate, periRate);
totalRedeemed = periRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty));
if (totalRedeemed > collateralForAccount) {
totalRedeemed = collateralForAccount;
amountToLiquidate = _periToUSD(
collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)),
periRate
);
}
if (amountToLiquidate == amountToFixRatio) {
liquidations().removeAccountInLiquidation(account);
}
}
_burnPynths(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued);
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external onlyPeriFinance returns (uint totalRedeemed, uint amountToLiquidate) {
require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, pUSD), "pUSD needs to be settled");
require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation");
require(IERC20(address(pynths[pUSD])).balanceOf(liquidator) >= pusdAmount, "Not enough pUSD");
uint liquidationPenalty = liquidations().liquidationPenalty();
(uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, pUSD);
(uint periRate, bool periRateInvalid) = exchangeRates().rateAndInvalid(PERI);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
uint collateralForAccount = _collateral(account);
uint amountToFixRatio =
liquidations().calculateAmountToFixCollateral(debtBalance, _periToUSD(collateralForAccount, periRate));
amountToLiquidate = amountToFixRatio < pusdAmount ? amountToFixRatio : pusdAmount;
uint periRedeemed = _usdToPeri(amountToLiquidate, periRate);
totalRedeemed = periRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty));
if (totalRedeemed > collateralForAccount) {
totalRedeemed = collateralForAccount;
amountToLiquidate = _periToUSD(
collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)),
periRate
);
}
if (amountToLiquidate == amountToFixRatio) {
liquidations().removeAccountInLiquidation(account);
}
}
function _requireRatesNotInvalid(bool anyRateIsInvalid) internal pure {
require(!anyRateIsInvalid, "A pynth or PERI rate is invalid");
}
function _requireCanIssueOnBehalf(address issueForAddress, address from) internal view {
require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf");
}
function _requireCanBurnOnBehalf(address burnForAddress, address from) internal view {
require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf");
}
function _requireCurrencyKeyIsNotpUSD(bytes32 _currencyKey) internal pure {
require(_currencyKey != pUSD, "pUSD is not staking coin");
}
function _requireNotExceedsQuotaLimit(
address _account,
uint _debtBalance,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) internal view {
uint estimatedExternalTokenQuota =
_externalTokenQuota(_account, _debtBalance, _additionalpUSD, _additionalExToken, _isIssue);
bytes32[] memory tokenList = exTokenStakeManager().getTokenList();
uint minDecimals = 18;
for (uint i = 0; i < tokenList.length; i++) {
uint decimals = exTokenStakeManager().getTokenDecimals(tokenList[i]);
minDecimals = decimals < minDecimals ? decimals : minDecimals;
}
require(
"External token staking amount exceeds quota limit"
);
}
function _requireNotExceedsQuotaLimit(
address _account,
uint _debtBalance,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) internal view {
uint estimatedExternalTokenQuota =
_externalTokenQuota(_account, _debtBalance, _additionalpUSD, _additionalExToken, _isIssue);
bytes32[] memory tokenList = exTokenStakeManager().getTokenList();
uint minDecimals = 18;
for (uint i = 0; i < tokenList.length; i++) {
uint decimals = exTokenStakeManager().getTokenDecimals(tokenList[i]);
minDecimals = decimals < minDecimals ? decimals : minDecimals;
}
require(
"External token staking amount exceeds quota limit"
);
}
estimatedExternalTokenQuota.roundDownDecimal(uint(18).sub(minDecimals)) <= getExternalTokenQuota(),
function _issuePynths(
address from,
uint amount,
uint maxIssuable,
uint existingDebt,
uint totalSystemDebt,
bool issueMax
) internal returns (uint afterDebt) {
if (!issueMax) {
require(amount <= maxIssuable, "Amount too large");
amount = maxIssuable;
}
afterDebt = existingDebt.add(amount);
}
function _issuePynths(
address from,
uint amount,
uint maxIssuable,
uint existingDebt,
uint totalSystemDebt,
bool issueMax
) internal returns (uint afterDebt) {
if (!issueMax) {
require(amount <= maxIssuable, "Amount too large");
amount = maxIssuable;
}
afterDebt = existingDebt.add(amount);
}
} else {
_addToDebtRegister(from, amount, existingDebt, totalSystemDebt);
_setLastIssueEvent(from);
pynths[pUSD].issue(from, amount);
debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit());
_appendAccountIssuanceRecord(from);
function _burnPynths(
address debtAccount,
address burnAccount,
uint amountBurnt,
uint existingDebt,
uint totalDebtIssued
) internal returns (uint) {
require(amountBurnt <= existingDebt, "Trying to burn more than debt");
_removeFromDebtRegister(debtAccount, amountBurnt, existingDebt, totalDebtIssued);
pynths[pUSD].burn(burnAccount, amountBurnt);
debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit());
_appendAccountIssuanceRecord(debtAccount);
return amountBurnt;
}
function _voluntaryBurnPynths(
address from,
uint amount,
bool burnToTarget,
bool burnMax
) internal returns (uint remainingDebt) {
if (!burnToTarget) {
require(_canBurnPynths(from), "Minimum stake time not reached");
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD);
(uint maxIssuablePynthsForAccount, bool periRateInvalid) = _maxIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnMax) {
amount = existingDebt;
}
uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue);
remainingDebt = existingDebt.sub(amountBurnt);
if (existingDebt >= amountBurnt && remainingDebt <= maxIssuablePynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _voluntaryBurnPynths(
address from,
uint amount,
bool burnToTarget,
bool burnMax
) internal returns (uint remainingDebt) {
if (!burnToTarget) {
require(_canBurnPynths(from), "Minimum stake time not reached");
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD);
(uint maxIssuablePynthsForAccount, bool periRateInvalid) = _maxIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnMax) {
amount = existingDebt;
}
uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue);
remainingDebt = existingDebt.sub(amountBurnt);
if (existingDebt >= amountBurnt && remainingDebt <= maxIssuablePynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _voluntaryBurnPynths(
address from,
uint amount,
bool burnToTarget,
bool burnMax
) internal returns (uint remainingDebt) {
if (!burnToTarget) {
require(_canBurnPynths(from), "Minimum stake time not reached");
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD);
(uint maxIssuablePynthsForAccount, bool periRateInvalid) = _maxIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnMax) {
amount = existingDebt;
}
uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue);
remainingDebt = existingDebt.sub(amountBurnt);
if (existingDebt >= amountBurnt && remainingDebt <= maxIssuablePynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _voluntaryBurnPynths(
address from,
uint amount,
bool burnToTarget,
bool burnMax
) internal returns (uint remainingDebt) {
if (!burnToTarget) {
require(_canBurnPynths(from), "Minimum stake time not reached");
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD);
(uint maxIssuablePynthsForAccount, bool periRateInvalid) = _maxIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnMax) {
amount = existingDebt;
}
uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue);
remainingDebt = existingDebt.sub(amountBurnt);
if (existingDebt >= amountBurnt && remainingDebt <= maxIssuablePynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _voluntaryBurnPynths(
address from,
uint amount,
bool burnToTarget,
bool burnMax
) internal returns (uint remainingDebt) {
if (!burnToTarget) {
require(_canBurnPynths(from), "Minimum stake time not reached");
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD);
(uint maxIssuablePynthsForAccount, bool periRateInvalid) = _maxIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnMax) {
amount = existingDebt;
}
uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue);
remainingDebt = existingDebt.sub(amountBurnt);
if (existingDebt >= amountBurnt && remainingDebt <= maxIssuablePynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _setLastIssueEvent(address account) internal {
flexibleStorage().setUIntValue(
CONTRACT_NAME,
keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)),
block.timestamp
);
}
function _appendAccountIssuanceRecord(address from) internal {
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = periFinanceState().issuanceData(from);
feePool().appendAccountIssuanceRecord(from, initialDebtOwnership, debtEntryIndex);
}
function _addToDebtRegister(
address from,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
uint newTotalDebtIssued = amount.add(totalDebtIssued);
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
if (existingDebt > 0) {
debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
state.incrementTotalIssuerCount();
}
if (state.debtLedgerLength() > 0 && state.lastDebtLedgerEntry() != 0) {
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
function _addToDebtRegister(
address from,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
uint newTotalDebtIssued = amount.add(totalDebtIssued);
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
if (existingDebt > 0) {
debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
state.incrementTotalIssuerCount();
}
if (state.debtLedgerLength() > 0 && state.lastDebtLedgerEntry() != 0) {
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
} else {
state.setCurrentIssuanceData(from, debtPercentage);
function _addToDebtRegister(
address from,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
uint newTotalDebtIssued = amount.add(totalDebtIssued);
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
if (existingDebt > 0) {
debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
state.incrementTotalIssuerCount();
}
if (state.debtLedgerLength() > 0 && state.lastDebtLedgerEntry() != 0) {
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
} else {
function _removeFromDebtRegister(
address from,
uint debtToRemove,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta = 0;
if (newTotalDebtIssued > 0) {
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
}
if (debtToRemove == existingDebt) {
state.setCurrentIssuanceData(from, 0);
state.decrementTotalIssuerCount();
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
state.setCurrentIssuanceData(from, newDebtPercentage);
}
}
function _removeFromDebtRegister(
address from,
uint debtToRemove,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta = 0;
if (newTotalDebtIssued > 0) {
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
}
if (debtToRemove == existingDebt) {
state.setCurrentIssuanceData(from, 0);
state.decrementTotalIssuerCount();
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
state.setCurrentIssuanceData(from, newDebtPercentage);
}
}
function _removeFromDebtRegister(
address from,
uint debtToRemove,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta = 0;
if (newTotalDebtIssued > 0) {
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
}
if (debtToRemove == existingDebt) {
state.setCurrentIssuanceData(from, 0);
state.decrementTotalIssuerCount();
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
state.setCurrentIssuanceData(from, newDebtPercentage);
}
}
} else {
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
function _onlyPeriFinance() internal view {
require(msg.sender == address(periFinance()), "Issuer: Only the periFinance contract can perform this action");
}
modifier onlyPeriFinance() {
_;
}
event PynthAdded(bytes32 currencyKey, address pynth);
event PynthRemoved(bytes32 currencyKey, address pynth);
}
| 1,743,726 | [
1,
4528,
30,
8532,
18,
457,
77,
18,
926,
1359,
19,
16351,
87,
19,
3168,
19,
16351,
87,
19,
17567,
15633,
453,
878,
451,
87,
1492,
848,
506,
1399,
598,
326,
2619,
478,
21873,
2502,
1257,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
23959,
353,
14223,
11748,
16,
490,
10131,
3163,
2628,
16,
467,
16667,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1450,
14060,
5749,
10477,
364,
2254,
31,
203,
203,
565,
2971,
878,
451,
8526,
1071,
2319,
52,
878,
451,
87,
31,
203,
565,
2874,
12,
3890,
1578,
516,
2971,
878,
451,
13,
1071,
293,
878,
451,
87,
31,
203,
565,
2874,
12,
2867,
516,
1731,
1578,
13,
1071,
293,
878,
451,
87,
858,
1887,
31,
203,
203,
203,
565,
1731,
1578,
2713,
5381,
293,
3378,
40,
273,
315,
84,
3378,
40,
14432,
203,
565,
1731,
1578,
2713,
5381,
293,
1584,
44,
273,
315,
84,
1584,
44,
14432,
203,
565,
1731,
1578,
2713,
5381,
10950,
45,
273,
315,
3194,
45,
14432,
203,
565,
1731,
1578,
2713,
5381,
11836,
5528,
273,
315,
3378,
5528,
14432,
203,
203,
203,
565,
1731,
1578,
1071,
5381,
8020,
2849,
1268,
67,
1985,
273,
315,
16667,
14432,
203,
565,
1731,
1578,
2713,
5381,
15612,
67,
25689,
1821,
67,
10454,
273,
315,
2722,
12956,
1133,
14432,
203,
203,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
3194,
5501,
706,
4722,
273,
315,
2173,
77,
6187,
1359,
14432,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
2294,
1792,
1258,
3101,
273,
315,
424,
343,
11455,
14432,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
2294,
24062,
55,
273,
315,
11688,
20836,
14432,
203,
565,
1731,
1578,
3238,
5381,
8020,
2849,
1268,
67,
3194,
5501,
706,
4722,
7998,
273,
315,
2173,
77,
6187,
1359,
2
] |
./full_match/97/0x19e0392e68E98a476d705202BBE90C2D5b854dA2/sources/project_/contracts/lendingprotocol.sol | Struct to store information about a loan struct Loan { address borrower; uint256 principal; uint256 interestRate; uint256 duration; uint256 startTime; uint256 endTime; } Mapping from loan ID to loan information mapping(uint256 => Loan) public loans; | contract LendingProtocol {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 public loanCount;
event Transfer(address indexed from, address indexed to, uint256 value);
event DepositMade(address indexed addr, uint256 amount);
event Withdraw(address indexed addr, uint256 amount);
mapping(address => uint256) public balances;
mapping(address => uint256) public lend;
address iBnBToken = (0xf9d32C5E10Dd51511894b360e6bD39D7573450F9);
}
constructor() public {}
function makeBNBDeposit(uint256 loanID, uint256 _amount) public payable {
require(loanID > 0 && loanID <= loanCount, "Invalid loan ID");
require(_amount > 0, "Amount must be greater than 0");
require(
_amount <= msg.value,
"Insufficient BNB sent with the transaction"
);
balances[msg.sender] = balances[msg.sender].add(_amount);
lend[msg.sender] = calculateBNB(msg.value);
emit DepositMade(msg.sender, msg.value);
}
IVault(iBnBToken).deposit{value : msg.value}(msg.value);
function calculateBNB(uint256 _amount)public view returns (uint256){
IVault vault = IVault(iBnBToken);
uint256 ibTokenPrice = _amount*(vault.totalToken()*(1e18)).div(vault.totalSupply());
return ibTokenPrice;
}
function withdraw() public {
uint256 ibTokenAmount = lend[msg.sender];
IVault(iBnBToken).withdraw(ibTokenAmount);
}
}
| 3,290,435 | [
1,
3823,
358,
1707,
1779,
2973,
279,
28183,
1958,
3176,
304,
288,
377,
1758,
29759,
264,
31,
377,
2254,
5034,
8897,
31,
377,
2254,
5034,
16513,
4727,
31,
377,
2254,
5034,
3734,
31,
377,
2254,
5034,
8657,
31,
377,
2254,
5034,
13859,
31,
289,
9408,
628,
28183,
1599,
358,
28183,
1779,
2874,
12,
11890,
5034,
516,
3176,
304,
13,
1071,
437,
634,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
511,
2846,
5752,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
2254,
5034,
1071,
28183,
1380,
31,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
565,
871,
4019,
538,
305,
49,
2486,
12,
2867,
8808,
3091,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
3091,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
328,
409,
31,
203,
27699,
282,
1758,
277,
38,
82,
38,
1345,
273,
261,
20,
5841,
29,
72,
1578,
39,
25,
41,
2163,
40,
72,
25,
3600,
2499,
6675,
24,
70,
29751,
73,
26,
70,
40,
5520,
40,
5877,
27,
5026,
3361,
42,
29,
1769,
203,
27699,
203,
203,
97,
203,
565,
3885,
1435,
1071,
2618,
203,
565,
445,
1221,
15388,
38,
758,
1724,
12,
11890,
5034,
28183,
734,
16,
2254,
5034,
389,
8949,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
383,
304,
734,
405,
374,
597,
28183,
734,
1648,
28183,
1380,
16,
315,
1941,
28183,
1599,
8863,
203,
3639,
203,
4202,
203,
3639,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
6275,
1297,
506,
6802,
2353,
374,
8863,
203,
3639,
2583,
12,
203,
5411,
389,
8949,
1648,
1234,
18,
1132,
16,
203,
5411,
315,
5048,
11339,
605,
20626,
3271,
598,
326,
2492,
2
] |
pragma solidity ^0.6.2;
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period.
*/
contract CookDistribution {
event AllocationRegistered(address indexed beneficiary, uint256 amount);
event TokensWithdrawal(address userAddress, uint256 amount);
struct Allocation {
uint256 amount;
uint256 released;
bool blackListed;
bool isRegistered;
}
// beneficiary of tokens after they are released
mapping(address => Allocation) private _beneficiaryAllocations;
// oracle price data (dayNumber => price)
mapping(uint256 => uint256) private _oraclePriceFeed;
// all beneficiary address1
address[] private _allBeneficiary;
function addAddressWithAllocation(address beneficiaryAddress, uint256 amount ) public {
require(
_beneficiaryAllocations[beneficiaryAddress].isRegistered == false,
"The address to be added already exisits in the distribution contact, please use a new one"
);
_beneficiaryAllocations[beneficiaryAddress].isRegistered = true;
_beneficiaryAllocations[beneficiaryAddress] = Allocation( amount, 0, false, true
);
emit AllocationRegistered(beneficiaryAddress, amount);
}
function addMultipleAddressWithAllocations(address[] memory beneficiaryAddresses, uint256[] memory amounts) public {
require(beneficiaryAddresses.length > 0 && amounts.length > 0 && beneficiaryAddresses.length == amounts.length,
"The length of user addressed and amounts should be matched and cannot be empty"
);
for (uint256 i = 0; i < beneficiaryAddresses.length; i++) {
require(_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered == false,
"The address to be added already exisits in the distribution contact, please use a new one"
);
}
for (uint256 i = 0; i < beneficiaryAddresses.length; i++) {
_beneficiaryAllocations[beneficiaryAddresses[i]].isRegistered = true;
_beneficiaryAllocations[beneficiaryAddresses[i]] = Allocation(amounts[i], 0, false, true);
emit AllocationRegistered(beneficiaryAddresses[i], amounts[i]);
}
}
} | all beneficiary address1 | address[] private _allBeneficiary;
| 55,049 | [
1,
454,
27641,
74,
14463,
814,
1758,
21,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
8526,
3238,
389,
454,
38,
4009,
74,
14463,
814,
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
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// =============================== veFXS ==============================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Original idea and credit:
// Curve Finance's veCRV
// https://resources.curve.fi/faq/vote-locking-boost
// https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/VotingEscrow.vy
// This is a Solidity version converted from Vyper by the Frax team
// Almost all of the logic / algorithms are the Curve team's
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
//@notice Votes have a weight depending on time, so that users are
// committed to the future of (whatever they are voting for)
//@dev Vote weight decays linearly over time. Lock time cannot be
// more than `MAXTIME` (3 years).
// Voting escrow to have time-weighted votes
// Votes have a weight depending on time, so that users are committed
// to the future of (whatever they are voting for).
// The weight in this implementation is linear, and lock cannot be more than maxtime:
// w ^
// 1 + /
// | /
// | /
// | /
// |/
// 0 +--------+------> time
// maxtime (3 years?)
import "../Utils/Math.sol";
import "../Utils/TransferHelper.sol";
import "../Governance/Comp.sol";
import "../Utils/StringHelpers.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// import "../Frax/Frax.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
// Inheritance
import "../Utils/Owned.sol";
import "../Utils/Pausable.sol";
// # Interface for checking whether address belongs to a whitelisted
// # type of a smart wallet.
// # When new types are added - the whole contract is changed
// # The check() method is modifying to be able to use caching
// # for individual wallet addresses
interface SmartWalletChecker {
function check(address addr) external returns (bool);
}
contract veToken is ReentrancyGuard{
using SafeMath for uint256;
using SafeERC20 for IERC20;
// We cannot really do block numbers per se b/c slope is per time, not per block
// and per block could be fairly bad b/c Ethereum changes blocktimes.
// What we can do is to extrapolate ***At functions
struct Point {
int128 bias;
int128 slope; // dweight / dt
uint256 ts;
uint256 blk; // block
}
struct LockedBalance {
int128 amount;
uint256 end;
}
/* ========== STATE VARIABLES ========== */
address public token; // FXS
uint256 public supply; // veFXS
uint256 public epoch;
mapping (address => LockedBalance) public locked;
Point[100000000000000000000000000000] public point_history; // epoch (total 10 ** 29) -> unsigned point
mapping (address => Point[1000000000]) public user_point_history; // 10 ** 9 epoch
mapping (address => uint256) public user_point_epoch;
mapping (uint256 => int128) public slope_changes; // time -> signed slope change
// Aragon's view methods for
address public controller;
bool public transfersEnabled;
// veFXS token related
string public name;
string public symbol;
string public version;
uint256 public decimals;
// Checker for whitelisted (smart contract) wallets which are allowed to deposit
// The goal is to prevent tokenizing the escrow
address public future_smart_wallet_checker;
address public smart_wallet_checker;
address public admin; // Can and will be a smart contract
address public future_admin;
int128 public constant DEPOSIT_FOR_TYPE = 0;
int128 public constant CREATE_LOCK_TYPE = 1;
int128 public constant INCREASE_LOCK_AMOUNT = 2;
int128 public constant INCREASE_UNLOCK_TIME = 3;
address public constant ZERO_ADDRESS = address(0);
uint256 public constant WEEK = 7 * 86400; // all future times are rounded by week
uint256 public constant MAXTIME = 3 * 365 * 86400; // 3 years
uint256 public constant MULTIPLIER = 10 ** 18;
/* ========== MODIFIERS ========== */
modifier onlyAdmin {
require(msg.sender == admin, "You are not the admin");
_;
}
/* ========== CONSTRUCTOR ========== */
// token_addr: address, _name: String[64], _symbol: String[32], _version: String[32]
/**
* @notice Contract constructor
* @param token_addr `ERC20CRV` token address
* @param _name Token name
* @param _symbol Token symbol
* @param _version Contract version - required for Aragon compatibility
*/
constructor (
address token_addr,
string memory _name,
string memory _symbol,
string memory _version
) {
admin = msg.sender;
token = token_addr;
point_history[0].blk = block.number;
point_history[0].ts = block.timestamp;
controller = msg.sender;
transfersEnabled = true;
// todo: debug
// uint256 _decimals = IERC20Metadata(token_addr).decimals();
uint256 _decimals = 18;
assert(_decimals <= 255);
decimals = _decimals;
name = _name;
symbol = _symbol;
version = _version;
}
/* ========== VIEWS ========== */
// Constant structs not allowed yet, so this will have to do
function EMPTY_POINT_FACTORY() internal view returns (Point memory){
return Point({
bias: 0,
slope: 0,
ts: 0,
blk: 0
});
}
// Constant structs not allowed yet, so this will have to do
function EMPTY_LOCKED_BALANCE_FACTORY() internal view returns (LockedBalance memory){
return LockedBalance({
amount: 0,
end: 0
});
}
/**
* @notice Get the most recently recorded rate of voting power decrease for `addr`
* @param addr Address of the user wallet
* @return Value of the slope
*/
function get_last_user_slope(address addr) external view returns (int128) {
uint256 uepoch = user_point_epoch[addr];
return user_point_history[addr][uepoch].slope;
}
/**
* @notice Get the timestamp for checkpoint `_idx` for `_addr`
* @param _addr User wallet address
* @param _idx User epoch number
* @return Epoch time of the checkpoint
*/
function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256) {
return user_point_history[_addr][_idx].ts;
}
/**
* @notice Get timestamp when `_addr`'s lock finishes
* @param _addr User wallet
* @return Epoch time of the lock end
*/
function locked__end(address _addr) external view returns (uint256) {
return locked[_addr].end;
}
/**
* @notice Get the current voting power for `msg.sender` at the specified timestamp
* @dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility
* @param addr User wallet address
* @param _t Epoch time to return voting power at
* @return User voting power
*/
function balanceOf(address addr, uint256 _t) internal view returns (uint256) {
uint256 _epoch = user_point_epoch[addr];
if (_epoch == 0) {
return 0;
}
else {
Point memory last_point = user_point_history[addr][_epoch];
last_point.bias -= last_point.slope * (int128(uint128(_t)) - int128(uint128(last_point.ts)));
if (last_point.bias < 0) {
last_point.bias = 0;
}
return uint256(int256(last_point.bias));
}
}
/**
* @notice Get the current voting power for `msg.sender` at the current timestamp
* @dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility
* @param addr User wallet address
* @return User voting power
*/
function balanceOf(address addr) public view returns (uint256) {
return balanceOf(addr, block.timestamp);
}
/**
* @notice Measure voting power of `addr` at block height `_block`
* @dev Adheres to MiniMe `balanceOfAt` interface: https://github.com/Giveth/minime
* @param addr User's wallet address
* @param _block Block to calculate the voting power at
* @return Voting power
*/
function balanceOfAt(address addr, uint256 _block) external view returns (uint256) {
// Copying and pasting totalSupply code because Vyper cannot pass by
// reference yet
require(_block <= block.number);
// Binary search
uint256 _min = 0;
uint256 _max = user_point_epoch[addr];
// Will be always enough for 128-bit numbers
for(uint i = 0; i < 128; i++){
if (_min >= _max) {
break;
}
uint256 _mid = (_min + _max + 1) / 2;
if (user_point_history[addr][_mid].blk <= _block) {
_min = _mid;
}
else {
_max = _mid - 1;
}
}
Point memory upoint = user_point_history[addr][_min];
uint256 max_epoch = epoch;
uint256 _epoch = find_block_epoch(_block, max_epoch);
Point memory point_0 = point_history[_epoch];
uint256 d_block = 0;
uint256 d_t = 0;
if (_epoch < max_epoch) {
Point memory point_1 = point_history[_epoch + 1];
d_block = point_1.blk - point_0.blk;
d_t = point_1.ts - point_0.ts;
}
else {
d_block = block.number - point_0.blk;
d_t = block.timestamp - point_0.ts;
}
uint256 block_time = point_0.ts;
if (d_block != 0) {
block_time += d_t * (_block - point_0.blk) / d_block;
}
upoint.bias -= upoint.slope * (int128(uint128(block_time)) - int128(uint128(upoint.ts)));
if (upoint.bias >= 0) {
return uint256(int256(upoint.bias));
}
else {
return 0;
}
}
/**
* @notice Calculate total voting power at the specified timestamp
* @dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility
* @return Total voting power
*/
function totalSupply(uint256 t) internal view returns (uint256) {
uint256 _epoch = epoch;
Point memory last_point = point_history[_epoch];
return supply_at(last_point, t);
}
/**
* @notice Calculate total voting power at the current timestamp
* @dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility
* @return Total voting power
*/
function totalSupply() public view returns (uint256) {
return totalSupply(block.timestamp);
}
/**
* @notice Calculate total voting power at some point in the past
* @param _block Block to calculate the total voting power at
* @return Total voting power at `_block`
*/
function totalSupplyAt(uint256 _block) external view returns (uint256) {
require(_block <= block.number);
uint256 _epoch = epoch;
uint256 target_epoch = find_block_epoch(_block, _epoch);
Point memory point = point_history[target_epoch];
uint256 dt = 0;
if (target_epoch < _epoch) {
Point memory point_next = point_history[target_epoch + 1];
if (point.blk != point_next.blk) {
dt = ((_block - point.blk) * (point_next.ts - point.ts)) / (point_next.blk - point.blk);
}
}
else {
if (point.blk != block.number) {
dt = ((_block - point.blk) * (block.timestamp - point.ts)) / (block.number - point.blk);
}
}
// Now dt contains info on how far are we beyond point
return supply_at(point, point.ts + dt);
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice Check if the call is from a whitelisted smart contract, revert if not
* @param addr Address to be checked
*/
function assert_not_contract(address addr) internal {
if (addr != tx.origin) {
address checker = smart_wallet_checker;
if (checker != ZERO_ADDRESS){
if (SmartWalletChecker(checker).check(addr)){
return;
}
}
revert("Smart contract depositors not allowed");
}
}
/**
* @notice Record global and per-user data to checkpoint
* @param addr User's wallet address. No user checkpoint if 0x0
* @param old_locked Previous locked amount / end lock time for the user
* @param new_locked New locked amount / end lock time for the user
*/
function _checkpoint(
address addr,
LockedBalance memory old_locked,
LockedBalance memory new_locked
) internal {
Point memory u_old = EMPTY_POINT_FACTORY();
Point memory u_new = EMPTY_POINT_FACTORY();
int128 old_dslope = 0;
int128 new_dslope = 0;
uint256 _epoch = epoch;
if (addr != ZERO_ADDRESS){
// Calculate slopes and biases
// Kept at zero when they have to
// 追加质押
if ((old_locked.end > block.timestamp) && (old_locked.amount > 0)){
u_old.slope = old_locked.amount / int128(uint128(MAXTIME));
u_old.bias = u_old.slope * (int128(uint128(old_locked.end)) - int128(uint128(block.timestamp)));
}
// 新建质押
if ((new_locked.end > block.timestamp) && (new_locked.amount > 0)){
// 时间衰减斜率 / 3
u_new.slope = new_locked.amount / int128(uint128(MAXTIME));
// 当前额外数 / 3
u_new.bias = u_new.slope * (int128(uint128(new_locked.end)) - int128(uint128(block.timestamp)));
}
// Read values of scheduled changes in the slope
// old_locked.end can be in the past and in the future
// new_locked.end can ONLY by in the FUTURE unless everything expired: than zeros
// 新建为0
old_dslope = slope_changes[old_locked.end];
// 新建
if (new_locked.end != 0) {
if (new_locked.end == old_locked.end) {
new_dslope = old_dslope;
}
else {
// 新建为0
new_dslope = slope_changes[new_locked.end];
}
}
}
Point memory last_point = Point({
bias: 0,
slope: 0,
ts: block.timestamp,
blk: block.number
});
if (_epoch > 0) {
last_point = point_history[_epoch];
}
uint256 last_checkpoint = last_point.ts;
// initial_last_point is used for extrapolation to calculate block number
// (approximately, for *At methods) and save them
// as we cannot figure that out exactly from inside the contract
Point memory initial_last_point = last_point;
uint256 block_slope = 0; // dblock/dt
if (block.timestamp > last_point.ts) {
// b / s * 10 ** 18
block_slope = MULTIPLIER * (block.number - last_point.blk) / (block.timestamp - last_point.ts);
}
// If last point is already recorded in this block, slope=0
// But that's ok b/c we know the block in such case
// Go over weeks to fill history and calculate what the current point is
// 上次记录ts -> 满周的ts
uint256 t_i = (last_checkpoint / WEEK) * WEEK;
for(uint i = 0; i < 255; i++){
// Hopefully it won't happen that this won't get used in 4 years!
// If it does, users will be able to withdraw but vote weight will be broken
t_i += WEEK;
int128 d_slope = 0;
if (t_i > block.timestamp) {
// 更新到当前ts
t_i = block.timestamp;
}
else {
// 当前ts之前(包括当前ts)的满周ts
d_slope = slope_changes[t_i];
}
last_point.bias -= last_point.slope * (int128(uint128(t_i)) - int128(uint128(last_checkpoint)));
last_point.slope += d_slope;
if (last_point.bias < 0) {
last_point.bias = 0; // This can happen
}
if (last_point.slope < 0) {
last_point.slope = 0; // This cannot happen - just in case
}
last_checkpoint = t_i;
last_point.ts = t_i;
last_point.blk = initial_last_point.blk + block_slope * (t_i - initial_last_point.ts) / MULTIPLIER;
_epoch += 1;
if (t_i == block.timestamp){
last_point.blk = block.number;
break;
}
else {
point_history[_epoch] = last_point;
}
}
epoch = _epoch;
// Now point_history is filled until t=now
if (addr != ZERO_ADDRESS) {
// If last point was in this block, the slope change has been applied already
// But in such case we have 0 slope(s)
last_point.slope += (u_new.slope - u_old.slope);
last_point.bias += (u_new.bias - u_old.bias);
if (last_point.slope < 0) {
last_point.slope = 0;
}
if (last_point.bias < 0) {
last_point.bias = 0;
}
}
// Record the changed point into history
point_history[_epoch] = last_point;
if (addr != ZERO_ADDRESS) {
// Schedule the slope changes (slope is going down)
// We subtract new_user_slope from [new_locked.end]
// and add old_user_slope to [old_locked.end]
if (old_locked.end > block.timestamp) {
// old_dslope was <something> - u_old.slope, so we cancel that
old_dslope += u_old.slope;
if (new_locked.end == old_locked.end) {
old_dslope -= u_new.slope; // It was a new deposit, not extension
}
slope_changes[old_locked.end] = old_dslope;
}
if (new_locked.end > block.timestamp) {
if (new_locked.end > old_locked.end) {
new_dslope -= u_new.slope; // old slope disappeared at this point
slope_changes[new_locked.end] = new_dslope;
}
// else: we recorded it already in old_dslope
}
// Now handle user history
// Second function needed for 'stack too deep' issues
_checkpoint_part_two(addr, u_new.bias, u_new.slope);
}
}
/**
* @notice Needed for 'stack too deep' issues in _checkpoint()
* @param addr User's wallet address. No user checkpoint if 0x0
* @param _bias from unew
* @param _slope from unew
*/
function _checkpoint_part_two(address addr, int128 _bias, int128 _slope) internal {
uint256 user_epoch = user_point_epoch[addr] + 1;
user_point_epoch[addr] = user_epoch;
user_point_history[addr][user_epoch] = Point({
bias: _bias,
slope: _slope,
ts: block.timestamp,
blk: block.number
});
}
/**
* @notice Deposit and lock tokens for a user
* @param _addr User's wallet address
* @param _value Amount to deposit
* @param unlock_time New time when to unlock the tokens, or 0 if unchanged
* @param locked_balance Previous locked amount / timestamp
*/
function _deposit_for(
address _addr,
uint256 _value,
uint256 unlock_time,
LockedBalance memory locked_balance,
int128 _type
) internal {
LockedBalance memory _locked = locked_balance;
uint256 supply_before = supply;
supply = supply_before + _value;
LockedBalance memory old_locked = _locked;
// Adding to existing lock, or if a lock is expired - creating a new one
_locked.amount += int128(uint128(_value));
if (unlock_time != 0) {
_locked.end = unlock_time;
}
locked[_addr] = _locked;
// Possibilities:
// Both old_locked.end could be current or expired (>/< block.timestamp)
// value == 0 (extend lock) or value > 0 (add to lock or extend lock)
// _locked.end > block.timestamp (always)
_checkpoint(_addr, old_locked, _locked);
if (_value != 0) {
assert(IERC20(token).transferFrom(_addr, address(this), _value));
}
emit Deposit(_addr, _value, _locked.end, _type, block.timestamp);
emit Supply(supply_before, supply_before + _value);
}
// The following ERC20/minime-compatible methods are not real balanceOf and supply!
// They measure the weights for the purpose of voting, so they don't represent
// real coins.
/**
* @notice Binary search to estimate timestamp for block number
* @param _block Block to find
* @param max_epoch Don't go beyond this epoch
* @return Approximate timestamp for block
*/
function find_block_epoch(uint256 _block, uint256 max_epoch) internal view returns (uint256) {
// Binary search
uint256 _min = 0;
uint256 _max = max_epoch;
// Will be always enough for 128-bit numbers
for (uint i = 0; i < 128; i++){
if (_min >= _max) {
break;
}
uint256 _mid = (_min + _max + 1) / 2;
if (point_history[_mid].blk <= _block) {
_min = _mid;
}
else {
_max = _mid - 1;
}
}
return _min;
}
/**
* @notice Calculate total voting power at some point in the past
* @param point The point (bias/slope) to start search from
* @param t Time to calculate the total voting power at
* @return Total voting power at that time
*/
function supply_at(Point memory point, uint256 t) internal view returns (uint256) {
Point memory last_point = point;
uint256 t_i = (last_point.ts / WEEK) * WEEK;
for(uint i = 0; i < 255; i++){
t_i += WEEK;
int128 d_slope = 0;
if (t_i > t) {
t_i = t;
}
else {
d_slope = slope_changes[t_i];
}
last_point.bias -= last_point.slope * (int128(uint128(t_i)) - int128(uint128(last_point.ts)));
if (t_i == t) {
break;
}
last_point.slope += d_slope;
last_point.ts = t_i;
}
if (last_point.bias < 0) {
last_point.bias = 0;
}
return uint256(int256(last_point.bias));
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Record global data to checkpoint
*/
function checkpoint(address _addr) external {
_checkpoint(ZERO_ADDRESS, EMPTY_LOCKED_BALANCE_FACTORY(), EMPTY_LOCKED_BALANCE_FACTORY());
}
/**
* @notice Deposit and lock tokens for a user
* @dev Anyone (even a smart contract) can deposit for someone else, but
cannot extend their locktime and deposit for a brand new user
* @param _addr User's wallet address
* @param _value Amount to add to user's lock
*/
function deposit_for(address _addr, uint256 _value) external nonReentrant {
LockedBalance memory _locked = locked[_addr];
require (_value > 0, "need non-zero value");
require (_locked.amount > 0, "No existing lock found");
require (_locked.end > block.timestamp, "Cannot add to expired lock. Withdraw");
_deposit_for(_addr, _value, 0, locked[_addr], DEPOSIT_FOR_TYPE);
}
function getUnlockTime(uint unlock_time, bool isInput) external view returns(uint) {
if (isInput) {
return unlock_time;
}
return (unlock_time / WEEK) * WEEK;
}
/**
* @notice Deposit `_value` tokens for `msg.sender` and lock until `_unlock_time`
* @param _value Amount to deposit
* @param _unlock_time Epoch time when tokens unlock, rounded down to whole weeks
*/
function create_lock(uint256 _value, uint256 _unlock_time) external nonReentrant {
assert_not_contract(msg.sender);
uint256 unlock_time = (_unlock_time / WEEK) * WEEK ; // Locktime is rounded down to weeks
LockedBalance memory _locked = locked[msg.sender];
require (_value > 0, "need non-zero value");
require (_locked.amount == 0, "Withdraw old tokens first");
require (unlock_time > block.timestamp, "Can only lock until time in the future");
require (unlock_time <= block.timestamp + MAXTIME, "Voting lock can be 3 years max");
_deposit_for(msg.sender, _value, unlock_time, _locked, CREATE_LOCK_TYPE);
}
/**
* @notice Deposit `_value` additional tokens for `msg.sender`
without modifying the unlock time
* @param _value Amount of tokens to deposit and add to the lock
*/
function increase_amount(uint256 _value) external nonReentrant {
assert_not_contract(msg.sender);
LockedBalance memory _locked = locked[msg.sender];
require(_value > 0, "need non-zero value");
require(_locked.amount > 0, "No existing lock found");
require(_locked.end > block.timestamp, "Cannot add to expired lock. Withdraw");
_deposit_for(msg.sender, _value, 0, _locked, INCREASE_LOCK_AMOUNT);
}
/**
* @notice Extend the unlock time for `msg.sender` to `_unlock_time`
* @param _unlock_time New epoch time for unlocking
*/
function increase_unlock_time(uint256 _unlock_time) external nonReentrant {
assert_not_contract(msg.sender);
LockedBalance memory _locked = locked[msg.sender];
uint256 unlock_time = (_unlock_time / WEEK) * WEEK; // Locktime is rounded down to weeks
require(_locked.end > block.timestamp, "Lock expired");
require(_locked.amount > 0, "Nothing is locked");
require(unlock_time > _locked.end, "Can only increase lock duration");
require(unlock_time <= block.timestamp + MAXTIME, "Voting lock can be 3 years max");
_deposit_for(msg.sender, 0, unlock_time, _locked, INCREASE_UNLOCK_TIME);
}
/**
* @notice Withdraw all tokens for `msg.sender`ime`
* @dev Only possible if the lock has expired
*/
function withdraw() external nonReentrant {
LockedBalance memory _locked = locked[msg.sender];
require(block.timestamp >= _locked.end, "The lock didn't expire");
uint256 value = uint256(int256(_locked.amount));
LockedBalance memory old_locked = _locked;
_locked.end = 0;
_locked.amount = 0;
locked[msg.sender] = _locked;
uint256 supply_before = supply;
supply = supply_before - value;
// old_locked can have either expired <= timestamp or zero end
// _locked has only 0 end
// Both can have >= 0 amount
_checkpoint(msg.sender, old_locked, _locked);
require(IERC20(token).transfer(msg.sender, value));
emit Withdraw(msg.sender, value, block.timestamp);
emit Supply(supply_before, supply_before - value);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice Transfer ownership of VotingEscrow contract to `addr`
* @param addr Address to have ownership transferred to
*/
function commit_transfer_ownership(address addr) external onlyAdmin {
future_admin = addr;
emit CommitOwnership(addr);
}
/**
* @notice Apply ownership transfer
*/
function apply_transfer_ownership() external onlyAdmin {
address _admin = future_admin;
assert (_admin != ZERO_ADDRESS); // dev: admin not set
admin = _admin;
emit ApplyOwnership(_admin);
}
/**
* @notice Set an external contract to check for approved smart contract wallets
* @param addr Address of Smart contract checker
*/
function commit_smart_wallet_checker(address addr) external onlyAdmin {
future_smart_wallet_checker = addr;
}
/**
* @notice Apply setting external contract to check approved smart contract wallets
*/
function apply_smart_wallet_checker() external onlyAdmin {
smart_wallet_checker = future_smart_wallet_checker;
}
/**
* @notice Dummy method for compatibility with Aragon
* @dev Dummy method required for Aragon compatibility
*/
function changeController(address _newController) external {
require(msg.sender == controller);
controller = _newController;
}
// Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyAdmin {
// Admin cannot withdraw the staking token from the contract unless currently migrating
// if(!migrationsOn){
// require(tokenAddress != address(FXS), "Not in migration"); // Only Governance / Timelock can trigger a migration
// }
// Only the owner address can ever receive the recovery withdrawal
IERC20(tokenAddress).transfer(admin, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/* ========== EVENTS ========== */
event Recovered(address token, uint256 amount);
event CommitOwnership(address admin);
event ApplyOwnership(address admin);
event Deposit(address indexed provider, uint256 value, uint256 indexed locktime, int128 _type, uint256 ts);
event Withdraw(address indexed provider, uint256 value, uint256 ts);
event Supply(uint256 prevSupply, uint256 supply);
}
| * @notice Get the most recently recorded rate of voting power decrease for `addr` @param addr Address of the user wallet @return Value of the slope/ | function get_last_user_slope(address addr) external view returns (int128) {
uint256 uepoch = user_point_epoch[addr];
return user_point_history[addr][uepoch].slope;
}
| 1,062,028 | [
1,
967,
326,
4486,
19907,
16421,
4993,
434,
331,
17128,
7212,
20467,
364,
1375,
4793,
68,
225,
3091,
5267,
434,
326,
729,
9230,
327,
1445,
434,
326,
17543,
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
] | [
1,
1,
1,
1,
1,
1,
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,
565,
445,
336,
67,
2722,
67,
1355,
67,
30320,
12,
2867,
3091,
13,
3903,
1476,
1135,
261,
474,
10392,
13,
288,
203,
3639,
2254,
5034,
17869,
6127,
273,
729,
67,
1153,
67,
12015,
63,
4793,
15533,
203,
3639,
327,
729,
67,
1153,
67,
8189,
63,
4793,
6362,
344,
6127,
8009,
30320,
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
] |
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: EtherWrapper.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/EtherWrapper.sol
* Docs: https://docs.synthetix.io/contracts/EtherWrapper
*
* Contract Dependencies:
* - IAddressResolver
* - IEtherWrapper
* - MixinResolver
* - MixinSystemSettings
* - Owned
* - Pausable
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
interface IWETH {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// WETH-specific functions.
function deposit() external payable;
function withdraw(uint amount) external;
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Deposit(address indexed to, uint amount);
event Withdrawal(address indexed to, uint amount);
}
// https://docs.synthetix.io/contracts/source/interfaces/ietherwrapper
contract IEtherWrapper {
function mint(uint amount) external;
function burn(uint amount) external;
function distributeFees() external;
function capacity() external view returns (uint);
function getReserves() external view returns (uint);
function totalIssuedSynths() external view returns (uint);
function calculateMintFee(uint amount) public view returns (uint);
function calculateBurnFee(uint amount) public view returns (uint);
function maxETH() public view returns (uint256);
function mintFeeRate() public view returns (uint256);
function burnFeeRate() public view returns (uint256);
function weth() public view returns (IWETH);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/pausable
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
constructor() internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// https://docs.synthetix.io/contracts/source/interfaces/iexchangerates
interface IExchangeRates {
// Structs
struct RateAndUpdatedTime {
uint216 rate;
uint40 time;
}
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozenAtUpperLimit;
bool frozenAtLowerLimit;
}
// Views
function aggregators(bytes32 currencyKey) external view returns (address);
function aggregatorWarningFlags() external view returns (address);
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool);
function canFreezeRate(bytes32 currencyKey) external view returns (bool);
function currentRoundForRate(bytes32 currencyKey) external view returns (uint);
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory);
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value);
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
);
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value);
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint);
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint);
function inversePricing(bytes32 currencyKey)
external
view
returns (
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool frozenAtUpperLimit,
bool frozenAtLowerLimit
);
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256);
function oracle() external view returns (address);
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time);
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time);
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid);
function rateForCurrency(bytes32 currencyKey) external view returns (uint);
function rateIsFlagged(bytes32 currencyKey) external view returns (bool);
function rateIsFrozen(bytes32 currencyKey) external view returns (bool);
function rateIsInvalid(bytes32 currencyKey) external view returns (bool);
function rateIsStale(bytes32 currencyKey) external view returns (bool);
function rateStalePeriod() external view returns (uint);
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times);
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid);
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory);
// Mutative functions
function freezeRate(bytes32 currencyKey) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/ifeepool
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.synthetix.io/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver {
bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings";
bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs";
bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor";
bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio";
bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration";
bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold";
bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay";
bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio";
bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty";
bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod";
bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate";
bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime";
bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags";
bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled";
bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime";
bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit";
bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH";
bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate";
bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal}
constructor(address _resolver) internal MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](1);
addresses[0] = CONTRACT_FLEXIBLESTORAGE;
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) {
if (gasLimitType == CrossDomainMessageGasLimits.Deposit) {
return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) {
return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Reward) {
return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) {
return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT;
} else {
revert("Unknown gas limit type");
}
}
function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType));
}
function getTradingRewardsEnabled() internal view returns (bool) {
return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED);
}
function getWaitingPeriodSecs() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS);
}
function getPriceDeviationThresholdFactor() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR);
}
function getIssuanceRatio() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO);
}
function getFeePeriodDuration() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION);
}
function getTargetThreshold() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD);
}
function getLiquidationDelay() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY);
}
function getLiquidationRatio() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO);
}
function getLiquidationPenalty() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY);
}
function getRateStalePeriod() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD);
}
function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getMinimumStakeTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME);
}
function getAggregatorWarningFlags() internal view returns (address) {
return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS);
}
function getDebtSnapshotStaleTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME);
}
function getEtherWrapperMaxETH() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH);
}
function getEtherWrapperMintFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE);
}
function getEtherWrapperBurnFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
}
// Inheritance
// Internal references
// Libraries
// https://docs.synthetix.io/contracts/source/contracts/etherwrapper
contract EtherWrapper is Owned, Pausable, MixinResolver, MixinSystemSettings, IEtherWrapper {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== CONSTANTS ============== */
/* ========== ENCODED NAMES ========== */
bytes32 internal constant sUSD = "sUSD";
bytes32 internal constant sETH = "sETH";
bytes32 internal constant ETH = "ETH";
bytes32 internal constant SNX = "SNX";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYNTHSETH = "SynthsETH";
bytes32 private constant CONTRACT_SYNTHSUSD = "SynthsUSD";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
// ========== STATE VARIABLES ==========
IWETH internal _weth;
uint public sETHIssued = 0;
uint public sUSDIssued = 0;
uint public feesEscrowed = 0;
constructor(
address _owner,
address _resolver,
address payable _WETH
) public Owned(_owner) Pausable() MixinSystemSettings(_resolver) {
_weth = IWETH(_WETH);
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](5);
newAddresses[0] = CONTRACT_SYNTHSETH;
newAddresses[1] = CONTRACT_SYNTHSUSD;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_ISSUER;
newAddresses[4] = CONTRACT_FEEPOOL;
addresses = combineArrays(existingAddresses, newAddresses);
return addresses;
}
/* ========== INTERNAL VIEWS ========== */
function synthsUSD() internal view returns (ISynth) {
return ISynth(requireAndGetAddress(CONTRACT_SYNTHSUSD));
}
function synthsETH() internal view returns (ISynth) {
return ISynth(requireAndGetAddress(CONTRACT_SYNTHSETH));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
/* ========== PUBLIC FUNCTIONS ========== */
// ========== VIEWS ==========
function capacity() public view returns (uint _capacity) {
// capacity = max(maxETH - balance, 0)
uint balance = getReserves();
if (balance >= maxETH()) {
return 0;
}
return maxETH().sub(balance);
}
function getReserves() public view returns (uint) {
return _weth.balanceOf(address(this));
}
function totalIssuedSynths() public view returns (uint) {
// This contract issues two different synths:
// 1. sETH
// 2. sUSD
//
// The sETH is always backed 1:1 with WETH.
// The sUSD fees are backed by sETH that is withheld during minting and burning.
return exchangeRates().effectiveValue(sETH, sETHIssued, sUSD).add(sUSDIssued);
}
function calculateMintFee(uint amount) public view returns (uint) {
return amount.multiplyDecimalRound(mintFeeRate());
}
function calculateBurnFee(uint amount) public view returns (uint) {
return amount.multiplyDecimalRound(burnFeeRate());
}
function maxETH() public view returns (uint256) {
return getEtherWrapperMaxETH();
}
function mintFeeRate() public view returns (uint256) {
return getEtherWrapperMintFeeRate();
}
function burnFeeRate() public view returns (uint256) {
return getEtherWrapperBurnFeeRate();
}
function weth() public view returns (IWETH) {
return _weth;
}
/* ========== MUTATIVE FUNCTIONS ========== */
// Transfers `amountIn` WETH to mint `amountIn - fees` sETH.
// `amountIn` is inclusive of fees, calculable via `calculateMintFee`.
function mint(uint amountIn) external notPaused {
require(amountIn <= _weth.allowance(msg.sender, address(this)), "Allowance not high enough");
require(amountIn <= _weth.balanceOf(msg.sender), "Balance is too low");
uint currentCapacity = capacity();
require(currentCapacity > 0, "Contract has no spare capacity to mint");
if (amountIn < currentCapacity) {
_mint(amountIn);
} else {
_mint(currentCapacity);
}
}
// Burns `amountIn` sETH for `amountIn - fees` WETH.
// `amountIn` is inclusive of fees, calculable via `calculateBurnFee`.
function burn(uint amountIn) external notPaused {
uint reserves = getReserves();
require(reserves > 0, "Contract cannot burn sETH for WETH, WETH balance is zero");
// principal = [amountIn / (1 + burnFeeRate)]
uint principal = amountIn.divideDecimalRound(SafeDecimalMath.unit().add(burnFeeRate()));
if (principal < reserves) {
_burn(principal, amountIn);
} else {
_burn(reserves, reserves.add(calculateBurnFee(reserves)));
}
}
function distributeFees() external {
// Normalize fee to sUSD
require(!exchangeRates().rateIsInvalid(sETH), "Currency rate is invalid");
uint amountSUSD = exchangeRates().effectiveValue(sETH, feesEscrowed, sUSD);
// Burn sETH.
synthsETH().burn(address(this), feesEscrowed);
// Pay down as much sETH debt as we burn. Any other debt is taken on by the stakers.
sETHIssued = sETHIssued < feesEscrowed ? 0 : sETHIssued.sub(feesEscrowed);
// Issue sUSD to the fee pool
issuer().synths(sUSD).issue(feePool().FEE_ADDRESS(), amountSUSD);
sUSDIssued = sUSDIssued.add(amountSUSD);
// Tell the fee pool about this
feePool().recordFeePaid(amountSUSD);
feesEscrowed = 0;
}
// ========== RESTRICTED ==========
/**
* @notice Fallback function
*/
function() external payable {
revert("Fallback disabled, use mint()");
}
/* ========== INTERNAL FUNCTIONS ========== */
function _mint(uint amountIn) internal {
// Calculate minting fee.
uint feeAmountEth = calculateMintFee(amountIn);
uint principal = amountIn.sub(feeAmountEth);
// Transfer WETH from user.
_weth.transferFrom(msg.sender, address(this), amountIn);
// Mint `amountIn - fees` sETH to user.
synthsETH().issue(msg.sender, principal);
// Escrow fee.
synthsETH().issue(address(this), feeAmountEth);
feesEscrowed = feesEscrowed.add(feeAmountEth);
// Add sETH debt.
sETHIssued = sETHIssued.add(amountIn);
emit Minted(msg.sender, principal, feeAmountEth, amountIn);
}
function _burn(uint principal, uint amountIn) internal {
// for burn, amount is inclusive of the fee.
uint feeAmountEth = amountIn.sub(principal);
require(amountIn <= IERC20(address(synthsETH())).allowance(msg.sender, address(this)), "Allowance not high enough");
require(amountIn <= IERC20(address(synthsETH())).balanceOf(msg.sender), "Balance is too low");
// Burn `amountIn` sETH from user.
synthsETH().burn(msg.sender, amountIn);
// sETH debt is repaid by burning.
sETHIssued = sETHIssued < principal ? 0 : sETHIssued.sub(principal);
// We use burn/issue instead of burning the principal and transferring the fee.
// This saves an approval and is cheaper.
// Escrow fee.
synthsETH().issue(address(this), feeAmountEth);
// We don't update sETHIssued, as only the principal was subtracted earlier.
feesEscrowed = feesEscrowed.add(feeAmountEth);
// Transfer `amount - fees` WETH to user.
_weth.transfer(msg.sender, principal);
emit Burned(msg.sender, principal, feeAmountEth, amountIn);
}
/* ========== EVENTS ========== */
event Minted(address indexed account, uint principal, uint fee, uint amountIn);
event Burned(address indexed account, uint principal, uint fee, uint amountIn);
}
| Transfers `amountIn` WETH to mint `amountIn - fees` sETH. `amountIn` is inclusive of fees, calculable via `calculateMintFee`. | function mint(uint amountIn) external notPaused {
require(amountIn <= _weth.allowance(msg.sender, address(this)), "Allowance not high enough");
require(amountIn <= _weth.balanceOf(msg.sender), "Balance is too low");
uint currentCapacity = capacity();
require(currentCapacity > 0, "Contract has no spare capacity to mint");
if (amountIn < currentCapacity) {
_mint(amountIn);
_mint(currentCapacity);
}
}
| 5,981,679 | [
1,
1429,
18881,
1375,
8949,
382,
68,
678,
1584,
44,
358,
312,
474,
1375,
8949,
382,
300,
1656,
281,
68,
272,
1584,
44,
18,
1375,
8949,
382,
68,
353,
13562,
434,
1656,
281,
16,
3026,
429,
3970,
1375,
11162,
49,
474,
14667,
8338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
312,
474,
12,
11890,
3844,
382,
13,
3903,
486,
28590,
288,
203,
3639,
2583,
12,
8949,
382,
1648,
389,
91,
546,
18,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
13,
3631,
315,
7009,
1359,
486,
3551,
7304,
8863,
203,
3639,
2583,
12,
8949,
382,
1648,
389,
91,
546,
18,
12296,
951,
12,
3576,
18,
15330,
3631,
315,
13937,
353,
4885,
4587,
8863,
203,
203,
3639,
2254,
783,
7437,
273,
7519,
5621,
203,
3639,
2583,
12,
2972,
7437,
405,
374,
16,
315,
8924,
711,
1158,
1694,
834,
7519,
358,
312,
474,
8863,
203,
203,
3639,
309,
261,
8949,
382,
411,
783,
7437,
13,
288,
203,
5411,
389,
81,
474,
12,
8949,
382,
1769,
203,
5411,
389,
81,
474,
12,
2972,
7437,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
contract BowdenCoin {
uint8 Decimals = 6;
uint256 total_supply = 100 * 10**6;
address owner;
uint creation_block;
function BowdenCoin() public{
owner = msg.sender;
balanceOf[msg.sender] = total_supply;
creation_block = block.number;
}
event Transfer(address indexed _from, address indexed _to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 value);
event DoubleSend(address indexed sender, address indexed recipient, uint256 value);
event NextDouble(address indexed _owner, uint256 date);
event Burn(address indexed burner, uint256 value);
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
mapping (address => uint256) public nextDouble;
function name() pure public returns (string _name){
return "BowdenCoin";
}
function symbol() pure public returns (string _symbol){
return "BDC";
}
function decimals() view public returns (uint8 _decimals){
return Decimals;
}
function totalSupply() public constant returns (uint256 total){
return total_supply;
}
function balanceOf(address tokenOwner) public constant returns (uint256 balance){
return balanceOf[tokenOwner];
}
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining){
return allowance[tokenOwner][spender];
}
function transfer(address recipient, uint256 value) public returns (bool success){
require(balanceOf[msg.sender] >= value);
require(balanceOf[recipient] + value >= balanceOf[recipient]);
balanceOf[msg.sender] -= value;
balanceOf[recipient] += value;
Transfer(msg.sender, recipient, value);
if(nextDouble[msg.sender] > block.number && nextDouble[msg.sender] > nextDouble[recipient]){
nextDouble[recipient] = nextDouble[msg.sender];
NextDouble(recipient, nextDouble[recipient]);
}
return true;
}
function approve(address spender, uint256 value) public returns (bool success){
allowance[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address recipient, uint256 value) public
returns (bool success){
require(balanceOf[from] >= value); //ensure from address has available balance
require(balanceOf[recipient] + value >= balanceOf[recipient]); //stop overflow
require(value <= allowance[from][msg.sender]); //ensure msg.sender has enough allowance
balanceOf[from] -= value;
balanceOf[recipient] += value;
allowance[from][msg.sender] -= value;
Transfer(from, recipient, value);
if(nextDouble[from] > block.number && nextDouble[from] > nextDouble[recipient]){
nextDouble[recipient] = nextDouble[from];
NextDouble(recipient, nextDouble[recipient]);
}
return true;
}
function getDoublePeriod() view public returns (uint blocks){
require(block.number >= creation_block);
uint dp = ((block.number-creation_block)/60+1)*8; //goes up by 8 blocks every 60 blocks. Stars at 8
if(dp > 2 days) return 2 days; //equivalent to one months worth of blocks since there is 1 block every 15 seconds
return dp;
}
function canDouble(address tokenOwner) view public returns (bool can_double){
return nextDouble[tokenOwner] <= block.number;
}
function remainingDoublePeriod(uint blockNum) view internal returns (uint){
if(blockNum <= block.number) return 0;
return blockNum - block.number;
}
function getNextDouble(address tokenOwner) view public returns (uint256 blockHeight){
return nextDouble[tokenOwner];
}
function doubleSend(uint256 value, address recipient) public
returns(bool success){
uint half_value = value/2;
require(total_supply + half_value + half_value >= total_supply); //totalSupply overflow check
require(balanceOf[msg.sender] + half_value >= balanceOf[msg.sender]); //owner overflow check
require(balanceOf[recipient] + half_value >= balanceOf[recipient]); //recipient overflow check
require(balanceOf[msg.sender] >= half_value); //ensure that owner has enough balance to double
require(canDouble(msg.sender)); //ensure that owner has the right to double
require(msg.sender != recipient); //cant double and send to yourself
balanceOf[msg.sender] += half_value; //increase the balance of the function caller
balanceOf[recipient] += half_value; //increase the balance of the recipient
DoubleSend(msg.sender, recipient, half_value); //log the double send
total_supply += half_value + half_value; //increase the total supply to match the new amount
nextDouble[msg.sender] = block.number + getDoublePeriod(); //set the time of next doubling to the current block plus the current delay
NextDouble(msg.sender, nextDouble[msg.sender]); //log the next doubling for msg.sender
nextDouble[recipient] = block.number + getDoublePeriod() + remainingDoublePeriod(nextDouble[recipient]); //set the time of next doubling to the same as the msg.sender, plus any excess that was tied to the recipient
NextDouble(recipient, nextDouble[recipient]); //log
return true;
}
function withdrawEth() public returns(bool success){
require(msg.sender == owner); //ensure the owner can only use this
owner.transfer(this.balance); //transfer all eth to owner (failsafe incase eth is sent to this address)
return true;
}
function burnToken(uint256 value) public returns (bool success){
require(balanceOf[msg.sender] >= value); //must have enough in account to burn
require(total_supply - value <= total_supply); //check for underflow
balanceOf[msg.sender] -= value;
total_supply -= value;
Burn(msg.sender,value);
return true;
}
} | recipient overflow check
| require(balanceOf[recipient] + half_value >= balanceOf[recipient]); | 1,805,246 | [
1,
20367,
9391,
866,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
12,
12296,
951,
63,
20367,
65,
397,
8816,
67,
1132,
1545,
11013,
951,
63,
20367,
19226,
9079,
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
] |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {IBToken} from "../interfaces/IBToken.sol";
import {IDebtToken} from "../interfaces/IDebtToken.sol";
import {ILendPoolLoan} from "../interfaces/ILendPoolLoan.sol";
import {ILendPool} from "../interfaces/ILendPool.sol";
import {IReserveOracleGetter} from "../interfaces/IReserveOracleGetter.sol";
import {INFTOracleGetter} from "../interfaces/INFTOracleGetter.sol";
import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
import {WadRayMath} from "../libraries/math/WadRayMath.sol";
import {GenericLogic} from "../libraries/logic/GenericLogic.sol";
import {PercentageMath} from "../libraries/math/PercentageMath.sol";
import {ReserveLogic} from "../libraries/logic/ReserveLogic.sol";
import {NftLogic} from "../libraries/logic/NftLogic.sol";
import {ValidationLogic} from "../libraries/logic/ValidationLogic.sol";
import {ReserveConfiguration} from "../libraries/configuration/ReserveConfiguration.sol";
import {NftConfiguration} from "../libraries/configuration/NftConfiguration.sol";
import {DataTypes} from "../libraries/types/DataTypes.sol";
import {LendPoolStorage} from "./LendPoolStorage.sol";
import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import {IERC721ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
/**
* @title LendPool contract
* @dev Main point of interaction with an Bend protocol's market
* - Users can:
* # Deposit
* # Withdraw
* # Borrow
* # Repay
* # Auction
* # Liquidate
* - To be covered by a proxy contract, owned by the LendPoolAddressesProvider of the specific market
* - All admin functions are callable by the LendPoolConfigurator contract defined also in the
* LendPoolAddressesProvider
* @author Bend
**/
contract LendPool is Initializable, ILendPool, LendPoolStorage, ContextUpgradeable, IERC721ReceiverUpgradeable {
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using ReserveLogic for DataTypes.ReserveData;
using NftLogic for DataTypes.NftData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using NftConfiguration for DataTypes.NftConfigurationMap;
modifier whenNotPaused() {
_whenNotPaused();
_;
}
modifier onlyLendPoolConfigurator() {
_onlyLendPoolConfigurator();
_;
}
function _whenNotPaused() internal view {
require(!_paused, Errors.LP_IS_PAUSED);
}
function _onlyLendPoolConfigurator() internal view {
require(_addressesProvider.getLendPoolConfigurator() == _msgSender(), Errors.LP_CALLER_NOT_LEND_POOL_CONFIGURATOR);
}
/**
* @dev Function is invoked by the proxy contract when the LendPool contract is added to the
* LendPoolAddressesProvider of the market.
* - Caching the address of the LendPoolAddressesProvider in order to reduce gas consumption
* on subsequent operations
* @param provider The address of the LendPoolAddressesProvider
**/
function initialize(ILendPoolAddressesProvider provider) public initializer {
_maxNumberOfReserves = 32;
_maxNumberOfNfts = 256;
_addressesProvider = provider;
}
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens.
* - E.g. User deposits 100 USDC and gets in return 100 bUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the bTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of bTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external override whenNotPaused {
require(onBehalfOf != address(0), Errors.VL_INVALID_ONBEHALFOF_ADDRESS);
DataTypes.ReserveData storage reserve = _reserves[asset];
address bToken = reserve.bTokenAddress;
require(bToken != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
ValidationLogic.validateDeposit(reserve, amount);
reserve.updateState();
reserve.updateInterestRates(asset, bToken, amount, 0);
IERC20Upgradeable(asset).safeTransferFrom(_msgSender(), bToken, amount);
IBToken(bToken).mint(onBehalfOf, amount, reserve.liquidityIndex);
emit Deposit(_msgSender(), asset, amount, onBehalfOf, referralCode);
}
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent bTokens owned
* E.g. User has 100 bUSDC, calls withdraw() and receives 100 USDC, burning the 100 bUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole bToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external override whenNotPaused returns (uint256) {
require(to != address(0), Errors.VL_INVALID_TARGET_ADDRESS);
DataTypes.ReserveData storage reserve = _reserves[asset];
address bToken = reserve.bTokenAddress;
require(bToken != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
uint256 userBalance = IBToken(bToken).balanceOf(_msgSender());
uint256 amountToWithdraw = amount;
if (amount == type(uint256).max) {
amountToWithdraw = userBalance;
}
ValidationLogic.validateWithdraw(reserve, amountToWithdraw, userBalance);
reserve.updateState();
reserve.updateInterestRates(asset, bToken, 0, amountToWithdraw);
IBToken(bToken).burn(_msgSender(), to, amountToWithdraw, reserve.liquidityIndex);
emit Withdraw(_msgSender(), asset, amountToWithdraw, to);
return amountToWithdraw;
}
struct ExecuteBorrowLocalVars {
address initiator;
uint256 ltv;
uint256 liquidationThreshold;
uint256 liquidationBonus;
uint256 loanId;
address reserveOracle;
address nftOracle;
address loanAddress;
}
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset
* - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet
* and lock collateral asset in contract
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param nftAsset The address of the underlying nft used as collateral
* @param nftTokenId The token ID of the underlying nft used as collateral
* @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function borrow(
address asset,
uint256 amount,
address nftAsset,
uint256 nftTokenId,
address onBehalfOf,
uint16 referralCode
) external override whenNotPaused {
require(onBehalfOf != address(0), Errors.VL_INVALID_ONBEHALFOF_ADDRESS);
ExecuteBorrowLocalVars memory vars;
vars.initiator = _msgSender();
DataTypes.ReserveData storage reserveData = _reserves[asset];
DataTypes.NftData storage nftData = _nfts[nftAsset];
// update state MUST BEFORE get borrow amount which is depent on latest borrow index
reserveData.updateState();
// Convert asset amount to ETH
vars.reserveOracle = _addressesProvider.getReserveOracle();
vars.nftOracle = _addressesProvider.getNFTOracle();
vars.loanAddress = _addressesProvider.getLendPoolLoan();
vars.loanId = ILendPoolLoan(vars.loanAddress).getCollateralLoanId(nftAsset, nftTokenId);
ValidationLogic.validateBorrow(
onBehalfOf,
asset,
amount,
reserveData,
nftAsset,
nftData,
vars.loanAddress,
vars.loanId,
vars.reserveOracle,
vars.nftOracle
);
if (vars.loanId == 0) {
IERC721Upgradeable(nftAsset).safeTransferFrom(_msgSender(), address(this), nftTokenId);
vars.loanId = ILendPoolLoan(vars.loanAddress).createLoan(
vars.initiator,
onBehalfOf,
nftAsset,
nftTokenId,
nftData.bNftAddress,
asset,
amount,
reserveData.variableBorrowIndex
);
} else {
ILendPoolLoan(vars.loanAddress).updateLoan(
vars.initiator,
vars.loanId,
amount,
0,
reserveData.variableBorrowIndex
);
}
IDebtToken(reserveData.debtTokenAddress).mint(vars.initiator, onBehalfOf, amount, reserveData.variableBorrowIndex);
// update interest rate according latest borrow amount (utilizaton)
reserveData.updateInterestRates(asset, reserveData.bTokenAddress, 0, amount);
IBToken(reserveData.bTokenAddress).transferUnderlyingTo(vars.initiator, amount);
emit Borrow(
vars.initiator,
asset,
amount,
nftAsset,
nftTokenId,
onBehalfOf,
reserveData.currentVariableBorrowRate,
vars.loanId,
referralCode
);
}
struct RepayLocalVars {
address initiator;
address poolLoan;
address onBehalfOf;
uint256 loanId;
bool isUpdate;
uint256 borrowAmount;
uint256 repayAmount;
}
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned
* - E.g. User repays 100 USDC, burning loan and receives collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param amount The amount to repay
**/
function repay(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external override whenNotPaused returns (uint256, bool) {
RepayLocalVars memory vars;
vars.initiator = _msgSender();
vars.poolLoan = _addressesProvider.getLendPoolLoan();
vars.loanId = ILendPoolLoan(vars.poolLoan).getCollateralLoanId(nftAsset, nftTokenId);
require(vars.loanId != 0, Errors.LP_NFT_IS_NOT_USED_AS_COLLATERAL);
DataTypes.LoanData memory loanData = ILendPoolLoan(vars.poolLoan).getLoan(vars.loanId);
DataTypes.ReserveData storage reserveData = _reserves[loanData.reserveAsset];
DataTypes.NftData storage nftData = _nfts[loanData.nftAsset];
// update state MUST BEFORE get borrow amount which is depent on latest borrow index
reserveData.updateState();
(, vars.borrowAmount) = ILendPoolLoan(vars.poolLoan).getLoanReserveBorrowAmount(vars.loanId);
ValidationLogic.validateRepay(reserveData, nftData, loanData, amount, vars.borrowAmount);
vars.repayAmount = vars.borrowAmount;
vars.isUpdate = false;
if (amount < vars.repayAmount) {
vars.isUpdate = true;
vars.repayAmount = amount;
}
if (vars.isUpdate) {
ILendPoolLoan(vars.poolLoan).updateLoan(
vars.initiator,
vars.loanId,
0,
vars.repayAmount,
reserveData.variableBorrowIndex
);
} else {
ILendPoolLoan(vars.poolLoan).repayLoan(
vars.initiator,
vars.loanId,
nftData.bNftAddress,
vars.repayAmount,
reserveData.variableBorrowIndex
);
}
IDebtToken(reserveData.debtTokenAddress).burn(loanData.borrower, vars.repayAmount, reserveData.variableBorrowIndex);
// update interest rate according latest borrow amount (utilizaton)
reserveData.updateInterestRates(loanData.reserveAsset, reserveData.bTokenAddress, vars.repayAmount, 0);
// transfer repay amount to bToken
IERC20Upgradeable(loanData.reserveAsset).safeTransferFrom(
vars.initiator,
reserveData.bTokenAddress,
vars.repayAmount
);
// transfer erc721 to borrower
if (!vars.isUpdate) {
IERC721Upgradeable(loanData.nftAsset).safeTransferFrom(address(this), loanData.borrower, nftTokenId);
}
emit Repay(
vars.initiator,
loanData.reserveAsset,
vars.repayAmount,
loanData.nftAsset,
loanData.nftTokenId,
loanData.borrower,
vars.loanId
);
return (vars.repayAmount, !vars.isUpdate);
}
/**
* @dev Function to auction a non-healthy position collateral-wise
* - The bidder want to buy collateral asset of the user getting liquidated
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param bidPrice The bid price of the bidder want to buy underlying NFT
* @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of NFT
* is a different wallet
**/
function auction(
address nftAsset,
uint256 nftTokenId,
uint256 bidPrice,
address onBehalfOf
) external override whenNotPaused {
address poolLiquidator = _addressesProvider.getLendPoolLiquidator();
//solium-disable-next-line
(bool success, bytes memory result) = poolLiquidator.delegatecall(
abi.encodeWithSignature("auction(address,uint256,uint256,address)", nftAsset, nftTokenId, bidPrice, onBehalfOf)
);
_verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED);
}
/**
* @notice Redeem a NFT loan which state is in Auction
* - E.g. User repays 100 USDC, burning loan and receives collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param amount The amount to repay the debt and bid fine
**/
function redeem(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external override whenNotPaused returns (uint256) {
address poolLiquidator = _addressesProvider.getLendPoolLiquidator();
//solium-disable-next-line
(bool success, bytes memory result) = poolLiquidator.delegatecall(
abi.encodeWithSignature("redeem(address,uint256,uint256)", nftAsset, nftTokenId, amount)
);
bytes memory resultData = _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED);
uint256 repayAmount = abi.decode(resultData, (uint256));
return (repayAmount);
}
/**
* @dev Function to liquidate a non-healthy position collateral-wise
* - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives
* the collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
**/
function liquidate(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external override whenNotPaused returns (uint256) {
address poolLiquidator = _addressesProvider.getLendPoolLiquidator();
//solium-disable-next-line
(bool success, bytes memory result) = poolLiquidator.delegatecall(
abi.encodeWithSignature("liquidate(address,uint256,uint256)", nftAsset, nftTokenId, amount)
);
bytes memory resultData = _verifyCallResult(success, result, Errors.LP_DELEGATE_CALL_FAILED);
uint256 extraAmount = abi.decode(resultData, (uint256));
return (extraAmount);
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external pure override returns (bytes4) {
operator;
from;
tokenId;
data;
return IERC721ReceiverUpgradeable.onERC721Received.selector;
}
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getReserveConfiguration(address asset)
external
view
override
returns (DataTypes.ReserveConfigurationMap memory)
{
return _reserves[asset].configuration;
}
/**
* @dev Returns the configuration of the NFT
* @param asset The address of the asset of the NFT
* @return The configuration of the NFT
**/
function getNftConfiguration(address asset) external view override returns (DataTypes.NftConfigurationMap memory) {
return _nfts[asset].configuration;
}
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view override returns (uint256) {
return _reserves[asset].getNormalizedIncome();
}
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) {
return _reserves[asset].getNormalizedDebt();
}
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) {
return _reserves[asset];
}
/**
* @dev Returns the state and configuration of the nft
* @param asset The address of the underlying asset of the nft
* @return The state of the nft
**/
function getNftData(address asset) external view override returns (DataTypes.NftData memory) {
return _nfts[asset];
}
/**
* @dev Returns the loan data of the NFT
* @param nftAsset The address of the NFT
* @param reserveAsset The address of the Reserve
* @return totalCollateralInETH the total collateral in ETH of the NFT
* @return totalCollateralInReserve the total collateral in Reserve of the NFT
* @return availableBorrowsInETH the borrowing power in ETH of the NFT
* @return availableBorrowsInReserve the borrowing power in Reserve of the NFT
* @return ltv the loan to value of the user
* @return liquidationThreshold the liquidation threshold of the NFT
* @return liquidationBonus the liquidation bonus of the NFT
**/
function getNftCollateralData(address nftAsset, address reserveAsset)
external
view
override
returns (
uint256 totalCollateralInETH,
uint256 totalCollateralInReserve,
uint256 availableBorrowsInETH,
uint256 availableBorrowsInReserve,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus
)
{
DataTypes.NftData storage nftData = _nfts[nftAsset];
DataTypes.ReserveData storage reserveData = _reserves[reserveAsset];
(ltv, liquidationThreshold, liquidationBonus) = nftData.configuration.getCollateralParams();
(totalCollateralInETH, totalCollateralInReserve) = GenericLogic.calculateNftCollateralData(
reserveAsset,
reserveData,
nftAsset,
nftData,
_addressesProvider.getReserveOracle(),
_addressesProvider.getNFTOracle()
);
availableBorrowsInETH = GenericLogic.calculateAvailableBorrows(totalCollateralInETH, 0, ltv);
availableBorrowsInReserve = GenericLogic.calculateAvailableBorrows(totalCollateralInReserve, 0, ltv);
}
/**
* @dev Returns the debt data of the NFT
* @param nftAsset The address of the NFT
* @param nftTokenId The token id of the NFT
* @return loanId the loan id of the NFT
* @return reserveAsset the address of the Reserve
* @return totalCollateral the total power of the NFT
* @return totalDebt the total debt of the NFT
* @return availableBorrows the borrowing power left of the NFT
* @return healthFactor the current health factor of the NFT
**/
function getNftDebtData(address nftAsset, uint256 nftTokenId)
external
view
override
returns (
uint256 loanId,
address reserveAsset,
uint256 totalCollateral,
uint256 totalDebt,
uint256 availableBorrows,
uint256 healthFactor
)
{
DataTypes.NftData storage nftData = _nfts[nftAsset];
(uint256 ltv, uint256 liquidationThreshold, ) = nftData.configuration.getCollateralParams();
loanId = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getCollateralLoanId(nftAsset, nftTokenId);
if (loanId == 0) {
return (0, address(0), 0, 0, 0, 0);
}
DataTypes.LoanData memory loan = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getLoan(loanId);
reserveAsset = loan.reserveAsset;
DataTypes.ReserveData storage reserveData = _reserves[reserveAsset];
(, totalCollateral) = GenericLogic.calculateNftCollateralData(
reserveAsset,
reserveData,
nftAsset,
nftData,
_addressesProvider.getReserveOracle(),
_addressesProvider.getNFTOracle()
);
(, totalDebt) = GenericLogic.calculateNftDebtData(
reserveAsset,
reserveData,
_addressesProvider.getLendPoolLoan(),
loanId,
_addressesProvider.getReserveOracle()
);
availableBorrows = GenericLogic.calculateAvailableBorrows(totalCollateral, totalDebt, ltv);
if (loan.state == DataTypes.LoanState.Active) {
healthFactor = GenericLogic.calculateHealthFactorFromBalances(totalCollateral, totalDebt, liquidationThreshold);
}
}
/**
* @dev Returns the auction data of the NFT
* @param nftAsset The address of the NFT
* @param nftTokenId The token id of the NFT
* @return loanId the loan id of the NFT
* @return bidderAddress the highest bidder address of the loan
* @return bidPrice the highest bid price in Reserve of the loan
* @return bidBorrowAmount the borrow amount in Reserve of the loan
* @return bidFine the penalty fine of the loan
**/
function getNftAuctionData(address nftAsset, uint256 nftTokenId)
external
view
override
returns (
uint256 loanId,
address bidderAddress,
uint256 bidPrice,
uint256 bidBorrowAmount,
uint256 bidFine
)
{
DataTypes.NftData storage nftData = _nfts[nftAsset];
loanId = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getCollateralLoanId(nftAsset, nftTokenId);
if (loanId != 0) {
DataTypes.LoanData memory loan = ILendPoolLoan(_addressesProvider.getLendPoolLoan()).getLoan(loanId);
bidderAddress = loan.bidderAddress;
bidPrice = loan.bidPrice;
bidBorrowAmount = loan.bidBorrowAmount;
bidFine = loan.bidPrice.percentMul(nftData.configuration.getRedeemFine());
}
}
struct GetLiquidationPriceLocalVars {
address poolLoan;
uint256 loanId;
uint256 thresholdPrice;
uint256 liquidatePrice;
uint256 paybackAmount;
uint256 remainAmount;
}
function getNftLiquidatePrice(address nftAsset, uint256 nftTokenId)
external
view
override
returns (uint256 liquidatePrice, uint256 paybackAmount)
{
GetLiquidationPriceLocalVars memory vars;
vars.poolLoan = _addressesProvider.getLendPoolLoan();
vars.loanId = ILendPoolLoan(vars.poolLoan).getCollateralLoanId(nftAsset, nftTokenId);
if (vars.loanId == 0) {
return (0, 0);
}
DataTypes.LoanData memory loanData = ILendPoolLoan(vars.poolLoan).getLoan(vars.loanId);
DataTypes.ReserveData storage reserveData = _reserves[loanData.reserveAsset];
DataTypes.NftData storage nftData = _nfts[nftAsset];
(vars.paybackAmount, vars.thresholdPrice, vars.liquidatePrice) = GenericLogic.calculateLoanLiquidatePrice(
vars.loanId,
loanData.reserveAsset,
reserveData,
loanData.nftAsset,
nftData,
vars.poolLoan,
_addressesProvider.getReserveOracle(),
_addressesProvider.getNFTOracle()
);
if (vars.liquidatePrice < vars.paybackAmount) {
vars.liquidatePrice = vars.paybackAmount;
}
return (vars.liquidatePrice, vars.paybackAmount);
}
/**
* @dev Validates and finalizes an bToken transfer
* - Only callable by the overlying bToken of the `asset`
* @param asset The address of the underlying asset of the bToken
* @param from The user from which the bToken are transferred
* @param to The user receiving the bTokens
* @param amount The amount being transferred/withdrawn
* @param balanceFromBefore The bToken balance of the `from` user before the transfer
* @param balanceToBefore The bToken balance of the `to` user before the transfer
*/
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromBefore,
uint256 balanceToBefore
) external view override whenNotPaused {
asset;
from;
to;
amount;
balanceFromBefore;
balanceToBefore;
DataTypes.ReserveData storage reserve = _reserves[asset];
require(_msgSender() == reserve.bTokenAddress, Errors.LP_CALLER_MUST_BE_AN_BTOKEN);
ValidationLogic.validateTransfer(from, reserve);
}
/**
* @dev Returns the list of the initialized reserves
**/
function getReservesList() external view override returns (address[] memory) {
address[] memory _activeReserves = new address[](_reservesCount);
for (uint256 i = 0; i < _reservesCount; i++) {
_activeReserves[i] = _reservesList[i];
}
return _activeReserves;
}
/**
* @dev Returns the list of the initialized nfts
**/
function getNftsList() external view override returns (address[] memory) {
address[] memory _activeNfts = new address[](_nftsCount);
for (uint256 i = 0; i < _nftsCount; i++) {
_activeNfts[i] = _nftsList[i];
}
return _activeNfts;
}
/**
* @dev Set the _pause state of the pool
* - Only callable by the LendPoolConfigurator contract
* @param val `true` to pause the pool, `false` to un-pause it
*/
function setPause(bool val) external override onlyLendPoolConfigurator {
_paused = val;
if (_paused) {
emit Paused();
} else {
emit Unpaused();
}
}
/**
* @dev Returns if the LendPool is paused
*/
function paused() external view override returns (bool) {
return _paused;
}
/**
* @dev Returns the cached LendPoolAddressesProvider connected to this contract
**/
function getAddressesProvider() external view override returns (ILendPoolAddressesProvider) {
return _addressesProvider;
}
function setMaxNumberOfReserves(uint256 val) external override onlyLendPoolConfigurator {
_maxNumberOfReserves = val;
}
/**
* @dev Returns the maximum number of reserves supported to be listed in this LendPool
*/
function getMaxNumberOfReserves() public view override returns (uint256) {
return _maxNumberOfReserves;
}
function setMaxNumberOfNfts(uint256 val) external override onlyLendPoolConfigurator {
_maxNumberOfNfts = val;
}
/**
* @dev Returns the maximum number of nfts supported to be listed in this LendPool
*/
function getMaxNumberOfNfts() public view override returns (uint256) {
return _maxNumberOfNfts;
}
/**
* @dev Initializes a reserve, activating it, assigning an bToken and nft loan and an
* interest rate strategy
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param bTokenAddress The address of the bToken that will be assigned to the reserve
* @param debtTokenAddress The address of the debtToken that will be assigned to the reserve
* @param interestRateAddress The address of the interest rate strategy contract
**/
function initReserve(
address asset,
address bTokenAddress,
address debtTokenAddress,
address interestRateAddress
) external override onlyLendPoolConfigurator {
require(AddressUpgradeable.isContract(asset), Errors.LP_NOT_CONTRACT);
_reserves[asset].init(bTokenAddress, debtTokenAddress, interestRateAddress);
_addReserveToList(asset);
}
/**
* @dev Initializes a nft, activating it, assigning nft loan and an
* interest rate strategy
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the underlying asset of the nft
**/
function initNft(address asset, address bNftAddress) external override onlyLendPoolConfigurator {
require(AddressUpgradeable.isContract(asset), Errors.LP_NOT_CONTRACT);
_nfts[asset].init(bNftAddress);
_addNftToList(asset);
require(_addressesProvider.getLendPoolLoan() != address(0), Errors.LPC_INVALIED_LOAN_ADDRESS);
IERC721Upgradeable(asset).setApprovalForAll(_addressesProvider.getLendPoolLoan(), true);
ILendPoolLoan(_addressesProvider.getLendPoolLoan()).initNft(asset, bNftAddress);
}
/**
* @dev Updates the address of the interest rate strategy contract
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param rateAddress The address of the interest rate strategy contract
**/
function setReserveInterestRateAddress(address asset, address rateAddress)
external
override
onlyLendPoolConfigurator
{
_reserves[asset].interestRateAddress = rateAddress;
}
/**
* @dev Sets the configuration bitmap of the reserve as a whole
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param configuration The new configuration bitmap
**/
function setReserveConfiguration(address asset, uint256 configuration) external override onlyLendPoolConfigurator {
_reserves[asset].configuration.data = configuration;
}
/**
* @dev Sets the configuration bitmap of the NFT as a whole
* - Only callable by the LendPoolConfigurator contract
* @param asset The address of the asset of the NFT
* @param configuration The new configuration bitmap
**/
function setNftConfiguration(address asset, uint256 configuration) external override onlyLendPoolConfigurator {
_nfts[asset].configuration.data = configuration;
}
function _addReserveToList(address asset) internal {
uint256 reservesCount = _reservesCount;
require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED);
bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset;
if (!reserveAlreadyAdded) {
_reserves[asset].id = uint8(reservesCount);
_reservesList[reservesCount] = asset;
_reservesCount = reservesCount + 1;
}
}
function _addNftToList(address asset) internal {
uint256 nftsCount = _nftsCount;
require(nftsCount < _maxNumberOfNfts, Errors.LP_NO_MORE_NFTS_ALLOWED);
bool nftAlreadyAdded = _nfts[asset].id != 0 || _nftsList[0] == asset;
if (!nftAlreadyAdded) {
_nfts[asset].id = uint8(nftsCount);
_nftsList[nftsCount] = asset;
_nftsCount = nftsCount + 1;
}
}
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: agpl-3.0
pragma solidity 0.8.4;
import {ILendPoolAddressesProvider} from "./ILendPoolAddressesProvider.sol";
import {IIncentivesController} from "./IIncentivesController.sol";
import {IScaledBalanceToken} from "./IScaledBalanceToken.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
interface IBToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable {
/**
* @dev Emitted when an bToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param incentivesController The address of the incentives controller for this bToken
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
address incentivesController
);
/**
* @dev Initializes the bToken
* @param addressProvider The address of the address provider where this bToken will be used
* @param treasury The address of the Bend treasury, receiving the fees on this bToken
* @param underlyingAsset The address of the underlying asset of this bToken
*/
function initialize(
ILendPoolAddressesProvider addressProvider,
address treasury,
address underlyingAsset,
uint8 bTokenDecimals,
string calldata bTokenName,
string calldata bTokenSymbol
) external;
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` bTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after bTokens are burned
* @param from The owner of the bTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed from, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns bTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the bTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints bTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IIncentivesController);
/**
* @dev Returns the address of the underlying asset of this bToken
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol";
import {IIncentivesController} from "./IIncentivesController.sol";
import {IScaledBalanceToken} from "./IScaledBalanceToken.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
/**
* @title IDebtToken
* @author Bend
* @notice Defines the basic interface for a debt token.
**/
interface IDebtToken is IScaledBalanceToken, IERC20Upgradeable, IERC20MetadataUpgradeable {
/**
* @dev Emitted when a debt token is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lend pool
* @param incentivesController The address of the incentives controller
* @param debtTokenDecimals the decimals of the debt token
* @param debtTokenName the name of the debt token
* @param debtTokenSymbol the symbol of the debt token
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address incentivesController,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol
);
/**
* @dev Initializes the debt token.
* @param addressProvider The address of the lend pool
* @param underlyingAsset The address of the underlying asset
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendPoolAddressesProvider addressProvider,
address underlyingAsset,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol
) external;
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints debt token to the `user` address
* @param user The address receiving the borrowed underlying
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IIncentivesController);
/**
* @dev delegates borrowing power to a user on the specific debt token
* @param delegatee the address receiving the delegated borrowing power
* @param amount the maximum amount being delegated. Delegation will still
* respect the liquidation constraints (even if delegated, a delegatee cannot
* force a delegator HF to go below 1)
**/
function approveDelegation(address delegatee, uint256 amount) external;
/**
* @dev returns the borrow allowance of the user
* @param fromUser The user to giving allowance
* @param toUser The user to give allowance to
* @return the current allowance of toUser
**/
function borrowAllowance(address fromUser, address toUser) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {DataTypes} from "../libraries/types/DataTypes.sol";
interface ILendPoolLoan {
/**
* @dev Emitted on initialization to share location of dependent notes
* @param pool The address of the associated lend pool
*/
event Initialized(address indexed pool);
/**
* @dev Emitted when a loan is created
* @param user The address initiating the action
*/
event LoanCreated(
address indexed user,
address indexed onBehalfOf,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amount,
uint256 borrowIndex
);
/**
* @dev Emitted when a loan is updated
* @param user The address initiating the action
*/
event LoanUpdated(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amountAdded,
uint256 amountTaken,
uint256 borrowIndex
);
/**
* @dev Emitted when a loan is repaid by the borrower
* @param user The address initiating the action
*/
event LoanRepaid(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amount,
uint256 borrowIndex
);
/**
* @dev Emitted when a loan is auction by the liquidator
* @param user The address initiating the action
*/
event LoanAuctioned(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
uint256 amount,
uint256 borrowIndex,
address bidder,
uint256 price,
address previousBidder,
uint256 previousPrice
);
/**
* @dev Emitted when a loan is redeemed
* @param user The address initiating the action
*/
event LoanRedeemed(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amountTaken,
uint256 borrowIndex
);
/**
* @dev Emitted when a loan is liquidate by the liquidator
* @param user The address initiating the action
*/
event LoanLiquidated(
address indexed user,
uint256 indexed loanId,
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 amount,
uint256 borrowIndex
);
function initNft(address nftAsset, address bNftAddress) external;
/**
* @dev Create store a loan object with some params
* @param initiator The address of the user initiating the borrow
* @param onBehalfOf The address receiving the loan
*/
function createLoan(
address initiator,
address onBehalfOf,
address nftAsset,
uint256 nftTokenId,
address bNftAddress,
address reserveAsset,
uint256 amount,
uint256 borrowIndex
) external returns (uint256);
/**
* @dev Update the given loan with some params
*
* Requirements:
* - The caller must be a holder of the loan
* - The loan must be in state Active
* @param initiator The address of the user initiating the borrow
*/
function updateLoan(
address initiator,
uint256 loanId,
uint256 amountAdded,
uint256 amountTaken,
uint256 borrowIndex
) external;
/**
* @dev Repay the given loan
*
* Requirements:
* - The caller must be a holder of the loan
* - The caller must send in principal + interest
* - The loan must be in state Active
*
* @param initiator The address of the user initiating the repay
* @param loanId The loan getting burned
* @param bNftAddress The address of bNFT
*/
function repayLoan(
address initiator,
uint256 loanId,
address bNftAddress,
uint256 amount,
uint256 borrowIndex
) external;
/**
* @dev Auction the given loan
*
* Requirements:
* - The price must be greater than current highest price
* - The loan must be in state Active or Auction
*
* @param initiator The address of the user initiating the auction
* @param loanId The loan getting auctioned
* @param bidPrice The bid price of this auction
*/
function auctionLoan(
address initiator,
uint256 loanId,
address onBehalfOf,
uint256 bidPrice,
uint256 borrowAmount,
uint256 borrowIndex
) external;
/**
* @dev Redeem the given loan with some params
*
* Requirements:
* - The caller must be a holder of the loan
* - The loan must be in state Auction
* @param initiator The address of the user initiating the borrow
*/
function redeemLoan(
address initiator,
uint256 loanId,
uint256 amountTaken,
uint256 borrowIndex
) external;
/**
* @dev Liquidate the given loan
*
* Requirements:
* - The caller must send in principal + interest
* - The loan must be in state Active
*
* @param initiator The address of the user initiating the auction
* @param loanId The loan getting burned
* @param bNftAddress The address of bNFT
*/
function liquidateLoan(
address initiator,
uint256 loanId,
address bNftAddress,
uint256 borrowAmount,
uint256 borrowIndex
) external;
function borrowerOf(uint256 loanId) external view returns (address);
function getCollateralLoanId(address nftAsset, uint256 nftTokenId) external view returns (uint256);
function getLoan(uint256 loanId) external view returns (DataTypes.LoanData memory loanData);
function getLoanCollateralAndReserve(uint256 loanId)
external
view
returns (
address nftAsset,
uint256 nftTokenId,
address reserveAsset,
uint256 scaledAmount
);
function getLoanReserveBorrowScaledAmount(uint256 loanId) external view returns (address, uint256);
function getLoanReserveBorrowAmount(uint256 loanId) external view returns (address, uint256);
function getLoanHighestBid(uint256 loanId) external view returns (address, uint256);
function getNftCollateralAmount(address nftAsset) external view returns (uint256);
function getUserNftCollateralAmount(address user, address nftAsset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {ILendPoolAddressesProvider} from "./ILendPoolAddressesProvider.sol";
import {DataTypes} from "../libraries/types/DataTypes.sol";
interface ILendPool {
/**
* @dev Emitted on deposit()
* @param user The address initiating the deposit
* @param amount The amount deposited
* @param reserve The address of the underlying asset of the reserve
* @param onBehalfOf The beneficiary of the deposit, receiving the bTokens
* @param referral The referral code used
**/
event Deposit(
address user,
address indexed reserve,
uint256 amount,
address indexed onBehalfOf,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param user The address initiating the withdrawal, owner of bTokens
* @param reserve The address of the underlyng asset being withdrawn
* @param amount The amount to be withdrawn
* @param to Address that will receive the underlying
**/
event Withdraw(address indexed user, address indexed reserve, uint256 amount, address indexed to);
/**
* @dev Emitted on borrow() when loan needs to be opened
* @param user The address of the user initiating the borrow(), receiving the funds
* @param reserve The address of the underlying asset being borrowed
* @param amount The amount borrowed out
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token id of the underlying NFT used as collateral
* @param onBehalfOf The address that will be getting the loan
* @param referral The referral code used
**/
event Borrow(
address user,
address indexed reserve,
uint256 amount,
address nftAsset,
uint256 nftTokenId,
address indexed onBehalfOf,
uint256 borrowRate,
uint256 loanId,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param user The address of the user initiating the repay(), providing the funds
* @param reserve The address of the underlying asset of the reserve
* @param amount The amount repaid
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token id of the underlying NFT used as collateral
* @param borrower The beneficiary of the repayment, getting his debt reduced
* @param loanId The loan ID of the NFT loans
**/
event Repay(
address user,
address indexed reserve,
uint256 amount,
address indexed nftAsset,
uint256 nftTokenId,
address indexed borrower,
uint256 loanId
);
/**
* @dev Emitted when a borrower's loan is auctioned.
* @param user The address of the user initiating the auction
* @param reserve The address of the underlying asset of the reserve
* @param bidPrice The price of the underlying reserve given by the bidder
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token id of the underlying NFT used as collateral
* @param onBehalfOf The address that will be getting the NFT
* @param loanId The loan ID of the NFT loans
**/
event Auction(
address user,
address indexed reserve,
uint256 bidPrice,
address indexed nftAsset,
uint256 nftTokenId,
address onBehalfOf,
address indexed borrower,
uint256 loanId
);
/**
* @dev Emitted on redeem()
* @param user The address of the user initiating the redeem(), providing the funds
* @param reserve The address of the underlying asset of the reserve
* @param borrowAmount The borrow amount repaid
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token id of the underlying NFT used as collateral
* @param loanId The loan ID of the NFT loans
**/
event Redeem(
address user,
address indexed reserve,
uint256 borrowAmount,
uint256 fineAmount,
address indexed nftAsset,
uint256 nftTokenId,
address indexed borrower,
uint256 loanId
);
/**
* @dev Emitted when a borrower's loan is liquidated.
* @param user The address of the user initiating the auction
* @param reserve The address of the underlying asset of the reserve
* @param repayAmount The amount of reserve repaid by the liquidator
* @param remainAmount The amount of reserve received by the borrower
* @param loanId The loan ID of the NFT loans
**/
event Liquidate(
address user,
address indexed reserve,
uint256 repayAmount,
uint256 remainAmount,
address indexed nftAsset,
uint256 nftTokenId,
address indexed borrower,
uint256 loanId
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendPool contract. The event is therefore replicated here so it
* gets added to the LendPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens.
* - E.g. User deposits 100 USDC and gets in return 100 bUSDC
* @param reserve The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the bTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of bTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address reserve,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent bTokens owned
* E.g. User has 100 bUSDC, calls withdraw() and receives 100 USDC, burning the 100 bUSDC
* @param reserve The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole bToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address reserve,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral
* - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet
* and lock collateral asset in contract
* @param reserveAsset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param onBehalfOf Address of the user who will receive the loan. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function borrow(
address reserveAsset,
uint256 amount,
address nftAsset,
uint256 nftTokenId,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned
* - E.g. User repays 100 USDC, burning loan and receives collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param amount The amount to repay
* @return The final amount repaid, loan is burned or not
**/
function repay(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external returns (uint256, bool);
/**
* @dev Function to auction a non-healthy position collateral-wise
* - The caller (liquidator) want to buy collateral asset of the user getting liquidated
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param bidPrice The bid price of the liquidator want to buy the underlying NFT
* @param onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of NFT
* is a different wallet
**/
function auction(
address nftAsset,
uint256 nftTokenId,
uint256 bidPrice,
address onBehalfOf
) external;
/**
* @notice Redeem a NFT loan which state is in Auction
* - E.g. User repays 100 USDC, burning loan and receives collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
* @param amount The amount to repay the debt and bid fine
**/
function redeem(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external returns (uint256);
/**
* @dev Function to liquidate a non-healthy position collateral-wise
* - The caller (liquidator) buy collateral asset of the user getting liquidated, and receives
* the collateral asset
* @param nftAsset The address of the underlying NFT used as collateral
* @param nftTokenId The token ID of the underlying NFT used as collateral
**/
function liquidate(
address nftAsset,
uint256 nftTokenId,
uint256 amount
) external returns (uint256);
/**
* @dev Validates and finalizes an bToken transfer
* - Only callable by the overlying bToken of the `asset`
* @param asset The address of the underlying asset of the bToken
* @param from The user from which the bTokens are transferred
* @param to The user receiving the bTokens
* @param amount The amount being transferred/withdrawn
* @param balanceFromBefore The bToken balance of the `from` user before the transfer
* @param balanceToBefore The bToken balance of the `to` user before the transfer
*/
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromBefore,
uint256 balanceToBefore
) external view;
function getReserveConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);
function getNftConfiguration(address asset) external view returns (DataTypes.NftConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function getReservesList() external view returns (address[] memory);
function getNftData(address asset) external view returns (DataTypes.NftData memory);
/**
* @dev Returns the loan data of the NFT
* @param nftAsset The address of the NFT
* @param reserveAsset The address of the Reserve
* @return totalCollateralInETH the total collateral in ETH of the NFT
* @return totalCollateralInReserve the total collateral in Reserve of the NFT
* @return availableBorrowsInETH the borrowing power in ETH of the NFT
* @return availableBorrowsInReserve the borrowing power in Reserve of the NFT
* @return ltv the loan to value of the user
* @return liquidationThreshold the liquidation threshold of the NFT
* @return liquidationBonus the liquidation bonus of the NFT
**/
function getNftCollateralData(address nftAsset, address reserveAsset)
external
view
returns (
uint256 totalCollateralInETH,
uint256 totalCollateralInReserve,
uint256 availableBorrowsInETH,
uint256 availableBorrowsInReserve,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus
);
/**
* @dev Returns the debt data of the NFT
* @param nftAsset The address of the NFT
* @param nftTokenId The token id of the NFT
* @return loanId the loan id of the NFT
* @return reserveAsset the address of the Reserve
* @return totalCollateral the total power of the NFT
* @return totalDebt the total debt of the NFT
* @return availableBorrows the borrowing power left of the NFT
* @return healthFactor the current health factor of the NFT
**/
function getNftDebtData(address nftAsset, uint256 nftTokenId)
external
view
returns (
uint256 loanId,
address reserveAsset,
uint256 totalCollateral,
uint256 totalDebt,
uint256 availableBorrows,
uint256 healthFactor
);
/**
* @dev Returns the auction data of the NFT
* @param nftAsset The address of the NFT
* @param nftTokenId The token id of the NFT
* @return loanId the loan id of the NFT
* @return bidderAddress the highest bidder address of the loan
* @return bidPrice the highest bid price in Reserve of the loan
* @return bidBorrowAmount the borrow amount in Reserve of the loan
* @return bidFine the penalty fine of the loan
**/
function getNftAuctionData(address nftAsset, uint256 nftTokenId)
external
view
returns (
uint256 loanId,
address bidderAddress,
uint256 bidPrice,
uint256 bidBorrowAmount,
uint256 bidFine
);
function getNftLiquidatePrice(address nftAsset, uint256 nftTokenId)
external
view
returns (uint256 liquidatePrice, uint256 paybackAmount);
function getNftsList() external view returns (address[] memory);
/**
* @dev Set the _pause state of a reserve
* - Only callable by the LendPool contract
* @param val `true` to pause the reserve, `false` to un-pause it
*/
function setPause(bool val) external;
/**
* @dev Returns if the LendPool is paused
*/
function paused() external view returns (bool);
function getAddressesProvider() external view returns (ILendPoolAddressesProvider);
function initReserve(
address asset,
address bTokenAddress,
address debtTokenAddress,
address interestRateAddress
) external;
function initNft(address asset, address bNftAddress) external;
function setReserveInterestRateAddress(address asset, address rateAddress) external;
function setReserveConfiguration(address asset, uint256 configuration) external;
function setNftConfiguration(address asset, uint256 configuration) external;
function setMaxNumberOfReserves(uint256 val) external;
function setMaxNumberOfNfts(uint256 val) external;
function getMaxNumberOfReserves() external view returns (uint256);
function getMaxNumberOfNfts() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/************
@title IReserveOracleGetter interface
@notice Interface for getting Reserve price oracle.*/
interface IReserveOracleGetter {
/* CAUTION: Price uint is ETH based (WEI, 18 decimals) */
/***********
@dev returns the asset price in ETH
*/
function getAssetPrice(address asset) external view returns (uint256);
// get twap price depending on _period
function getTwapPrice(address _priceFeedKey, uint256 _interval) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/************
@title INFTOracleGetter interface
@notice Interface for getting NFT price oracle.*/
interface INFTOracleGetter {
/* CAUTION: Price uint is ETH based (WEI, 18 decimals) */
/***********
@dev returns the asset price in ETH
*/
function getAssetPrice(address asset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/**
* @title LendPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Bend Governance
* @author Bend
**/
interface ILendPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendPoolUpdated(address indexed newAddress, bytes encodedCallData);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendPoolConfiguratorUpdated(address indexed newAddress, bytes encodedCallData);
event ReserveOracleUpdated(address indexed newAddress);
event NftOracleUpdated(address indexed newAddress);
event LendPoolLoanUpdated(address indexed newAddress, bytes encodedCallData);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy, bytes encodedCallData);
event BNFTRegistryUpdated(address indexed newAddress);
event LendPoolLiquidatorUpdated(address indexed newAddress);
event IncentivesControllerUpdated(address indexed newAddress);
event UIDataProviderUpdated(address indexed newAddress);
event BendDataProviderUpdated(address indexed newAddress);
event WalletBalanceProviderUpdated(address indexed newAddress);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(
bytes32 id,
address impl,
bytes memory encodedCallData
) external;
function getAddress(bytes32 id) external view returns (address);
function getLendPool() external view returns (address);
function setLendPoolImpl(address pool, bytes memory encodedCallData) external;
function getLendPoolConfigurator() external view returns (address);
function setLendPoolConfiguratorImpl(address configurator, bytes memory encodedCallData) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getReserveOracle() external view returns (address);
function setReserveOracle(address reserveOracle) external;
function getNFTOracle() external view returns (address);
function setNFTOracle(address nftOracle) external;
function getLendPoolLoan() external view returns (address);
function setLendPoolLoanImpl(address loan, bytes memory encodedCallData) external;
function getBNFTRegistry() external view returns (address);
function setBNFTRegistry(address factory) external;
function getLendPoolLiquidator() external view returns (address);
function setLendPoolLiquidator(address liquidator) external;
function getIncentivesController() external view returns (address);
function setIncentivesController(address controller) external;
function getUIDataProvider() external view returns (address);
function setUIDataProvider(address provider) external;
function getBendDataProvider() external view returns (address);
function setBendDataProvider(address provider) external;
function getWalletBalanceProvider() external view returns (address);
function setWalletBalanceProvider(address provider) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
/**
* @title Errors library
* @author Bend
* @notice Defines the error messages emitted by the different contracts of the Bend protocol
*/
library Errors {
enum ReturnCode {
SUCCESS,
FAILED
}
string public constant SUCCESS = "0";
//common errors
string public constant CALLER_NOT_POOL_ADMIN = "100"; // 'The caller must be the pool admin'
string public constant CALLER_NOT_ADDRESS_PROVIDER = "101";
string public constant INVALID_FROM_BALANCE_AFTER_TRANSFER = "102";
string public constant INVALID_TO_BALANCE_AFTER_TRANSFER = "103";
//math library erros
string public constant MATH_MULTIPLICATION_OVERFLOW = "200";
string public constant MATH_ADDITION_OVERFLOW = "201";
string public constant MATH_DIVISION_BY_ZERO = "202";
//validation & check errors
string public constant VL_INVALID_AMOUNT = "301"; // 'Amount must be greater than 0'
string public constant VL_NO_ACTIVE_RESERVE = "302"; // 'Action requires an active reserve'
string public constant VL_RESERVE_FROZEN = "303"; // 'Action cannot be performed because the reserve is frozen'
string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = "304"; // 'User cannot withdraw more than the available balance'
string public constant VL_BORROWING_NOT_ENABLED = "305"; // 'Borrowing is not enabled'
string public constant VL_COLLATERAL_BALANCE_IS_0 = "306"; // 'The collateral balance is 0'
string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = "307"; // 'Health factor is lesser than the liquidation threshold'
string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = "308"; // 'There is not enough collateral to cover a new borrow'
string public constant VL_NO_DEBT_OF_SELECTED_TYPE = "309"; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt'
string public constant VL_NO_ACTIVE_NFT = "310";
string public constant VL_NFT_FROZEN = "311";
string public constant VL_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = "312"; // 'User did not borrow the specified currency'
string public constant VL_INVALID_HEALTH_FACTOR = "313";
string public constant VL_INVALID_ONBEHALFOF_ADDRESS = "314";
string public constant VL_INVALID_TARGET_ADDRESS = "315";
string public constant VL_INVALID_RESERVE_ADDRESS = "316";
string public constant VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER = "317";
string public constant VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER = "318";
string public constant VL_HEALTH_FACTOR_HIGHER_THAN_LIQUIDATION_THRESHOLD = "319";
//lend pool errors
string public constant LP_CALLER_NOT_LEND_POOL_CONFIGURATOR = "400"; // 'The caller of the function is not the lending pool configurator'
string public constant LP_IS_PAUSED = "401"; // 'Pool is paused'
string public constant LP_NO_MORE_RESERVES_ALLOWED = "402";
string public constant LP_NOT_CONTRACT = "403";
string public constant LP_BORROW_NOT_EXCEED_LIQUIDATION_THRESHOLD = "404";
string public constant LP_BORROW_IS_EXCEED_LIQUIDATION_PRICE = "405";
string public constant LP_NO_MORE_NFTS_ALLOWED = "406";
string public constant LP_INVALIED_USER_NFT_AMOUNT = "407";
string public constant LP_INCONSISTENT_PARAMS = "408";
string public constant LP_NFT_IS_NOT_USED_AS_COLLATERAL = "409";
string public constant LP_CALLER_MUST_BE_AN_BTOKEN = "410";
string public constant LP_INVALIED_NFT_AMOUNT = "411";
string public constant LP_NFT_HAS_USED_AS_COLLATERAL = "412";
string public constant LP_DELEGATE_CALL_FAILED = "413";
string public constant LP_AMOUNT_LESS_THAN_EXTRA_DEBT = "414";
string public constant LP_AMOUNT_LESS_THAN_REDEEM_THRESHOLD = "415";
//lend pool loan errors
string public constant LPL_INVALID_LOAN_STATE = "480";
string public constant LPL_INVALID_LOAN_AMOUNT = "481";
string public constant LPL_INVALID_TAKEN_AMOUNT = "482";
string public constant LPL_AMOUNT_OVERFLOW = "483";
string public constant LPL_BID_PRICE_LESS_THAN_LIQUIDATION_PRICE = "484";
string public constant LPL_BID_PRICE_LESS_THAN_HIGHEST_PRICE = "485";
string public constant LPL_BID_REDEEM_DURATION_HAS_END = "486";
string public constant LPL_BID_USER_NOT_SAME = "487";
string public constant LPL_BID_REPAY_AMOUNT_NOT_ENOUGH = "488";
string public constant LPL_BID_AUCTION_DURATION_HAS_END = "489";
string public constant LPL_BID_AUCTION_DURATION_NOT_END = "490";
string public constant LPL_BID_PRICE_LESS_THAN_BORROW = "491";
string public constant LPL_INVALID_BIDDER_ADDRESS = "492";
string public constant LPL_AMOUNT_LESS_THAN_BID_FINE = "493";
//common token errors
string public constant CT_CALLER_MUST_BE_LEND_POOL = "500"; // 'The caller of this function must be a lending pool'
string public constant CT_INVALID_MINT_AMOUNT = "501"; //invalid amount to mint
string public constant CT_INVALID_BURN_AMOUNT = "502"; //invalid amount to burn
string public constant CT_BORROW_ALLOWANCE_NOT_ENOUGH = "503";
//reserve logic errors
string public constant RL_RESERVE_ALREADY_INITIALIZED = "601"; // 'Reserve has already been initialized'
string public constant RL_LIQUIDITY_INDEX_OVERFLOW = "602"; // Liquidity index overflows uint128
string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = "603"; // Variable borrow index overflows uint128
string public constant RL_LIQUIDITY_RATE_OVERFLOW = "604"; // Liquidity rate overflows uint128
string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = "605"; // Variable borrow rate overflows uint128
//configure errors
string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = "700"; // 'The liquidity of the reserve needs to be 0'
string public constant LPC_INVALID_CONFIGURATION = "701"; // 'Invalid risk parameters for the reserve'
string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = "702"; // 'The caller must be the emergency admin'
string public constant LPC_INVALIED_BNFT_ADDRESS = "703";
string public constant LPC_INVALIED_LOAN_ADDRESS = "704";
string public constant LPC_NFT_LIQUIDITY_NOT_0 = "705";
//reserve config errors
string public constant RC_INVALID_LTV = "730";
string public constant RC_INVALID_LIQ_THRESHOLD = "731";
string public constant RC_INVALID_LIQ_BONUS = "732";
string public constant RC_INVALID_DECIMALS = "733";
string public constant RC_INVALID_RESERVE_FACTOR = "734";
string public constant RC_INVALID_REDEEM_DURATION = "735";
string public constant RC_INVALID_AUCTION_DURATION = "736";
string public constant RC_INVALID_REDEEM_FINE = "737";
string public constant RC_INVALID_REDEEM_THRESHOLD = "738";
//address provider erros
string public constant LPAPR_PROVIDER_NOT_REGISTERED = "760"; // 'Provider is not registered'
string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = "761";
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
/**
* @title WadRayMath library
* @author Bend
* @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: agpl-3.0
pragma solidity 0.8.4;
import {ILendPoolLoan} from "../../interfaces/ILendPoolLoan.sol";
import {IReserveOracleGetter} from "../../interfaces/IReserveOracleGetter.sol";
import {INFTOracleGetter} from "../../interfaces/INFTOracleGetter.sol";
import {WadRayMath} from "../math/WadRayMath.sol";
import {PercentageMath} from "../math/PercentageMath.sol";
import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol";
import {NftConfiguration} from "../configuration/NftConfiguration.sol";
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
import {ReserveLogic} from "./ReserveLogic.sol";
/**
* @title GenericLogic library
* @author Bend
* @notice Implements protocol-level logic to calculate and validate the state of a user
*/
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using WadRayMath for uint256;
using PercentageMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using NftConfiguration for DataTypes.NftConfigurationMap;
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;
struct CalculateLoanDataVars {
uint256 reserveUnitPrice;
uint256 reserveUnit;
uint256 reserveDecimals;
uint256 healthFactor;
uint256 totalCollateralInETH;
uint256 totalCollateralInReserve;
uint256 totalDebtInETH;
uint256 totalDebtInReserve;
uint256 nftLtv;
uint256 nftLiquidationThreshold;
address nftAsset;
uint256 nftTokenId;
uint256 nftUnitPrice;
}
/**
* @dev Calculates the nft loan data.
* this includes the total collateral/borrow balances in Reserve,
* the Loan To Value, the Liquidation Ratio, and the Health factor.
* @param reserveData Data of the reserve
* @param nftData Data of the nft
* @param reserveOracle The price oracle address of reserve
* @param nftOracle The price oracle address of nft
* @return The total collateral and total debt of the loan in Reserve, the ltv, liquidation threshold and the HF
**/
function calculateLoanData(
address reserveAddress,
DataTypes.ReserveData storage reserveData,
address nftAddress,
DataTypes.NftData storage nftData,
address loanAddress,
uint256 loanId,
address reserveOracle,
address nftOracle
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
CalculateLoanDataVars memory vars;
(vars.nftLtv, vars.nftLiquidationThreshold, ) = nftData.configuration.getCollateralParams();
// calculate total borrow balance for the loan
if (loanId != 0) {
(vars.totalDebtInETH, vars.totalDebtInReserve) = calculateNftDebtData(
reserveAddress,
reserveData,
loanAddress,
loanId,
reserveOracle
);
}
// calculate total collateral balance for the nft
(vars.totalCollateralInETH, vars.totalCollateralInReserve) = calculateNftCollateralData(
reserveAddress,
reserveData,
nftAddress,
nftData,
reserveOracle,
nftOracle
);
// calculate health by borrow and collateral
vars.healthFactor = calculateHealthFactorFromBalances(
vars.totalCollateralInReserve,
vars.totalDebtInReserve,
vars.nftLiquidationThreshold
);
return (vars.totalCollateralInReserve, vars.totalDebtInReserve, vars.healthFactor);
}
function calculateNftDebtData(
address reserveAddress,
DataTypes.ReserveData storage reserveData,
address loanAddress,
uint256 loanId,
address reserveOracle
) internal view returns (uint256, uint256) {
CalculateLoanDataVars memory vars;
// all asset price has converted to ETH based, unit is in WEI (18 decimals)
vars.reserveDecimals = reserveData.configuration.getDecimals();
vars.reserveUnit = 10**vars.reserveDecimals;
vars.reserveUnitPrice = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAddress);
(, vars.totalDebtInReserve) = ILendPoolLoan(loanAddress).getLoanReserveBorrowAmount(loanId);
vars.totalDebtInETH = (vars.totalDebtInReserve * vars.reserveUnitPrice) / vars.reserveUnit;
return (vars.totalDebtInETH, vars.totalDebtInReserve);
}
function calculateNftCollateralData(
address reserveAddress,
DataTypes.ReserveData storage reserveData,
address nftAddress,
DataTypes.NftData storage nftData,
address reserveOracle,
address nftOracle
) internal view returns (uint256, uint256) {
reserveData;
nftData;
CalculateLoanDataVars memory vars;
// calculate total collateral balance for the nft
// all asset price has converted to ETH based, unit is in WEI (18 decimals)
vars.nftUnitPrice = INFTOracleGetter(nftOracle).getAssetPrice(nftAddress);
vars.totalCollateralInETH = vars.nftUnitPrice;
if (reserveAddress != address(0)) {
vars.reserveDecimals = reserveData.configuration.getDecimals();
vars.reserveUnit = 10**vars.reserveDecimals;
vars.reserveUnitPrice = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAddress);
vars.totalCollateralInReserve = (vars.totalCollateralInETH * vars.reserveUnit) / vars.reserveUnitPrice;
}
return (vars.totalCollateralInETH, vars.totalCollateralInReserve);
}
/**
* @dev Calculates the health factor from the corresponding balances
* @param totalCollateral The total collateral
* @param totalDebt The total debt
* @param liquidationThreshold The avg liquidation threshold
* @return The health factor calculated from the balances provided
**/
function calculateHealthFactorFromBalances(
uint256 totalCollateral,
uint256 totalDebt,
uint256 liquidationThreshold
) internal pure returns (uint256) {
if (totalDebt == 0) return type(uint256).max;
return (totalCollateral.percentMul(liquidationThreshold)).wadDiv(totalDebt);
}
/**
* @dev Calculates the equivalent amount that an user can borrow, depending on the available collateral and the
* average Loan To Value
* @param totalCollateral The total collateral
* @param totalDebt The total borrow balance
* @param ltv The average loan to value
* @return the amount available to borrow for the user
**/
function calculateAvailableBorrows(
uint256 totalCollateral,
uint256 totalDebt,
uint256 ltv
) internal pure returns (uint256) {
uint256 availableBorrows = totalCollateral.percentMul(ltv);
if (availableBorrows < totalDebt) {
return 0;
}
availableBorrows = availableBorrows - totalDebt;
return availableBorrows;
}
struct CalcLiquidatePriceLocalVars {
uint256 ltv;
uint256 liquidationThreshold;
uint256 liquidationBonus;
uint256 nftPriceInETH;
uint256 nftPriceInReserve;
uint256 reserveDecimals;
uint256 reservePriceInETH;
uint256 thresholdPrice;
uint256 liquidatePrice;
uint256 borrowAmount;
}
function calculateLoanLiquidatePrice(
uint256 loanId,
address reserveAsset,
DataTypes.ReserveData storage reserveData,
address nftAsset,
DataTypes.NftData storage nftData,
address poolLoan,
address reserveOracle,
address nftOracle
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
CalcLiquidatePriceLocalVars memory vars;
/*
* 0 CR LH 100
* |___________________|___________________|___________________|
* < Borrowing with Interest <
* CR: Callteral Ratio;
* LH: Liquidate Threshold;
* Liquidate Trigger: Borrowing with Interest > thresholdPrice;
* Liquidate Price: (100% - BonusRatio) * NFT Price;
*/
vars.reserveDecimals = reserveData.configuration.getDecimals();
(, vars.borrowAmount) = ILendPoolLoan(poolLoan).getLoanReserveBorrowAmount(loanId);
(vars.ltv, vars.liquidationThreshold, vars.liquidationBonus) = nftData.configuration.getCollateralParams();
vars.nftPriceInETH = INFTOracleGetter(nftOracle).getAssetPrice(nftAsset);
vars.reservePriceInETH = IReserveOracleGetter(reserveOracle).getAssetPrice(reserveAsset);
vars.nftPriceInReserve = ((10**vars.reserveDecimals) * vars.nftPriceInETH) / vars.reservePriceInETH;
vars.thresholdPrice = vars.nftPriceInReserve.percentMul(vars.liquidationThreshold);
vars.liquidatePrice = vars.nftPriceInReserve.percentMul(PercentageMath.PERCENTAGE_FACTOR - vars.liquidationBonus);
return (vars.borrowAmount, vars.thresholdPrice, vars.liquidatePrice);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
/**
* @title PercentageMath library
* @author Bend
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
uint256 constant ONE_PERCENT = 1e2; //100, 1%
uint256 constant TEN_PERCENT = 1e3; //1000, 10%
uint256 constant ONE_THOUSANDTH_PERCENT = 1e1; //10, 0.1%
uint256 constant ONE_TEN_THOUSANDTH_PERCENT = 1; //1, 0.01%
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) {
require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO);
uint256 halfPercentage = percentage / 2;
require(value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {IBToken} from "../../interfaces/IBToken.sol";
import {IDebtToken} from "../../interfaces/IDebtToken.sol";
import {IInterestRate} from "../../interfaces/IInterestRate.sol";
import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol";
import {MathUtils} from "../math/MathUtils.sol";
import {WadRayMath} from "../math/WadRayMath.sol";
import {PercentageMath} from "../math/PercentageMath.sol";
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
/**
* @title ReserveLogic library
* @author Bend
* @notice Implements the logic to update the reserves state
*/
library ReserveLogic {
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/**
* @dev Emitted when the state of a reserve is updated
* @param asset The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed asset,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
using ReserveLogic for DataTypes.ReserveData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
/**
* @dev Returns the ongoing normalized income for the reserve
* A value of 1e27 means there is no income. As time passes, the income is accrued
* A value of 2*1e27 means for each unit of asset one unit of income has been accrued
* @param reserve The reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) {
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.liquidityIndex;
}
uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(
reserve.liquidityIndex
);
return cumulated;
}
/**
* @dev Returns the ongoing normalized variable debt for the reserve
* A value of 1e27 means there is no debt. As time passes, the income is accrued
* A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated
* @param reserve The reserve object
* @return The normalized variable debt. expressed in ray
**/
function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) {
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.variableBorrowIndex;
}
uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex,
lastUpdatedTimestamp
);
}
/**
* @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate
* the flashloan fee to the reserve, and spread it between all the depositors
* @param reserve The reserve object
* @param totalLiquidity The total liquidity available in the reserve
* @param amount The amount to accomulate
**/
function cumulateToLiquidityIndex(
DataTypes.ReserveData storage reserve,
uint256 totalLiquidity,
uint256 amount
) internal {
uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay());
uint256 result = amountToLiquidityRatio + (WadRayMath.ray());
result = result.rayMul(reserve.liquidityIndex);
require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(result);
}
/**
* @dev Initializes a reserve
* @param reserve The reserve object
* @param bTokenAddress The address of the overlying bToken contract
* @param debtTokenAddress The address of the overlying debtToken contract
* @param interestRateAddress The address of the interest rate strategy contract
**/
function init(
DataTypes.ReserveData storage reserve,
address bTokenAddress,
address debtTokenAddress,
address interestRateAddress
) external {
require(reserve.bTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
reserve.liquidityIndex = uint128(WadRayMath.ray());
reserve.variableBorrowIndex = uint128(WadRayMath.ray());
reserve.bTokenAddress = bTokenAddress;
reserve.debtTokenAddress = debtTokenAddress;
reserve.interestRateAddress = interestRateAddress;
}
struct UpdateInterestRatesLocalVars {
uint256 availableLiquidity;
uint256 newLiquidityRate;
uint256 newVariableRate;
uint256 totalVariableDebt;
}
/**
* @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate
* @param reserve The address of the reserve to be updated
* @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param liquidityTaken The amount of liquidity taken from the protocol (withdraw or borrow)
**/
function updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address bTokenAddress,
uint256 liquidityAdded,
uint256 liquidityTaken
) internal {
UpdateInterestRatesLocalVars memory vars;
//calculates the total variable debt locally using the scaled borrow amount instead
//of borrow amount(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IDebtToken(reserve.debtTokenAddress).scaledTotalSupply().rayMul(
reserve.variableBorrowIndex
);
(vars.newLiquidityRate, vars.newVariableRate) = IInterestRate(reserve.interestRateAddress).calculateInterestRates(
reserveAddress,
bTokenAddress,
liquidityAdded,
liquidityTaken,
vars.totalVariableDebt,
reserve.configuration.getReserveFactor()
);
require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);
require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
struct MintToTreasuryLocalVars {
uint256 currentVariableDebt;
uint256 previousVariableDebt;
uint256 totalDebtAccrued;
uint256 amountToMint;
uint256 reserveFactor;
}
/**
* @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the
* specific asset.
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The current scaled total variable debt
* @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest
* @param newLiquidityIndex The new liquidity index
* @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest
**/
function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 previousVariableBorrowIndex,
uint256 newLiquidityIndex,
uint256 newVariableBorrowIndex,
uint40 timestamp
) internal {
timestamp;
MintToTreasuryLocalVars memory vars;
vars.reserveFactor = reserve.configuration.getReserveFactor();
if (vars.reserveFactor == 0) {
return;
}
//calculate the last principal variable debt
vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);
//calculate the new total supply after accumulation of the index
vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);
//debt accrued is the sum of the current debt minus the sum of the debt at the last update
vars.totalDebtAccrued = vars.currentVariableDebt - (vars.previousVariableDebt);
vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);
if (vars.amountToMint != 0) {
IBToken(reserve.bTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);
}
}
/**
* @dev Updates the reserve indexes and the timestamp of the update
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The scaled variable debt
* @param liquidityIndex The last stored liquidity index
* @param variableBorrowIndex The last stored variable borrow index
**/
function _updateIndexes(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 timestamp
) internal returns (uint256, uint256) {
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 newLiquidityIndex = liquidityIndex;
uint256 newVariableBorrowIndex = variableBorrowIndex;
//only cumulating if there is any income being produced
if (currentLiquidityRate > 0) {
uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);
newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);
require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(newLiquidityIndex);
//as the liquidity rate might come only from stable rate loans, we need to ensure
//that there is actual variable debt before accumulating
if (scaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(
reserve.currentVariableBorrowRate,
timestamp
);
newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);
require(newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW);
reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);
}
}
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
return (newLiquidityIndex, newVariableBorrowIndex);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
/**
* @title NftLogic library
* @author Bend
* @notice Implements the logic to update the nft state
*/
library NftLogic {
/**
* @dev Initializes a nft
* @param nft The nft object
* @param bNftAddress The address of the bNFT contract
**/
function init(DataTypes.NftData storage nft, address bNftAddress) external {
require(nft.bNftAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
nft.bNftAddress = bNftAddress;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {ReserveLogic} from "./ReserveLogic.sol";
import {GenericLogic} from "./GenericLogic.sol";
import {WadRayMath} from "../math/WadRayMath.sol";
import {PercentageMath} from "../math/PercentageMath.sol";
import {ReserveConfiguration} from "../configuration/ReserveConfiguration.sol";
import {NftConfiguration} from "../configuration/NftConfiguration.sol";
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
import {IInterestRate} from "../../interfaces/IInterestRate.sol";
import {ILendPoolLoan} from "../../interfaces/ILendPoolLoan.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
/**
* @title ValidationLogic library
* @author Bend
* @notice Implements functions to validate the different actions of the protocol
*/
library ValidationLogic {
using ReserveLogic for DataTypes.ReserveData;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using NftConfiguration for DataTypes.NftConfigurationMap;
/**
* @dev Validates a deposit action
* @param reserve The reserve object on which the user is depositing
* @param amount The amount to be deposited
*/
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {
(bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags();
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!isFrozen, Errors.VL_RESERVE_FROZEN);
}
/**
* @dev Validates a withdraw action
* @param reserveData The reserve state
* @param amount The amount to be withdrawn
* @param userBalance The balance of the user
*/
function validateWithdraw(
DataTypes.ReserveData storage reserveData,
uint256 amount,
uint256 userBalance
) external view {
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);
(bool isActive, , , ) = reserveData.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
}
struct ValidateBorrowLocalVars {
uint256 currentLtv;
uint256 currentLiquidationThreshold;
uint256 amountOfCollateralNeeded;
uint256 userCollateralBalance;
uint256 userBorrowBalance;
uint256 availableLiquidity;
uint256 healthFactor;
bool isActive;
bool isFrozen;
bool borrowingEnabled;
bool stableRateBorrowingEnabled;
bool nftIsActive;
bool nftIsFrozen;
address loanReserveAsset;
address loanBorrower;
}
/**
* @dev Validates a borrow action
* @param reserveAsset The address of the asset to borrow
* @param amount The amount to be borrowed
* @param reserveData The reserve state from which the user is borrowing
* @param nftData The state of the user for the specific nft
*/
function validateBorrow(
address user,
address reserveAsset,
uint256 amount,
DataTypes.ReserveData storage reserveData,
address nftAsset,
DataTypes.NftData storage nftData,
address loanAddress,
uint256 loanId,
address reserveOracle,
address nftOracle
) external view {
ValidateBorrowLocalVars memory vars;
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(amount > 0, Errors.VL_INVALID_AMOUNT);
if (loanId != 0) {
DataTypes.LoanData memory loanData = ILendPoolLoan(loanAddress).getLoan(loanId);
require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE);
require(reserveAsset == loanData.reserveAsset, Errors.VL_SPECIFIED_RESERVE_NOT_BORROWED_BY_USER);
require(user == loanData.borrower, Errors.VL_SPECIFIED_LOAN_NOT_BORROWED_BY_USER);
}
(vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserveData
.configuration
.getFlags();
require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);
require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);
(vars.nftIsActive, vars.nftIsFrozen) = nftData.configuration.getFlags();
require(vars.nftIsActive, Errors.VL_NO_ACTIVE_NFT);
require(!vars.nftIsFrozen, Errors.VL_NFT_FROZEN);
(vars.currentLtv, vars.currentLiquidationThreshold, ) = nftData.configuration.getCollateralParams();
(vars.userCollateralBalance, vars.userBorrowBalance, vars.healthFactor) = GenericLogic.calculateLoanData(
reserveAsset,
reserveData,
nftAsset,
nftData,
loanAddress,
loanId,
reserveOracle,
nftOracle
);
require(vars.userCollateralBalance > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);
require(
vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD
);
//add the current already borrowed amount to the amount requested to calculate the total collateral needed.
//LTV is calculated in percentage
vars.amountOfCollateralNeeded = (vars.userBorrowBalance + amount).percentDiv(vars.currentLtv);
require(vars.amountOfCollateralNeeded <= vars.userCollateralBalance, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW);
}
/**
* @dev Validates a repay action
* @param reserveData The reserve state from which the user is repaying
* @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)
* @param borrowAmount The borrow balance of the user
*/
function validateRepay(
DataTypes.ReserveData storage reserveData,
DataTypes.NftData storage nftData,
DataTypes.LoanData memory loanData,
uint256 amountSent,
uint256 borrowAmount
) external view {
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);
require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);
require(amountSent > 0, Errors.VL_INVALID_AMOUNT);
require(borrowAmount > 0, Errors.VL_NO_DEBT_OF_SELECTED_TYPE);
require(loanData.state == DataTypes.LoanState.Active, Errors.LPL_INVALID_LOAN_STATE);
}
/**
* @dev Validates the auction action
* @param reserveData The reserve data of the principal
* @param nftData The nft data of the underlying nft
* @param bidPrice Total variable debt balance of the user
**/
function validateAuction(
DataTypes.ReserveData storage reserveData,
DataTypes.NftData storage nftData,
DataTypes.LoanData memory loanData,
uint256 bidPrice
) internal view {
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);
require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);
require(
loanData.state == DataTypes.LoanState.Active || loanData.state == DataTypes.LoanState.Auction,
Errors.LPL_INVALID_LOAN_STATE
);
require(bidPrice > 0, Errors.VL_INVALID_AMOUNT);
}
/**
* @dev Validates a redeem action
* @param reserveData The reserve state
* @param nftData The nft state
*/
function validateRedeem(
DataTypes.ReserveData storage reserveData,
DataTypes.NftData storage nftData,
DataTypes.LoanData memory loanData,
uint256 amount
) external view {
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);
require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);
require(loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE);
require(loanData.bidderAddress != address(0), Errors.LPL_INVALID_BIDDER_ADDRESS);
uint256 bidFine = loanData.bidPrice.percentMul(nftData.configuration.getRedeemFine());
require(amount > bidFine, Errors.LPL_AMOUNT_LESS_THAN_BID_FINE);
}
/**
* @dev Validates the liquidation action
* @param reserveData The reserve data of the principal
* @param nftData The data of the underlying NFT
* @param loanData The loan data of the underlying NFT
**/
function validateLiquidate(
DataTypes.ReserveData storage reserveData,
DataTypes.NftData storage nftData,
DataTypes.LoanData memory loanData
) internal view {
require(nftData.bNftAddress != address(0), Errors.LPC_INVALIED_BNFT_ADDRESS);
require(reserveData.bTokenAddress != address(0), Errors.VL_INVALID_RESERVE_ADDRESS);
require(reserveData.configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE);
require(nftData.configuration.getActive(), Errors.VL_NO_ACTIVE_NFT);
require(loanData.state == DataTypes.LoanState.Auction, Errors.LPL_INVALID_LOAN_STATE);
require(loanData.bidderAddress != address(0), Errors.LPL_INVALID_BIDDER_ADDRESS);
}
/**
* @dev Validates an bToken transfer
* @param from The user from which the bTokens are being transferred
* @param reserveData The state of the reserve
*/
function validateTransfer(address from, DataTypes.ReserveData storage reserveData) internal pure {
from;
reserveData;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
/**
* @title ReserveConfiguration library
* @author Bend
* @notice Implements the bitmap logic to handle the reserve configuration
*/
library ReserveConfiguration {
uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore
uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore
uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore
uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore
uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore
uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore
/// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;
uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;
uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;
uint256 constant MAX_VALID_LTV = 65535;
uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;
uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;
uint256 constant MAX_VALID_DECIMALS = 255;
uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;
/**
* @dev Sets the Loan to Value of the reserve
* @param self The reserve configuration
* @param ltv the new ltv
**/
function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {
require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);
self.data = (self.data & LTV_MASK) | ltv;
}
/**
* @dev Gets the Loan to Value of the reserve
* @param self The reserve configuration
* @return The loan to value
**/
function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return self.data & ~LTV_MASK;
}
/**
* @dev Sets the liquidation threshold of the reserve
* @param self The reserve configuration
* @param threshold The new liquidation threshold
**/
function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure {
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);
self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation threshold of the reserve
* @param self The reserve configuration
* @return The liquidation threshold
**/
function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
}
/**
* @dev Sets the liquidation bonus of the reserve
* @param self The reserve configuration
* @param bonus The new liquidation bonus
**/
function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure {
require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);
self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation bonus of the reserve
* @param self The reserve configuration
* @return The liquidation bonus
**/
function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
}
/**
* @dev Sets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @param decimals The decimals
**/
function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure {
require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);
self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);
}
/**
* @dev Gets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @return The decimals of the asset
**/
function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;
}
/**
* @dev Sets the active state of the reserve
* @param self The reserve configuration
* @param active The active state
**/
function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {
self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);
}
/**
* @dev Gets the active state of the reserve
* @param self The reserve configuration
* @return The active state
**/
function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~ACTIVE_MASK) != 0;
}
/**
* @dev Sets the frozen state of the reserve
* @param self The reserve configuration
* @param frozen The frozen state
**/
function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {
self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);
}
/**
* @dev Gets the frozen state of the reserve
* @param self The reserve configuration
* @return The frozen state
**/
function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
/**
* @dev Enables or disables borrowing on the reserve
* @param self The reserve configuration
* @param enabled True if the borrowing needs to be enabled, false otherwise
**/
function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {
self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);
}
/**
* @dev Gets the borrowing state of the reserve
* @param self The reserve configuration
* @return The borrowing state
**/
function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~BORROWING_MASK) != 0;
}
/**
* @dev Enables or disables stable rate borrowing on the reserve
* @param self The reserve configuration
* @param enabled True if the stable rate borrowing needs to be enabled, false otherwise
**/
function setStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure {
self.data =
(self.data & STABLE_BORROWING_MASK) |
(uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);
}
/**
* @dev Gets the stable rate borrowing state of the reserve
* @param self The reserve configuration
* @return The stable rate borrowing state
**/
function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~STABLE_BORROWING_MASK) != 0;
}
/**
* @dev Sets the reserve factor of the reserve
* @param self The reserve configuration
* @param reserveFactor The reserve factor
**/
function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure {
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);
self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);
}
/**
* @dev Gets the reserve factor of the reserve
* @param self The reserve configuration
* @return The reserve factor
**/
function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;
}
/**
* @dev Gets the configuration flags of the reserve
* @param self The reserve configuration
* @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
**/
function getFlags(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
bool,
bool,
bool,
bool
)
{
uint256 dataLocal = self.data;
return (
(dataLocal & ~ACTIVE_MASK) != 0,
(dataLocal & ~FROZEN_MASK) != 0,
(dataLocal & ~BORROWING_MASK) != 0,
(dataLocal & ~STABLE_BORROWING_MASK) != 0
);
}
/**
* @dev Gets the configuration paramters of the reserve
* @param self The reserve configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
**/
function getParams(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
dataLocal & ~LTV_MASK,
(dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
/**
* @dev Gets the configuration paramters of the reserve from a memory object
* @param self The reserve configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
**/
function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
self.data & ~LTV_MASK,
(self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
/**
* @dev Gets the configuration flags of the reserve from a memory object
* @param self The reserve configuration
* @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
**/
function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
bool,
bool,
bool,
bool
)
{
return (
(self.data & ~ACTIVE_MASK) != 0,
(self.data & ~FROZEN_MASK) != 0,
(self.data & ~BORROWING_MASK) != 0,
(self.data & ~STABLE_BORROWING_MASK) != 0
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {Errors} from "../helpers/Errors.sol";
import {DataTypes} from "../types/DataTypes.sol";
/**
* @title NftConfiguration library
* @author Bend
* @notice Implements the bitmap logic to handle the NFT configuration
*/
library NftConfiguration {
uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore
uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore
uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore
uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant REDEEM_DURATION_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant AUCTION_DURATION_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant REDEEM_FINE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant REDEEM_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore
/// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
uint256 constant REDEEM_DURATION_START_BIT_POSITION = 64;
uint256 constant AUCTION_DURATION_START_BIT_POSITION = 72;
uint256 constant REDEEM_FINE_START_BIT_POSITION = 80;
uint256 constant REDEEM_THRESHOLD_START_BIT_POSITION = 96;
uint256 constant MAX_VALID_LTV = 65535;
uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;
uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;
uint256 constant MAX_VALID_REDEEM_DURATION = 255;
uint256 constant MAX_VALID_AUCTION_DURATION = 255;
uint256 constant MAX_VALID_REDEEM_FINE = 65535;
uint256 constant MAX_VALID_REDEEM_THRESHOLD = 65535;
/**
* @dev Sets the Loan to Value of the NFT
* @param self The NFT configuration
* @param ltv the new ltv
**/
function setLtv(DataTypes.NftConfigurationMap memory self, uint256 ltv) internal pure {
require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);
self.data = (self.data & LTV_MASK) | ltv;
}
/**
* @dev Gets the Loan to Value of the NFT
* @param self The NFT configuration
* @return The loan to value
**/
function getLtv(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return self.data & ~LTV_MASK;
}
/**
* @dev Sets the liquidation threshold of the NFT
* @param self The NFT configuration
* @param threshold The new liquidation threshold
**/
function setLiquidationThreshold(DataTypes.NftConfigurationMap memory self, uint256 threshold) internal pure {
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);
self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation threshold of the NFT
* @param self The NFT configuration
* @return The liquidation threshold
**/
function getLiquidationThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
}
/**
* @dev Sets the liquidation bonus of the NFT
* @param self The NFT configuration
* @param bonus The new liquidation bonus
**/
function setLiquidationBonus(DataTypes.NftConfigurationMap memory self, uint256 bonus) internal pure {
require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);
self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation bonus of the NFT
* @param self The NFT configuration
* @return The liquidation bonus
**/
function getLiquidationBonus(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
}
/**
* @dev Sets the active state of the NFT
* @param self The NFT configuration
* @param active The active state
**/
function setActive(DataTypes.NftConfigurationMap memory self, bool active) internal pure {
self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);
}
/**
* @dev Gets the active state of the NFT
* @param self The NFT configuration
* @return The active state
**/
function getActive(DataTypes.NftConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~ACTIVE_MASK) != 0;
}
/**
* @dev Sets the frozen state of the NFT
* @param self The NFT configuration
* @param frozen The frozen state
**/
function setFrozen(DataTypes.NftConfigurationMap memory self, bool frozen) internal pure {
self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);
}
/**
* @dev Gets the frozen state of the NFT
* @param self The NFT configuration
* @return The frozen state
**/
function getFrozen(DataTypes.NftConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
/**
* @dev Sets the redeem duration of the NFT
* @param self The NFT configuration
* @param redeemDuration The redeem duration
**/
function setRedeemDuration(DataTypes.NftConfigurationMap memory self, uint256 redeemDuration) internal pure {
require(redeemDuration <= MAX_VALID_REDEEM_DURATION, Errors.RC_INVALID_REDEEM_DURATION);
self.data = (self.data & REDEEM_DURATION_MASK) | (redeemDuration << REDEEM_DURATION_START_BIT_POSITION);
}
/**
* @dev Gets the redeem duration of the NFT
* @param self The NFT configuration
* @return The redeem duration
**/
function getRedeemDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION;
}
/**
* @dev Sets the auction duration of the NFT
* @param self The NFT configuration
* @param auctionDuration The auction duration
**/
function setAuctionDuration(DataTypes.NftConfigurationMap memory self, uint256 auctionDuration) internal pure {
require(auctionDuration <= MAX_VALID_AUCTION_DURATION, Errors.RC_INVALID_AUCTION_DURATION);
self.data = (self.data & AUCTION_DURATION_MASK) | (auctionDuration << AUCTION_DURATION_START_BIT_POSITION);
}
/**
* @dev Gets the auction duration of the NFT
* @param self The NFT configuration
* @return The auction duration
**/
function getAuctionDuration(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION;
}
/**
* @dev Sets the redeem fine of the NFT
* @param self The NFT configuration
* @param redeemFine The redeem duration
**/
function setRedeemFine(DataTypes.NftConfigurationMap memory self, uint256 redeemFine) internal pure {
require(redeemFine <= MAX_VALID_REDEEM_FINE, Errors.RC_INVALID_REDEEM_FINE);
self.data = (self.data & REDEEM_FINE_MASK) | (redeemFine << REDEEM_FINE_START_BIT_POSITION);
}
/**
* @dev Gets the redeem fine of the NFT
* @param self The NFT configuration
* @return The redeem fine
**/
function getRedeemFine(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION;
}
/**
* @dev Sets the redeem threshold of the NFT
* @param self The NFT configuration
* @param redeemThreshold The redeem duration
**/
function setRedeemThreshold(DataTypes.NftConfigurationMap memory self, uint256 redeemThreshold) internal pure {
require(redeemThreshold <= MAX_VALID_REDEEM_THRESHOLD, Errors.RC_INVALID_REDEEM_THRESHOLD);
self.data = (self.data & REDEEM_THRESHOLD_MASK) | (redeemThreshold << REDEEM_THRESHOLD_START_BIT_POSITION);
}
/**
* @dev Gets the redeem threshold of the NFT
* @param self The NFT configuration
* @return The redeem threshold
**/
function getRedeemThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) {
return (self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION;
}
/**
* @dev Gets the configuration flags of the NFT
* @param self The NFT configuration
* @return The state flags representing active, frozen
**/
function getFlags(DataTypes.NftConfigurationMap storage self) internal view returns (bool, bool) {
uint256 dataLocal = self.data;
return ((dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0);
}
/**
* @dev Gets the configuration flags of the NFT from a memory object
* @param self The NFT configuration
* @return The state flags representing active, frozen
**/
function getFlagsMemory(DataTypes.NftConfigurationMap memory self) internal pure returns (bool, bool) {
return ((self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0);
}
/**
* @dev Gets the collateral configuration paramters of the NFT
* @param self The NFT configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus
**/
function getCollateralParams(DataTypes.NftConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
dataLocal & ~LTV_MASK,
(dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION
);
}
/**
* @dev Gets the auction configuration paramters of the NFT
* @param self The NFT configuration
* @return The state params representing redeem duration, auction duration, redeem fine
**/
function getAuctionParams(DataTypes.NftConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
(dataLocal & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION,
(dataLocal & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION,
(dataLocal & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION,
(dataLocal & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION
);
}
/**
* @dev Gets the collateral configuration paramters of the NFT from a memory object
* @param self The NFT configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus
**/
function getCollateralParamsMemory(DataTypes.NftConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256
)
{
return (
self.data & ~LTV_MASK,
(self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION
);
}
/**
* @dev Gets the auction configuration paramters of the NFT from a memory object
* @param self The NFT configuration
* @return The state params representing redeem duration, auction duration, redeem fine
**/
function getAuctionParamsMemory(DataTypes.NftConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256,
uint256
)
{
return (
(self.data & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION,
(self.data & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION,
(self.data & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION,
(self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
library DataTypes {
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address bTokenAddress;
address debtTokenAddress;
//address of the interest rate strategy
address interestRateAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct NftData {
//stores the nft configuration
NftConfigurationMap configuration;
//address of the bNFT contract
address bNftAddress;
//the id of the nft. Represents the position in the list of the active nfts
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct NftConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 56: NFT is active
//bit 57: NFT is frozen
uint256 data;
}
/**
* @dev Enum describing the current state of a loan
* State change flow:
* Created -> Active -> Repaid
* -> Auction -> Defaulted
*/
enum LoanState {
// We need a default that is not 'Created' - this is the zero value
None,
// The loan data is stored, but not initiated yet.
Created,
// The loan has been initialized, funds have been delivered to the borrower and the collateral is held.
Active,
// The loan is in auction, higest price liquidator will got chance to claim it.
Auction,
// The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state.
Repaid,
// The loan was delinquent and collateral claimed by the liquidator. This is a terminal state.
Defaulted
}
struct LoanData {
//the id of the nft loan
uint256 loanId;
//the current state of the loan
LoanState state;
//address of borrower
address borrower;
//address of nft asset token
address nftAsset;
//the id of nft token
uint256 nftTokenId;
//address of reserve asset token
address reserveAsset;
//scaled borrow amount. Expressed in ray
uint256 scaledAmount;
//start time of first bid time
uint256 bidStartTimestamp;
//bidder address of higest bid
address bidderAddress;
//price of higest bid
uint256 bidPrice;
//borrow amount of loan
uint256 bidBorrowAmount;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {DataTypes} from "../libraries/types/DataTypes.sol";
import {ReserveLogic} from "../libraries/logic/ReserveLogic.sol";
import {NftLogic} from "../libraries/logic/NftLogic.sol";
import {ILendPoolAddressesProvider} from "../interfaces/ILendPoolAddressesProvider.sol";
contract LendPoolStorage {
using ReserveLogic for DataTypes.ReserveData;
using NftLogic for DataTypes.NftData;
ILendPoolAddressesProvider internal _addressesProvider;
mapping(address => DataTypes.ReserveData) internal _reserves;
mapping(address => DataTypes.NftData) internal _nfts;
mapping(uint256 => address) internal _reservesList;
uint256 internal _reservesCount;
mapping(uint256 => address) internal _nftsList;
uint256 internal _nftsCount;
bool internal _paused;
uint256 internal _maxNumberOfReserves;
uint256 internal _maxNumberOfNfts;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// 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: 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 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 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.
*
* [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 (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 {
__Context_init_unchained();
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
interface IIncentivesController {
/**
* @dev Called by the corresponding asset on any update that affects the rewards distribution
* @param asset The address of the user
* @param totalSupply The total supply of the asset in the lending pool
* @param userBalance The balance of the user of the asset in the lending pool
**/
function handleAction(
address asset,
uint256 totalSupply,
uint256 userBalance
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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: agpl-3.0
pragma solidity 0.8.4;
/**
* @title IInterestRate interface
* @dev Interface for the calculation of the interest rates
* @author Bend
*/
interface IInterestRate {
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
address reserve,
uint256 availableLiquidity,
uint256 totalVariableDebt,
uint256 reserveFactor
) external view returns (uint256, uint256);
function calculateInterestRates(
address reserve,
address bToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalVariableDebt,
uint256 reserveFactor
) external view returns (uint256 liquidityRate, uint256 variableBorrowRate);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
import {WadRayMath} from "./WadRayMath.sol";
library MathUtils {
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) {
//solium-disable-next-line
uint256 timeDifference = block.timestamp - (uint256(lastUpdateTimestamp));
return ((rate * (timeDifference)) / SECONDS_PER_YEAR) + (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) {
//solium-disable-next-line
uint256 exp = currentTimestamp - (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 * (expMinusOne) * (basePowerTwo)) / 2;
uint256 thirdTerm = (exp * (expMinusOne) * (expMinusTwo) * (basePowerThree)) / 6;
return WadRayMath.ray() + (ratePerSecond * (exp)) + (secondTerm) + (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) {
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// 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);
} | * @dev Gets the auction configuration paramters of the NFT @param self The NFT configuration @return The state params representing redeem duration, auction duration, redeem fine/ | function getAuctionParams(DataTypes.NftConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
(dataLocal & ~REDEEM_DURATION_MASK) >> REDEEM_DURATION_START_BIT_POSITION,
(dataLocal & ~AUCTION_DURATION_MASK) >> AUCTION_DURATION_START_BIT_POSITION,
(dataLocal & ~REDEEM_FINE_MASK) >> REDEEM_FINE_START_BIT_POSITION,
(dataLocal & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION
);
}
| 503,269 | [
1,
3002,
326,
279,
4062,
1664,
579,
5432,
434,
326,
423,
4464,
225,
365,
1021,
423,
4464,
1664,
327,
1021,
919,
859,
5123,
283,
24903,
3734,
16,
279,
4062,
3734,
16,
283,
24903,
11079,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
4506,
4062,
1370,
12,
751,
2016,
18,
50,
1222,
1750,
863,
2502,
365,
13,
203,
565,
2713,
203,
565,
1476,
203,
565,
1135,
261,
203,
1377,
2254,
5034,
16,
203,
1377,
2254,
5034,
16,
203,
1377,
2254,
5034,
16,
203,
1377,
2254,
5034,
203,
565,
262,
203,
225,
288,
203,
565,
2254,
5034,
501,
2042,
273,
365,
18,
892,
31,
203,
203,
565,
327,
261,
203,
1377,
261,
892,
2042,
473,
4871,
862,
1639,
3375,
67,
24951,
67,
11704,
13,
1671,
2438,
1639,
3375,
67,
24951,
67,
7570,
67,
15650,
67,
15258,
16,
203,
1377,
261,
892,
2042,
473,
4871,
14237,
3106,
67,
24951,
67,
11704,
13,
1671,
432,
27035,
67,
24951,
67,
7570,
67,
15650,
67,
15258,
16,
203,
1377,
261,
892,
2042,
473,
4871,
862,
1639,
3375,
67,
42,
3740,
67,
11704,
13,
1671,
2438,
1639,
3375,
67,
42,
3740,
67,
7570,
67,
15650,
67,
15258,
16,
203,
1377,
261,
892,
2042,
473,
4871,
862,
1639,
3375,
67,
23840,
67,
11704,
13,
1671,
2438,
1639,
3375,
67,
23840,
67,
7570,
67,
15650,
67,
15258,
203,
565,
11272,
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
] |
./partial_match/1/0x0eE3C7249D5E6b05162bd2A632df652Af0f38eca/sources/PoofyLand.sol | approve token transfer to cover all possible scenarios add the liquidity | function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
operationaddress,
block.timestamp
);
}
| 3,983,593 | [
1,
12908,
537,
1147,
7412,
358,
5590,
777,
3323,
22456,
527,
326,
4501,
372,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
48,
18988,
24237,
12,
11890,
5034,
1147,
6275,
16,
2254,
5034,
13750,
6275,
13,
3238,
288,
203,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
1147,
6275,
1769,
203,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1147,
6275,
16,
203,
5411,
1674,
2867,
16,
203,
5411,
1203,
18,
5508,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.